mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 16:04:24 +00:00
Merge main (#7618 platform catalog + provider profile) into feature/composite-ollama-unified
解决与 #7618 的 51 个文件冲突,并把 ollama_cloud 接入平台清单与 provider profile: - domain/platforms.go 登记 ollama_cloud(OpenAI 网关,LiteLLMProvider 留空); provider_profile.go 登记 by_inbound profile(legacy/credits 两模式共用端点), 新增 ProviderProfile.DefaultAPIProtocol 表达未配置时默认 adaptive。 - 删除 #7114 手写的约 30 处平台清单/switch,改用清单派生(AllowedQuotaPlatforms、 binding 校验、调度快照、组合分组、路由 dispatcher、前端平台选项/配色/配额等)。 - 迁移 242_ollama_cloud_platform 改为 243_ollama_cloud_channel_monitor_provider: 只放宽渠道监控 provider CHECK,不再重建 #7618 删除的两个平台 CHECK(否则 command_code/cline 写入失败)。 - compositeOwnershipQueryPlatforms 改为平台清单派生,修复 command_code/cline 账号在组合分组归属扫描中被漏掉。 - 连接测试:ollama_cloud 专属路径先于按入站协议分流的通用分支。 - nativeAnthropicMessagesURL:版本感知拼接对 ollama_cloud 生效,国产厂商保持朴素拼接。 - GetOpenAIBaseURL 保留多协议账号不回落 api.openai.com 的护栏。 - 前端:ollama_cloud 保留专属表单(双额度模式 + 月度信用额度),从通用表单与 通用平台按钮中排除;端点常量改读平台清单;配额弹窗/设置页保留未知平台行护栏。 - 重新生成 platformCatalog.builtin.json;同步相关测试基准。
This commit is contained in:
commit
25af9b1dd2
146 files changed
+13778
-1343
No files matched your search
@@ -35,7 +35,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.0'
|
||||
go version | grep -q 'go1.27.2'
|
||||
- name: Unit tests
|
||||
working-directory: backend
|
||||
run: make test-unit
|
||||
@@ -75,11 +75,11 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.0'
|
||||
go version | grep -q 'go1.27.2'
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
version: v2.13
|
||||
version: v2.14.0
|
||||
args: --timeout=30m
|
||||
working-directory: backend
|
||||
|
||||
|
||||
@@ -137,7 +137,7 @@ jobs:
|
||||
check-latest: false
|
||||
cache: false
|
||||
- name: Verify Go version
|
||||
run: go version | grep -q 'go1.27.0'
|
||||
run: go version | grep -q 'go1.27.2'
|
||||
- name: Restore target-specific Go cache
|
||||
id: go-cache
|
||||
uses: actions/cache/restore@v6
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.0'
|
||||
go version | grep -q 'go1.27.2'
|
||||
- name: Run govulncheck
|
||||
working-directory: backend
|
||||
run: |
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
# =============================================================================
|
||||
|
||||
ARG NODE_IMAGE=node:24-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.27.0-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.27.2-alpine
|
||||
ARG ALPINE_IMAGE=alpine:3.21
|
||||
ARG POSTGRES_IMAGE=postgres:18-alpine
|
||||
ARG GOPROXY=https://goproxy.cn,direct
|
||||
|
||||
@@ -8,6 +8,12 @@ FRONTEND_CRITICAL_VITEST := \
|
||||
src/components/account/__tests__/OpenAIReferralCell.spec.ts \
|
||||
src/components/account/__tests__/OpenAIReferralCell.transport.spec.ts \
|
||||
src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts \
|
||||
src/constants/__tests__/platforms.spec.ts \
|
||||
src/components/account/__tests__/credentialsBuilder.platformCatalog.spec.ts \
|
||||
src/components/account/__tests__/CreateAccountModal.spec.ts \
|
||||
src/components/account/__tests__/EditAccountModal.spec.ts \
|
||||
src/components/account/__tests__/credentialsBuilder.spec.ts \
|
||||
src/components/account/__tests__/OpenCodeGoProtocolRulesEditor.spec.ts \
|
||||
src/components/keys/__tests__/BulkEditKeysModal.spec.ts \
|
||||
src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts \
|
||||
src/views/user/__tests__/KeysView.spec.ts \
|
||||
|
||||
@@ -123,6 +123,15 @@ linters:
|
||||
|
||||
exclusions:
|
||||
rules:
|
||||
# x/net v0.60 deprecated the HTTP/2 compatibility adapters. Keep their
|
||||
# existing per-protocol idle timeout and PING configuration in this CI fix.
|
||||
- path: 'internal/(repository/http_upstream(_http2_keepalive_test)?|server/http)\.go$'
|
||||
linters: [ staticcheck ]
|
||||
text: 'SA1019: (\(golang\.org/x/net/http2\.(Server|Transport)\)\.|golang\.org/x/net/http2\.(ConfigureServer|ConfigureTransports|Server|Transport)\b)'
|
||||
# Upstream libraries can still return the legacy typed GOAWAY error.
|
||||
- path: 'internal/service/openai_codex_models_service(_test)?\.go$'
|
||||
linters: [ staticcheck ]
|
||||
text: 'SA1019: golang\.org/x/net/http2\.GoAwayError\b'
|
||||
# G703/G704 污点分析在测试文件中只会命中 httptest mock 与测试者自设的
|
||||
# 环境变量路径,不构成攻击面;且该分析跨环境结果不稳定(本地/CI 报告的
|
||||
# 位置集合不同),逐点 nolint 无法收敛,故按路径豁免。生产代码不豁免,
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.27.0-alpine
|
||||
FROM golang:1.27.2-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
@@ -906,7 +906,21 @@ func init() {
|
||||
// compositemodelroute.DefaultTargetPlatform holds the default value on creation for the target_platform field.
|
||||
compositemodelroute.DefaultTargetPlatform = compositemodelrouteDescTargetPlatform.Default.(string)
|
||||
// compositemodelroute.TargetPlatformValidator is a validator for the "target_platform" field. It is called by the builders before save.
|
||||
compositemodelroute.TargetPlatformValidator = compositemodelrouteDescTargetPlatform.Validators[0].(func(string) error)
|
||||
compositemodelroute.TargetPlatformValidator = func() func(string) error {
|
||||
validators := compositemodelrouteDescTargetPlatform.Validators
|
||||
fns := [...]func(string) error{
|
||||
validators[0].(func(string) error),
|
||||
validators[1].(func(string) error),
|
||||
}
|
||||
return func(target_platform string) error {
|
||||
for _, fn := range fns {
|
||||
if err := fn(target_platform); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}()
|
||||
// compositemodelrouteDescUpstreamModel is the schema descriptor for upstream_model field.
|
||||
compositemodelrouteDescUpstreamModel := compositemodelrouteFields[4].Descriptor()
|
||||
// compositemodelroute.DefaultUpstreamModel holds the default value on creation for the upstream_model field.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
|
||||
@@ -45,6 +47,13 @@ func (CompositeModelRoute) Fields() []ent.Field {
|
||||
field.String("target_platform").
|
||||
MaxLen(50).
|
||||
Default(domain.PlatformOpenAI).
|
||||
Validate(func(s string) error {
|
||||
// 目标平台须为平台清单中的具体平台;数据库不再维护 CHECK 约束。
|
||||
if !domain.IsConcretePlatform(s) {
|
||||
return fmt.Errorf("target_platform %q is not a concrete platform", s)
|
||||
}
|
||||
return nil
|
||||
}).
|
||||
Comment("Concrete provider platform."),
|
||||
field.String("upstream_model").
|
||||
MaxLen(200).
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"entgo.io/ent/schema/field"
|
||||
"entgo.io/ent/schema/index"
|
||||
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
)
|
||||
|
||||
// UserPlatformQuota holds the schema definition for per-user per-platform quota.
|
||||
@@ -38,16 +39,12 @@ func (UserPlatformQuota) Fields() []ent.Field {
|
||||
MaxLen(32).
|
||||
NotEmpty().
|
||||
Validate(func(s string) error {
|
||||
// 注意:平台列表的单一权威源为 service.AllowedQuotaPlatforms;
|
||||
// 此处为 ent 构建期约束,需与 service.AllowedQuotaPlatforms 保持同步。
|
||||
switch s {
|
||||
case "anthropic", "openai", "gemini", "antigravity", "grok",
|
||||
"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe",
|
||||
"ollama_cloud":
|
||||
return nil
|
||||
default:
|
||||
// 平台白名单为平台清单(domain/platforms.go)中的全部具体平台,
|
||||
// 与 service.AllowedQuotaPlatforms 同源;数据库不再维护 CHECK 约束。
|
||||
if !domain.IsConcretePlatform(s) {
|
||||
return fmt.Errorf("platform %q is not allowed", s)
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
|
||||
// 日 / 周 / 月 USD 上限:
|
||||
|
||||
+10
-10
@@ -1,6 +1,6 @@
|
||||
module github.com/Wei-Shaw/sub2api
|
||||
|
||||
go 1.27.0
|
||||
go 1.27.2
|
||||
|
||||
require (
|
||||
entgo.io/ent v0.14.5
|
||||
@@ -19,6 +19,7 @@ require (
|
||||
github.com/coder/websocket v1.8.14
|
||||
github.com/dgraph-io/ristretto v0.2.0
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/go-playground/validator/v10 v10.14.0
|
||||
github.com/go-webauthn/webauthn v0.17.4
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/uuid v1.6.0
|
||||
@@ -50,12 +51,12 @@ require (
|
||||
github.com/wechatpay-apiv3/wechatpay-go v0.2.21
|
||||
github.com/zeromicro/go-zero v1.9.4
|
||||
go.uber.org/zap v1.24.0
|
||||
golang.org/x/crypto v0.55.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/image v0.41.0
|
||||
golang.org/x/mod v0.38.0
|
||||
golang.org/x/net v0.58.0
|
||||
golang.org/x/sync v0.22.0
|
||||
golang.org/x/term v0.45.0
|
||||
golang.org/x/mod v0.41.0
|
||||
golang.org/x/net v0.60.0
|
||||
golang.org/x/sync v0.23.0
|
||||
golang.org/x/term v0.46.0
|
||||
google.golang.org/grpc v1.83.2
|
||||
google.golang.org/protobuf v1.36.11
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
||||
@@ -120,7 +121,6 @@ require (
|
||||
github.com/go-openapi/inflect v0.19.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/go-webauthn/x v0.2.6 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
@@ -201,10 +201,10 @@ require (
|
||||
go.uber.org/multierr v1.9.0 // indirect
|
||||
golang.org/x/arch v0.3.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.41.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
golang.org/x/time v0.12.0 // indirect
|
||||
golang.org/x/tools v0.48.0 // indirect
|
||||
golang.org/x/tools v0.50.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
modernc.org/libc v1.67.6 // indirect
|
||||
|
||||
@@ -564,6 +564,8 @@ golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v
|
||||
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
|
||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
|
||||
@@ -580,6 +582,8 @@ golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
|
||||
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
@@ -603,6 +607,8 @@ golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
@@ -616,6 +622,8 @@ golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -649,6 +657,8 @@ golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
@@ -663,6 +673,8 @@ golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0=
|
||||
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
|
||||
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
@@ -675,6 +687,8 @@ golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
|
||||
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
@@ -691,6 +705,10 @@ golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
||||
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
|
||||
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
|
||||
@@ -30,8 +30,14 @@ const (
|
||||
PlatformMiniMax = "minimax" // MiniMax (M 系列)
|
||||
PlatformTypeSafe = "typesafe" // TypeSafe AI System One (Jev)
|
||||
// PlatformOpenCodeGo 是 OpenCode 平台(账号类型 Zen 按量 / Go 订阅)。
|
||||
// 值保持 opencode_go 以兼容已落库的分组、配额与 Composite 路由 CHECK。
|
||||
// 值保持 opencode_go 以兼容已落库的账号、分组、配额与 Composite 路由。
|
||||
PlatformOpenCodeGo = "opencode_go"
|
||||
// PlatformCommandCode 是 Command Code Provider API(多模型聚合,积分计费,
|
||||
// 订阅套餐另有 5 小时 / 每周滚动窗口)。
|
||||
PlatformCommandCode = "command_code"
|
||||
// PlatformCline 是 Cline API(多模型聚合,OpenAI 兼容 Chat Completions;按量积分计费,
|
||||
// 另有 ClinePass 订阅)。
|
||||
PlatformCline = "cline"
|
||||
// PlatformOllamaCloud 是 Ollama Cloud 订阅制聚合上游(多协议 API Key 网关)。
|
||||
PlatformOllamaCloud = "ollama_cloud"
|
||||
PlatformComposite = "composite"
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package domain
|
||||
|
||||
// 平台清单:平台的单一数据来源。"所有平台"类列表(分组平台、用户额度、组合
|
||||
// 路由目标、调度快照、定价匹配等)与"某网关族"类列表都从这里派生;新增平台
|
||||
// 登记一条即可在这些位置生效,无需逐处修改或新增数据库约束迁移。
|
||||
//
|
||||
// 依赖具体实现的能力(OAuth、渠道监控、余额 / Coding Plan 探测、用量窗口、
|
||||
// Codex 模型目录等)仍由各自的代码显式列出,不在此处声明。
|
||||
|
||||
// PlatformGateway 标识平台请求由哪个网关服务处理。
|
||||
type PlatformGateway string
|
||||
|
||||
const (
|
||||
// PlatformGatewayAnthropic 由 GatewayService 处理(Claude Messages 协议,以及 TypeSafe 的 /v1/systemone)。
|
||||
PlatformGatewayAnthropic PlatformGateway = "anthropic"
|
||||
// PlatformGatewayOpenAI 由 OpenAIGatewayService 处理(OpenAI、Grok 与多协议 API Key 供应商)。
|
||||
PlatformGatewayOpenAI PlatformGateway = "openai"
|
||||
// PlatformGatewayGemini 由 Gemini 兼容网关处理。
|
||||
PlatformGatewayGemini PlatformGateway = "gemini"
|
||||
// PlatformGatewayAntigravity 由 Antigravity 网关处理。
|
||||
PlatformGatewayAntigravity PlatformGateway = "antigravity"
|
||||
)
|
||||
|
||||
// PlatformSpec 描述一个具体(非 composite)平台。
|
||||
type PlatformSpec struct {
|
||||
ID string `json:"id"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Gateway PlatformGateway `json:"gateway"`
|
||||
// CNProvider 标识国产单一厂商(Kimi / 智谱 / DeepSeek / MiniMax),共享国产
|
||||
// 供应商的余额 / Coding Plan 等能力。
|
||||
CNProvider bool `json:"cn_provider"`
|
||||
// LiteLLMProvider 是定价目录中的 provider 名;空表示不支持从定价目录同步模型。
|
||||
LiteLLMProvider string `json:"litellm_provider,omitempty"`
|
||||
}
|
||||
|
||||
// platformList 的顺序即平台的展示顺序。
|
||||
var platformList = []PlatformSpec{
|
||||
{ID: PlatformAnthropic, DisplayName: "Anthropic", Gateway: PlatformGatewayAnthropic, LiteLLMProvider: "anthropic"},
|
||||
{ID: PlatformOpenAI, DisplayName: "OpenAI", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "openai"},
|
||||
{ID: PlatformGemini, DisplayName: "Gemini", Gateway: PlatformGatewayGemini, LiteLLMProvider: "gemini"},
|
||||
{ID: PlatformAntigravity, DisplayName: "Antigravity", Gateway: PlatformGatewayAntigravity, LiteLLMProvider: "anthropic"},
|
||||
{ID: PlatformGrok, DisplayName: "Grok", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "xai"},
|
||||
{ID: PlatformKimi, DisplayName: "Kimi", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "moonshot"},
|
||||
{ID: PlatformZhipu, DisplayName: "Zhipu GLM", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "zhipu"},
|
||||
{ID: PlatformDeepseek, DisplayName: "DeepSeek", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "deepseek"},
|
||||
{ID: PlatformMiniMax, DisplayName: "MiniMax", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "minimax"},
|
||||
{ID: PlatformOpenCodeGo, DisplayName: "OpenCode", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "opencode-go"},
|
||||
{ID: PlatformTypeSafe, DisplayName: "TypeSafe / Jev", Gateway: PlatformGatewayAnthropic, LiteLLMProvider: "typesafe"},
|
||||
{ID: PlatformCommandCode, DisplayName: "Command Code", Gateway: PlatformGatewayOpenAI},
|
||||
{ID: PlatformCline, DisplayName: "Cline", Gateway: PlatformGatewayOpenAI},
|
||||
// Ollama Cloud 定价目录没有 ollama 条目,LiteLLMProvider 留空(不支持从定价目录同步模型)。
|
||||
{ID: PlatformOllamaCloud, DisplayName: "Ollama Cloud", Gateway: PlatformGatewayOpenAI},
|
||||
}
|
||||
|
||||
var platformIndex = func() map[string]int {
|
||||
index := make(map[string]int, len(platformList))
|
||||
for i, spec := range platformList {
|
||||
index[spec.ID] = i
|
||||
}
|
||||
return index
|
||||
}()
|
||||
|
||||
// Platforms 返回全部具体平台(副本),按展示顺序。
|
||||
func Platforms() []PlatformSpec {
|
||||
out := make([]PlatformSpec, len(platformList))
|
||||
copy(out, platformList)
|
||||
return out
|
||||
}
|
||||
|
||||
// LookupPlatform 返回具体平台的登记信息;composite 与未知值返回 false。
|
||||
func LookupPlatform(id string) (PlatformSpec, bool) {
|
||||
i, ok := platformIndex[id]
|
||||
if !ok {
|
||||
return PlatformSpec{}, false
|
||||
}
|
||||
return platformList[i], true
|
||||
}
|
||||
|
||||
// IsConcretePlatform 报告 id 是否为已登记的具体平台(不含 composite)。
|
||||
func IsConcretePlatform(id string) bool {
|
||||
_, ok := platformIndex[id]
|
||||
return ok
|
||||
}
|
||||
|
||||
// IsGroupPlatform 报告 id 是否可作为分组平台(具体平台或 composite)。
|
||||
func IsGroupPlatform(id string) bool {
|
||||
return id == PlatformComposite || IsConcretePlatform(id)
|
||||
}
|
||||
|
||||
// ConcretePlatformIDs 返回全部具体平台标识,按展示顺序。
|
||||
func ConcretePlatformIDs() []string {
|
||||
return PlatformIDsWhere(func(PlatformSpec) bool { return true })
|
||||
}
|
||||
|
||||
// PlatformIDsWhere 返回满足条件的具体平台标识,按展示顺序。
|
||||
func PlatformIDsWhere(match func(PlatformSpec) bool) []string {
|
||||
out := make([]string, 0, len(platformList))
|
||||
for _, spec := range platformList {
|
||||
if match(spec) {
|
||||
out = append(out, spec.ID)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// compositePrecedenceHead 是组合分组查找顺序的固定前缀(历史顺序:Gemini 先于 OpenAI)。
|
||||
var compositePrecedenceHead = []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI}
|
||||
|
||||
// CompositePrecedencePlatformIDs 返回按平台依次回退时的顺序:组合分组在请求目标
|
||||
// 解析前逐平台查找定价 / 模型映射(先命中者生效)、拼接默认模型列表,以及调度快照
|
||||
// 遍历。沿用历史顺序 anthropic、gemini、openai,其余按展示顺序,新登记的平台追加在末尾。
|
||||
func CompositePrecedencePlatformIDs() []string {
|
||||
out := make([]string, 0, len(platformList))
|
||||
seen := make(map[string]struct{}, len(platformList))
|
||||
for _, id := range compositePrecedenceHead {
|
||||
if IsConcretePlatform(id) {
|
||||
out = append(out, id)
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
}
|
||||
for _, spec := range platformList {
|
||||
if _, ok := seen[spec.ID]; !ok {
|
||||
out = append(out, spec.ID)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// UsesOpenAIGateway 报告平台是否由 OpenAI 网关处理。
|
||||
func UsesOpenAIGateway(id string) bool {
|
||||
spec, ok := LookupPlatform(id)
|
||||
return ok && spec.Gateway == PlatformGatewayOpenAI
|
||||
}
|
||||
|
||||
// IsCNProviderPlatform 报告平台是否为国产单一厂商。
|
||||
func IsCNProviderPlatform(id string) bool {
|
||||
spec, ok := LookupPlatform(id)
|
||||
return ok && spec.CNProvider
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 重构前各处手写的平台列表,作为平台清单派生结果的等价基准;重构后新登记的平台
|
||||
// (Command Code、Cline、Ollama Cloud)按同类平台(OpenCode)的位置补入。
|
||||
var (
|
||||
legacyDisplayOrder = []string{
|
||||
PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
|
||||
PlatformCommandCode,
|
||||
PlatformCline,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
legacyCompositePrecedence = []string{
|
||||
PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
|
||||
PlatformCommandCode,
|
||||
PlatformCline,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
legacyOpenAIGateway = []string{
|
||||
PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo,
|
||||
PlatformCommandCode,
|
||||
PlatformCline,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
legacyCNProviders = []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax}
|
||||
legacyLiteLLMByPlatf = map[string]string{
|
||||
PlatformAnthropic: "anthropic", PlatformOpenAI: "openai", PlatformGemini: "gemini",
|
||||
PlatformAntigravity: "anthropic", PlatformGrok: "xai", PlatformKimi: "moonshot",
|
||||
PlatformZhipu: "zhipu", PlatformDeepseek: "deepseek", PlatformMiniMax: "minimax",
|
||||
PlatformOpenCodeGo: "opencode-go", PlatformTypeSafe: "typesafe", PlatformCommandCode: "", PlatformCline: "", PlatformOllamaCloud: "",
|
||||
}
|
||||
)
|
||||
|
||||
func TestPlatformListMatchesLegacyLists(t *testing.T) {
|
||||
require.Equal(t, legacyDisplayOrder, ConcretePlatformIDs())
|
||||
require.Equal(t, legacyCompositePrecedence, CompositePrecedencePlatformIDs())
|
||||
require.Equal(t, legacyOpenAIGateway, PlatformIDsWhere(func(spec PlatformSpec) bool {
|
||||
return spec.Gateway == PlatformGatewayOpenAI
|
||||
}))
|
||||
require.Equal(t, legacyCNProviders, PlatformIDsWhere(func(spec PlatformSpec) bool { return spec.CNProvider }))
|
||||
for platform, provider := range legacyLiteLLMByPlatf {
|
||||
spec, ok := LookupPlatform(platform)
|
||||
require.True(t, ok, platform)
|
||||
require.Equal(t, provider, spec.LiteLLMProvider, platform)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformListPredicates(t *testing.T) {
|
||||
for _, platform := range legacyDisplayOrder {
|
||||
require.True(t, IsConcretePlatform(platform), platform)
|
||||
require.True(t, IsGroupPlatform(platform), platform)
|
||||
spec, ok := LookupPlatform(platform)
|
||||
require.True(t, ok, platform)
|
||||
require.NotEmpty(t, spec.DisplayName, platform)
|
||||
require.NotEmpty(t, spec.Gateway, platform)
|
||||
}
|
||||
require.False(t, IsConcretePlatform(PlatformComposite))
|
||||
require.True(t, IsGroupPlatform(PlatformComposite))
|
||||
for _, invalid := range []string{"", "moonshot", "Kimi", "openai ", "glm", "bogus"} {
|
||||
require.False(t, IsConcretePlatform(invalid), invalid)
|
||||
require.False(t, IsGroupPlatform(invalid), invalid)
|
||||
require.False(t, UsesOpenAIGateway(invalid), invalid)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformsReturnsCopy(t *testing.T) {
|
||||
platforms := Platforms()
|
||||
platforms[0].ID = "mutated"
|
||||
require.Equal(t, PlatformAnthropic, Platforms()[0].ID)
|
||||
}
|
||||
@@ -1227,7 +1227,7 @@ func (h *AccountHandler) Update(c *gin.Context) {
|
||||
// 网关会按"现状即证据"默认走 Responses。
|
||||
func (h *AccountHandler) scheduleOpenAIResponsesProbe(account *service.Account) {
|
||||
if account == nil || account.Type != service.AccountTypeAPIKey ||
|
||||
(account.Platform != service.PlatformOpenAI && !service.IsCNProvider(account.Platform) && !account.IsOllamaCloud()) {
|
||||
(account.Platform != service.PlatformOpenAI && !account.RoutesProtocolByInbound()) {
|
||||
return
|
||||
}
|
||||
if h.accountTestService == nil {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
|
||||
@@ -631,25 +632,14 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// platformToLiteLLMProvider maps a channel platform name to the corresponding
|
||||
// LiteLLM provider string used as the key in the pricing catalog.
|
||||
//
|
||||
// ollama_cloud 故意不在本表(C24):LiteLLM 目录没有 ollama 条目,加了映射只会
|
||||
// 绕过 SyncPricingModels 的 unsupported 分支返回空列表(静默空池)。保持缺席,
|
||||
// 让 sync-models?platform=ollama_cloud 显式返回 400 UNSUPPORTED_PLATFORM;
|
||||
// ollama 定价走 billing_service.go fallbackPrices 的 ollama 条目(B2-② 落点)。
|
||||
var platformToLiteLLMProvider = map[string]string{
|
||||
service.PlatformAnthropic: "anthropic",
|
||||
service.PlatformOpenAI: "openai",
|
||||
service.PlatformGemini: "gemini",
|
||||
service.PlatformAntigravity: "anthropic",
|
||||
service.PlatformGrok: "xai",
|
||||
service.PlatformKimi: "moonshot",
|
||||
service.PlatformZhipu: "zhipu",
|
||||
service.PlatformDeepseek: "deepseek",
|
||||
service.PlatformMiniMax: "minimax",
|
||||
service.PlatformOpenCodeGo: "opencode-go",
|
||||
service.PlatformTypeSafe: "typesafe",
|
||||
// platformLiteLLMProvider maps a channel platform name to the corresponding
|
||||
// LiteLLM provider string used as the key in the pricing catalog (platform list).
|
||||
func platformLiteLLMProvider(platform string) (string, bool) {
|
||||
spec, ok := domain.LookupPlatform(platform)
|
||||
if !ok || spec.LiteLLMProvider == "" {
|
||||
return "", false
|
||||
}
|
||||
return spec.LiteLLMProvider, true
|
||||
}
|
||||
|
||||
// SyncPricingModels 返回 LiteLLM 定价目录中指定平台的最新模型列表
|
||||
@@ -662,7 +652,7 @@ func (h *ChannelHandler) SyncPricingModels(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
provider, ok := platformToLiteLLMProvider[platform]
|
||||
provider, ok := platformLiteLLMProvider(platform)
|
||||
if !ok {
|
||||
response.ErrorFrom(c, infraerrors.BadRequest("UNSUPPORTED_PLATFORM",
|
||||
fmt.Sprintf("unsupported platform: %s", platform)).
|
||||
|
||||
@@ -184,7 +184,7 @@ func sanitizeUpdateGroupRequestForSimpleMode(req *UpdateGroupRequest) {
|
||||
type CreateGroupRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Description string `json:"description"`
|
||||
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe ollama_cloud composite"`
|
||||
Platform string `json:"platform" binding:"omitempty,group_platform"`
|
||||
RateMultiplier float64 `json:"rate_multiplier"`
|
||||
IsExclusive bool `json:"is_exclusive"`
|
||||
SubscriptionType string `json:"subscription_type" binding:"omitempty,oneof=standard subscription"`
|
||||
@@ -258,7 +258,7 @@ type CreateGroupRequest struct {
|
||||
type UpdateGroupRequest struct {
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe ollama_cloud composite"`
|
||||
Platform string `json:"platform" binding:"omitempty,group_platform"`
|
||||
RateMultiplier *float64 `json:"rate_multiplier"`
|
||||
IsExclusive *bool `json:"is_exclusive"`
|
||||
Status string `json:"status" binding:"omitempty,oneof=active inactive"`
|
||||
@@ -332,7 +332,7 @@ type UpdateGroupRequest struct {
|
||||
type CompositeRouteRequest struct {
|
||||
PublicModel string `json:"public_model" binding:"required"`
|
||||
MatchType string `json:"match_type" binding:"omitempty,oneof=exact prefix"`
|
||||
TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe ollama_cloud"`
|
||||
TargetPlatform string `json:"target_platform" binding:"required,concrete_platform"`
|
||||
UpstreamModel string `json:"upstream_model"`
|
||||
Endpoint string `json:"endpoint" binding:"omitempty,oneof=any messages count_tokens responses chat_completions embeddings images gemini"`
|
||||
Priority int `json:"priority"`
|
||||
|
||||
@@ -27,7 +27,9 @@ func bindGroupPlatformJSON(t *testing.T, target any, body string) error {
|
||||
func TestGroupPlatformBinding_AllowedPlatforms(t *testing.T) {
|
||||
allowed := []string{
|
||||
"anthropic", "openai", "gemini", "antigravity", "grok",
|
||||
"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe", "ollama_cloud", "composite",
|
||||
"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "composite",
|
||||
"typesafe",
|
||||
"command_code", "cline", "ollama_cloud",
|
||||
}
|
||||
for _, platform := range allowed {
|
||||
t.Run("create_"+platform, func(t *testing.T) {
|
||||
@@ -72,7 +74,7 @@ func TestGroupPlatformBinding_RejectsInvalidPlatforms(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCompositeRouteTargetPlatform_AllowsConcreteProviders(t *testing.T) {
|
||||
for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe", "ollama_cloud"} {
|
||||
for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe", "command_code", "cline", "ollama_cloud"} {
|
||||
var req CompositeRouteRequest
|
||||
body := fmt.Sprintf(`{"public_model":"m","target_platform":%q}`, platform)
|
||||
require.NoError(t, bindGroupPlatformJSON(t, &req, body))
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
// 平台相关的请求绑定校验标签,由平台清单(domain/platforms.go)驱动,替代在
|
||||
// binding 标签里手写 oneof 白名单(新增平台时易漏加,导致分组无法创建):
|
||||
// - group_platform:已登记的具体平台或 composite;
|
||||
// - concrete_platform:已登记的具体平台。
|
||||
func init() {
|
||||
engine, ok := binding.Validator.Engine().(*validator.Validate)
|
||||
if !ok {
|
||||
panic("platform validation requires a go-playground validator engine")
|
||||
}
|
||||
if err := engine.RegisterValidation("group_platform", func(fl validator.FieldLevel) bool {
|
||||
return domain.IsGroupPlatform(fl.Field().String())
|
||||
}); err != nil {
|
||||
panic(fmt.Errorf("register group_platform validation: %w", err))
|
||||
}
|
||||
if err := engine.RegisterValidation("concrete_platform", func(fl validator.FieldLevel) bool {
|
||||
return domain.IsConcretePlatform(fl.Field().String())
|
||||
}); err != nil {
|
||||
panic(fmt.Errorf("register concrete_platform validation: %w", err))
|
||||
}
|
||||
}
|
||||
@@ -1380,7 +1380,7 @@ func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID *
|
||||
seen := make(map[string]struct{})
|
||||
models := make([]string, 0)
|
||||
schedulablePlatforms := h.gatewayService.GetSchedulablePlatforms(ctx, groupID)
|
||||
for _, platform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformTypeSafe, service.PlatformOllamaCloud} {
|
||||
for _, platform := range domain.CompositePrecedencePlatformIDs() {
|
||||
if platform == service.PlatformTypeSafe && !includeSystemOne {
|
||||
continue
|
||||
}
|
||||
@@ -1584,10 +1584,13 @@ func defaultModelIDsForPlatform(platform string) []string {
|
||||
case service.PlatformComposite:
|
||||
ids := make([]string, 0)
|
||||
seen := make(map[string]struct{})
|
||||
// TypeSafe is deliberately absent: jev-latest only works through
|
||||
// /v1/systemone, so the static fallback never advertises it to LLM
|
||||
// clients. compositeAvailableModels lists it when the group can serve it.
|
||||
for _, concretePlatform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud} {
|
||||
for _, concretePlatform := range domain.CompositePrecedencePlatformIDs() {
|
||||
// TypeSafe is deliberately skipped: jev-latest only works through
|
||||
// /v1/systemone, so the static fallback never advertises it to LLM
|
||||
// clients. compositeAvailableModels lists it when the group can serve it.
|
||||
if concretePlatform == service.PlatformTypeSafe {
|
||||
continue
|
||||
}
|
||||
for _, id := range defaultModelIDsForPlatform(concretePlatform) {
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ip"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
@@ -354,9 +355,9 @@ func allowOpenAICompatibleMessagesDispatch(c *gin.Context, apiKey *service.APIKe
|
||||
|
||||
func openAICompatibleTextTargetAllowed(c *gin.Context, apiKey *service.APIKey, model string) bool {
|
||||
return compositeTargetPlatformAllowed(c, apiKey, model,
|
||||
service.PlatformOpenAI, service.PlatformGrok,
|
||||
service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek,
|
||||
service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud)
|
||||
domain.PlatformIDsWhere(func(spec domain.PlatformSpec) bool {
|
||||
return spec.Gateway == domain.PlatformGatewayOpenAI
|
||||
})...)
|
||||
}
|
||||
|
||||
// isResponsesWebSocketCompositePlatform 限定 composite 分组在 Responses WebSocket
|
||||
|
||||
@@ -50,22 +50,9 @@ const (
|
||||
PlatformOllamaCloud = domain.PlatformOllamaCloud
|
||||
)
|
||||
|
||||
// AllPlatforms 返回所有支持的平台列表
|
||||
// AllPlatforms 返回所有支持的平台列表(平台清单,按展示顺序)。
|
||||
func AllPlatforms() []string {
|
||||
return []string{
|
||||
PlatformAnthropic,
|
||||
PlatformOpenAI,
|
||||
PlatformGemini,
|
||||
PlatformAntigravity,
|
||||
PlatformGrok,
|
||||
PlatformKimi,
|
||||
PlatformZhipu,
|
||||
PlatformDeepseek,
|
||||
PlatformMiniMax,
|
||||
PlatformOpenCodeGo,
|
||||
PlatformTypeSafe,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
return domain.ConcretePlatformIDs()
|
||||
}
|
||||
|
||||
// Validate 验证规则配置的有效性
|
||||
|
||||
@@ -19,6 +19,8 @@ func TestAllPlatformsIncludesEveryConcretePlatform(t *testing.T) {
|
||||
"minimax",
|
||||
"opencode_go",
|
||||
"typesafe",
|
||||
"command_code",
|
||||
"cline",
|
||||
"ollama_cloud",
|
||||
}, AllPlatforms())
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//go:build integration
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
dbmigrations "github.com/Wei-Shaw/sub2api/migrations"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func platformConstraintExists(t *testing.T, ctx context.Context, client *dbent.Client, table, constraint string) bool {
|
||||
t.Helper()
|
||||
rows, err := client.QueryContext(ctx, `
|
||||
SELECT 1
|
||||
FROM pg_constraint c
|
||||
JOIN pg_class tbl ON tbl.oid = c.conrelid
|
||||
JOIN pg_namespace ns ON ns.oid = tbl.relnamespace
|
||||
WHERE ns.nspname = 'public' AND tbl.relname = $1 AND c.conname = $2`, table, constraint)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = rows.Close() }()
|
||||
exists := rows.Next()
|
||||
require.NoError(t, rows.Err())
|
||||
return exists
|
||||
}
|
||||
|
||||
// 迁移 242 删除平台白名单 CHECK 约束:旧库(约束仍在)上可重复执行,执行后
|
||||
// 新登记的平台无需再做数据库迁移即可写入。
|
||||
func TestMigration242DropsPlatformCheckConstraints(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tx := testEntTx(t)
|
||||
client := tx.Client()
|
||||
|
||||
// 还原迁移 241_add_typesafe_platform 之后、242 之前的约束状态。
|
||||
for _, stmt := range []string{
|
||||
`ALTER TABLE user_platform_quotas DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check`,
|
||||
`ALTER TABLE user_platform_quotas ADD CONSTRAINT user_platform_quotas_platform_check
|
||||
CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok',
|
||||
'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))`,
|
||||
`ALTER TABLE composite_model_routes DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check`,
|
||||
`ALTER TABLE composite_model_routes ADD CONSTRAINT composite_model_routes_target_platform_check
|
||||
CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok',
|
||||
'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))`,
|
||||
} {
|
||||
_, err := client.ExecContext(ctx, stmt)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.True(t, platformConstraintExists(t, ctx, client, "user_platform_quotas", "user_platform_quotas_platform_check"))
|
||||
require.True(t, platformConstraintExists(t, ctx, client, "composite_model_routes", "composite_model_routes_target_platform_check"))
|
||||
|
||||
migrationSQL, err := dbmigrations.FS.ReadFile("242_drop_platform_check_constraints.sql")
|
||||
require.NoError(t, err)
|
||||
for range 2 {
|
||||
_, err = client.ExecContext(ctx, string(migrationSQL))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.False(t, platformConstraintExists(t, ctx, client, "user_platform_quotas", "user_platform_quotas_platform_check"))
|
||||
require.False(t, platformConstraintExists(t, ctx, client, "composite_model_routes", "composite_model_routes_target_platform_check"))
|
||||
// 渠道监控的 provider 约束表示探测能力,保留。
|
||||
require.True(t, platformConstraintExists(t, ctx, client, "channel_monitors", "channel_monitors_provider_check"))
|
||||
require.True(t, platformConstraintExists(t, ctx, client, "channel_monitor_request_templates", "channel_monitor_request_templates_provider_check"))
|
||||
|
||||
// 数据库层不再限制平台取值:模拟未来新登记的平台。
|
||||
userID := mustCreateUserForQuota(t, client)
|
||||
_, err = client.ExecContext(ctx, `
|
||||
INSERT INTO user_platform_quotas (user_id, platform, daily_limit_usd, daily_usage_usd, weekly_usage_usd, monthly_usage_usd, created_at, updated_at)
|
||||
VALUES ($1, 'future_platform', 1, 0, 0, 0, NOW(), NOW())`, userID)
|
||||
require.NoError(t, err)
|
||||
group := mustCreateGroup(t, client, &service.Group{Name: "platform-list-composite", Platform: service.PlatformComposite})
|
||||
_, err = client.ExecContext(ctx, `
|
||||
INSERT INTO composite_model_routes (group_id, public_model, target_platform)
|
||||
VALUES ($1, 'future-model', 'future_platform')`, group.ID)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// 删除 CHECK 约束后,平台合法性由应用层保证:原生 SQL 写入前的 repository 校验。
|
||||
func TestUserPlatformQuotaRepository_RejectsUnregisteredPlatform(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tx := testEntTx(t)
|
||||
txCtx := dbent.NewTxContext(ctx, tx)
|
||||
client := tx.Client()
|
||||
|
||||
userID := mustCreateUserForQuota(t, client)
|
||||
repo := NewUserPlatformQuotaRepository(client)
|
||||
daily := 5.0
|
||||
require.NoError(t, repo.UpsertForUser(txCtx, userID, []UserPlatformQuotaRecord{
|
||||
{UserID: userID, Platform: service.PlatformOpenCodeGo, DailyLimitUSD: &daily},
|
||||
}))
|
||||
|
||||
for _, platform := range []string{"bogus", "moonshot", "Kimi", service.PlatformComposite} {
|
||||
err := repo.BulkInsertInitial(txCtx, []UserPlatformQuotaRecord{
|
||||
{UserID: userID, Platform: service.PlatformAnthropic, DailyLimitUSD: &daily},
|
||||
{UserID: userID, Platform: platform, DailyLimitUSD: &daily},
|
||||
})
|
||||
require.ErrorContains(t, err, "is not allowed", platform)
|
||||
err = repo.UpsertForUser(txCtx, userID, []UserPlatformQuotaRecord{
|
||||
{UserID: userID, Platform: platform, DailyLimitUSD: &daily},
|
||||
})
|
||||
require.ErrorContains(t, err, "is not allowed", platform)
|
||||
}
|
||||
|
||||
// 被拒绝的写入不产生任何副作用:既有记录保留、未新增任何行。
|
||||
got, err := repo.ListByUser(txCtx, userID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 1)
|
||||
require.Equal(t, service.PlatformOpenCodeGo, got[0].Platform)
|
||||
|
||||
// 三档全空的记录不写入,也不参与校验(与既有 configuredRecords 语义一致)。
|
||||
require.NoError(t, repo.BulkInsertInitial(txCtx, []UserPlatformQuotaRecord{{UserID: userID, Platform: "bogus"}}))
|
||||
}
|
||||
|
||||
func TestCompositeModelRouteRepository_RejectsUnregisteredTargetPlatform(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tx := testEntTx(t)
|
||||
txCtx := dbent.NewTxContext(ctx, tx)
|
||||
client := tx.Client()
|
||||
|
||||
group := mustCreateGroup(t, client, &service.Group{Name: "platform-list-routes", Platform: service.PlatformComposite})
|
||||
repo := NewCompositeModelRouteRepository(client)
|
||||
|
||||
route := &service.CompositeModelRoute{
|
||||
GroupID: group.ID, PublicModel: "glm-5", MatchType: "exact", TargetPlatform: service.PlatformZhipu,
|
||||
UpstreamModel: "glm-5", Endpoint: "any", Priority: 100, Enabled: true,
|
||||
}
|
||||
require.NoError(t, repo.Create(txCtx, route))
|
||||
|
||||
bad := &service.CompositeModelRoute{
|
||||
GroupID: group.ID, PublicModel: "bogus-model", MatchType: "exact", TargetPlatform: "bogus",
|
||||
UpstreamModel: "bogus-model", Endpoint: "any", Priority: 100, Enabled: true,
|
||||
}
|
||||
require.Error(t, repo.Create(txCtx, bad))
|
||||
|
||||
route.TargetPlatform = service.PlatformComposite
|
||||
require.Error(t, repo.Update(txCtx, route))
|
||||
|
||||
routes, err := repo.ListByGroup(txCtx, group.ID, true)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, routes, 1)
|
||||
require.Equal(t, service.PlatformZhipu, routes[0].TargetPlatform)
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/Wei-Shaw/sub2api/ent/userplatformquota"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/timezone"
|
||||
)
|
||||
|
||||
@@ -95,6 +96,9 @@ func (r *userPlatformQuotaRepository) BulkInsertInitial(ctx context.Context, rec
|
||||
if len(records) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := validateQuotaPlatforms(records); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
client := clientFromContext(ctx, r.client)
|
||||
|
||||
@@ -318,6 +322,9 @@ func monthlyMaybeReset(prevUsage float64, prevStart *time.Time, cost float64, no
|
||||
// 清空某平台的限额即软删该行并放弃其累计用量;之后再次配置限额会新建行、从新窗口起算。
|
||||
func (r *userPlatformQuotaRepository) UpsertForUser(ctx context.Context, userID int64, records []UserPlatformQuotaRecord) error {
|
||||
records = configuredRecords(records)
|
||||
if err := validateQuotaPlatforms(records); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.withTx(ctx, func(txCtx context.Context, txClient *dbent.Client) error {
|
||||
platforms := make([]string, 0, len(records))
|
||||
for _, rec := range records {
|
||||
@@ -484,6 +491,17 @@ func (r *userPlatformQuotaRepository) BatchSnapshotUsage(ctx context.Context, sn
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateQuotaPlatforms 在原生 SQL 写入前校验平台须为平台清单中的具体平台,
|
||||
// 取代迁移 242 删除的 user_platform_quotas_platform_check 约束(原生 SQL 不经过 ent Validate)。
|
||||
func validateQuotaPlatforms(records []UserPlatformQuotaRecord) error {
|
||||
for _, rec := range records {
|
||||
if !domain.IsConcretePlatform(rec.Platform) {
|
||||
return fmt.Errorf("user_platform_quotas: platform %q is not allowed", rec.Platform)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// configuredRecords 过滤出至少配置了一档限额的记录;三档全空的记录视为未配置。
|
||||
func configuredRecords(records []UserPlatformQuotaRecord) []UserPlatformQuotaRecord {
|
||||
out := make([]UserPlatformQuotaRecord, 0, len(records))
|
||||
|
||||
@@ -863,7 +863,7 @@ func TestAPIContracts(t *testing.T) {
|
||||
"force_email_on_third_party_signup": false,
|
||||
"default_concurrency": 5,
|
||||
"default_balance": 1.25,
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"cline":{"daily":null,"weekly":null,"monthly":null},"command_code":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"auth_source_default_email_platform_quotas": null,
|
||||
"auth_source_default_github_platform_quotas": null,
|
||||
"auth_source_default_google_platform_quotas": null,
|
||||
@@ -1189,7 +1189,7 @@ func TestAPIContracts(t *testing.T) {
|
||||
"purchase_subscription_url": "",
|
||||
"table_default_page_size": 20,
|
||||
"table_page_size_options": [10, 20, 50],
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"cline":{"daily":null,"weekly":null,"monthly":null},"command_code":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"auth_source_default_email_platform_quotas": null,
|
||||
"auth_source_default_github_platform_quotas": null,
|
||||
"auth_source_default_google_platform_quotas": null,
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler"
|
||||
pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/requestmodel"
|
||||
@@ -508,17 +509,9 @@ func getGroupPlatform(c *gin.Context) string {
|
||||
}
|
||||
|
||||
// isOpenAICompatibleGatewayFamilyPlatform 报告单个平台是否经 OpenAI 网关转发
|
||||
// (openai/grok/国产 OpenAI 兼容供应商/OpenCode Go/Ollama Cloud)。
|
||||
// (openai、grok 与多协议 API Key 供应商,见平台清单)。
|
||||
func isOpenAICompatibleGatewayFamilyPlatform(platform string) bool {
|
||||
switch platform {
|
||||
case service.PlatformOpenAI, service.PlatformGrok,
|
||||
service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek,
|
||||
service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud:
|
||||
// 国产 OpenAI 兼容供应商与 openai/grok 一样经 OpenAI 网关转发。
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return domain.UsesOpenAIGateway(platform)
|
||||
}
|
||||
|
||||
// compositePoolCandidatePlatforms 返回 composite 账号池请求的候选平台集合;
|
||||
@@ -611,11 +604,11 @@ func dispatchOpenAICompatibleCountTokens(c *gin.Context, compatibleHandler, grok
|
||||
genericHandler(c)
|
||||
return
|
||||
}
|
||||
switch getGroupPlatform(c) {
|
||||
case service.PlatformOpenAI, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud:
|
||||
compatibleHandler(c)
|
||||
case service.PlatformGrok:
|
||||
switch platform := getGroupPlatform(c); {
|
||||
case platform == service.PlatformGrok:
|
||||
grokHandler(c)
|
||||
case isOpenAICompatibleGatewayFamilyPlatform(platform):
|
||||
compatibleHandler(c)
|
||||
default:
|
||||
genericHandler(c)
|
||||
}
|
||||
|
||||
@@ -324,7 +324,7 @@ func (a *Account) GetOllamaCloudAccountMode() string {
|
||||
// 兼容上游,也经 OpenAI 网关转发。OpenCode 与 Ollama Cloud 同样经 OpenAI
|
||||
// 网关按模型/协议分流。
|
||||
func (a *Account) IsOpenAICompatible() bool {
|
||||
return a != nil && (a.Platform == PlatformOpenAI || a.Platform == PlatformGrok || a.IsCNProvider() || a.IsOpenCodeGo() || a.IsOllamaCloud())
|
||||
return a != nil && domain.UsesOpenAIGateway(a.Platform)
|
||||
}
|
||||
|
||||
func (a *Account) GeminiOAuthType() string {
|
||||
@@ -1455,7 +1455,7 @@ func (a *Account) IsOpenAIApiKey() bool {
|
||||
// 适用 openai、国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)、OpenCode Go 与
|
||||
// Ollama Cloud;grok 走 GetGrokBaseURL,此处对 grok 返回 "" 以保持原有行为。
|
||||
func (a *Account) GetOpenAIBaseURL() string {
|
||||
if !a.IsOpenAI() && !a.IsCNProvider() && !a.IsOpenCodeGo() && !a.IsOllamaCloud() {
|
||||
if !a.IsOpenAI() && !a.IsMultiProtocolAPIKey() {
|
||||
return ""
|
||||
}
|
||||
if a.IsMultiProtocolAPIKey() && a.IsAdaptiveAPIProtocol() {
|
||||
@@ -1470,34 +1470,16 @@ func (a *Account) GetOpenAIBaseURL() string {
|
||||
return baseURL
|
||||
}
|
||||
}
|
||||
// 平台默认 base_url:CN 供应商按 account_mode 选择 payg / coding 默认值。
|
||||
switch a.Platform {
|
||||
case PlatformKimi:
|
||||
if a.GetAccountMode() == AccountModeCoding {
|
||||
return DefaultKimiCodingBaseURL
|
||||
}
|
||||
return DefaultKimiPayGBaseURL
|
||||
case PlatformZhipu:
|
||||
if a.GetAccountMode() == AccountModeCoding {
|
||||
return DefaultZhipuCodingBaseURL
|
||||
}
|
||||
return DefaultZhipuPayGBaseURL
|
||||
case PlatformDeepseek:
|
||||
return DefaultDeepseekBaseURL
|
||||
case PlatformMiniMax:
|
||||
return DefaultMiniMaxBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
return a.openCodeDefaultChatBaseURL()
|
||||
case PlatformOllamaCloud:
|
||||
return DefaultOllamaCloudBaseURL
|
||||
default:
|
||||
if a.IsMultiProtocolAPIKey() {
|
||||
// 多协议网关(CN / OpenCode / Ollama Cloud)的缺省端点必须由上面的平台
|
||||
// 分支显式给出:回落官方域名会把第三方 key 明文发到 api.openai.com。
|
||||
return ""
|
||||
}
|
||||
return "https://api.openai.com"
|
||||
// 平台默认 base_url:多协议供应商按 account_mode 查 provider profile。
|
||||
if baseURL := a.defaultProviderBaseURL(APIProtocolChatCompletions); baseURL != "" {
|
||||
return baseURL
|
||||
}
|
||||
if a.IsMultiProtocolAPIKey() {
|
||||
// 多协议网关的缺省端点必须由 provider profile 给出:回落官方域名会把第三方
|
||||
// key 明文发到 api.openai.com。
|
||||
return ""
|
||||
}
|
||||
return "https://api.openai.com"
|
||||
}
|
||||
|
||||
// GetAccountMode 返回国产供应商账号的接入模式(payg / coding);非国产供应商或未设置时
|
||||
@@ -1539,7 +1521,11 @@ func (a *Account) GetAPIProtocol() string {
|
||||
case APIProtocolChatCompletions:
|
||||
return APIProtocolChatCompletions
|
||||
}
|
||||
if a.IsOpenCodeGo() || a.IsOllamaCloud() {
|
||||
if profile := a.providerProfile(); profile != nil && profile.DefaultAPIProtocol != "" {
|
||||
return profile.DefaultAPIProtocol
|
||||
}
|
||||
// 按模型分流的供应商(多模型聚合平台)未显式配置时默认 adaptive。
|
||||
if a.routesByModel() {
|
||||
return APIProtocolAdaptive
|
||||
}
|
||||
return APIProtocolChatCompletions
|
||||
@@ -1550,15 +1536,7 @@ func (a *Account) GetAPIProtocol() string {
|
||||
// /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses;
|
||||
// Ollama Cloud 为 /v1/responses(non-stateful,见 normalizeDeepSeekResponsesRequestBody)。
|
||||
func (a *Account) SupportsNativeCNResponses() bool {
|
||||
if a == nil {
|
||||
return false
|
||||
}
|
||||
switch a.Platform {
|
||||
case PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return a.providerSupportsProtocol(APIProtocolResponses)
|
||||
}
|
||||
|
||||
// UsesNativeCNResponses 报告当前账号是否应按原生 Responses 协议转发
|
||||
@@ -1599,52 +1577,7 @@ func (a *Account) GetCNProtocolBaseURL(protocol string) string {
|
||||
}
|
||||
}
|
||||
}
|
||||
return a.defaultCNProtocolBaseURL(protocol)
|
||||
}
|
||||
|
||||
func (a *Account) defaultCNProtocolBaseURL(protocol string) string {
|
||||
switch protocol {
|
||||
case APIProtocolAnthropic:
|
||||
switch a.Platform {
|
||||
case PlatformKimi:
|
||||
if a.GetAccountMode() == AccountModeCoding {
|
||||
return DefaultKimiCodingAnthropicBaseURL
|
||||
}
|
||||
return DefaultKimiPayGAnthropicBaseURL
|
||||
case PlatformZhipu:
|
||||
return DefaultZhipuAnthropicBaseURL
|
||||
case PlatformDeepseek:
|
||||
return DefaultDeepseekAnthropicBaseURL
|
||||
case PlatformMiniMax:
|
||||
return DefaultMiniMaxAnthropicBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
return a.openCodeDefaultAnthropicBaseURL()
|
||||
case PlatformOllamaCloud:
|
||||
return DefaultOllamaCloudAnthropicBaseURL
|
||||
}
|
||||
case APIProtocolChatCompletions, APIProtocolResponses:
|
||||
switch a.Platform {
|
||||
case PlatformKimi:
|
||||
if a.GetAccountMode() == AccountModeCoding {
|
||||
return DefaultKimiCodingBaseURL
|
||||
}
|
||||
return DefaultKimiPayGBaseURL
|
||||
case PlatformZhipu:
|
||||
if a.GetAccountMode() == AccountModeCoding {
|
||||
return DefaultZhipuCodingBaseURL
|
||||
}
|
||||
return DefaultZhipuPayGBaseURL
|
||||
case PlatformDeepseek:
|
||||
return DefaultDeepseekBaseURL
|
||||
case PlatformMiniMax:
|
||||
return DefaultMiniMaxBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
return a.openCodeDefaultChatBaseURL()
|
||||
case PlatformOllamaCloud:
|
||||
return DefaultOllamaCloudBaseURL
|
||||
}
|
||||
}
|
||||
return ""
|
||||
return a.defaultProviderBaseURL(protocol)
|
||||
}
|
||||
|
||||
// IsAnthropicProtocol 报告账号是否以原生 Anthropic 协议接入上游
|
||||
@@ -1668,28 +1601,7 @@ func (a *Account) GetAnthropicProtocolBaseURL() string {
|
||||
return baseURL
|
||||
}
|
||||
}
|
||||
switch a.Platform {
|
||||
case PlatformKimi:
|
||||
if a.GetAccountMode() == AccountModeCoding {
|
||||
return DefaultKimiCodingAnthropicBaseURL
|
||||
}
|
||||
return DefaultKimiPayGAnthropicBaseURL
|
||||
case PlatformZhipu:
|
||||
return DefaultZhipuAnthropicBaseURL
|
||||
case PlatformDeepseek:
|
||||
return DefaultDeepseekAnthropicBaseURL
|
||||
case PlatformMiniMax:
|
||||
return DefaultMiniMaxAnthropicBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
return a.openCodeDefaultAnthropicBaseURL()
|
||||
case PlatformOllamaCloud:
|
||||
// 与 adaptive 分支(defaultCNProtocolBaseURL)同源:官方 Anthropic
|
||||
// 兼容端点不带 /v1 前缀。缺失时 pinned-anthropic 的 ollama_cloud 账号
|
||||
// 会拿到空 base,转发与连接测试都报「no anthropic protocol base url」。
|
||||
return DefaultOllamaCloudAnthropicBaseURL
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
return a.defaultProviderBaseURL(APIProtocolAnthropic)
|
||||
}
|
||||
|
||||
// GetOpenAIFormatBaseURL 返回供 OpenAI 格式端点(/v1/models、/v1/chat/completions
|
||||
@@ -1701,26 +1613,10 @@ func (a *Account) GetOpenAIFormatBaseURL() string {
|
||||
if a == nil || !a.IsAnthropicProtocol() {
|
||||
return a.GetOpenAIBaseURL()
|
||||
}
|
||||
switch a.Platform {
|
||||
case PlatformKimi:
|
||||
if a.GetAccountMode() == AccountModeCoding {
|
||||
return DefaultKimiCodingBaseURL
|
||||
}
|
||||
return DefaultKimiPayGBaseURL
|
||||
case PlatformZhipu:
|
||||
if a.GetAccountMode() == AccountModeCoding {
|
||||
return DefaultZhipuCodingBaseURL
|
||||
}
|
||||
return DefaultZhipuPayGBaseURL
|
||||
case PlatformDeepseek:
|
||||
return DefaultDeepseekBaseURL
|
||||
case PlatformMiniMax:
|
||||
return DefaultMiniMaxBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
return a.openCodeDefaultChatBaseURL()
|
||||
default:
|
||||
return a.GetOpenAIBaseURL()
|
||||
if baseURL := a.defaultProviderBaseURL(APIProtocolChatCompletions); baseURL != "" {
|
||||
return baseURL
|
||||
}
|
||||
return a.GetOpenAIBaseURL()
|
||||
}
|
||||
|
||||
// GetCNAPIKey 返回国产 OpenAI 兼容供应商账号的 api_key 凭据(kimi/zhipu/deepseek)。
|
||||
@@ -1732,7 +1628,8 @@ func (a *Account) GetCNAPIKey() string {
|
||||
return a.GetCredential("api_key")
|
||||
}
|
||||
|
||||
// GetCodingPlanProvider 根据 base_url 识别 Coding Plan 供应商(kimi / zhipu / minimax),
|
||||
// GetCodingPlanProvider 根据 base_url 识别 Coding Plan 供应商(kimi / zhipu / minimax;
|
||||
// OpenCode Go 订阅与官方主机上的 Command Code、Cline 账号按平台识别),
|
||||
// 用于路由到对应的额度查询端点。非 coding 模式或无法识别时返回空串。
|
||||
// 只认官方域名:自定义中转不得把第三方 Key 发往厂商官方额度端点。
|
||||
func (a *Account) GetCodingPlanProvider() string {
|
||||
@@ -1742,6 +1639,18 @@ func (a *Account) GetCodingPlanProvider() string {
|
||||
if a.IsOpenCodeGoPlan() {
|
||||
return PlatformOpenCodeGo
|
||||
}
|
||||
if a.IsCommandCode() {
|
||||
if a.commandCodeUsageSupported() {
|
||||
return PlatformCommandCode
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if a.IsCline() {
|
||||
if a.clineAccountAPISupported() {
|
||||
return PlatformCline
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if a.GetAccountMode() != AccountModeCoding {
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -77,10 +77,10 @@ func (a *Account) IsHeaderOverrideEligible() bool {
|
||||
if a == nil {
|
||||
return false
|
||||
}
|
||||
switch a.Platform {
|
||||
case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud:
|
||||
switch {
|
||||
case a.Platform == PlatformAnthropic, a.Platform == PlatformOpenAI, IsMultiProtocolAPIKeyProvider(a.Platform):
|
||||
return a.Type == AccountTypeAPIKey
|
||||
case PlatformGrok:
|
||||
case a.Platform == PlatformGrok:
|
||||
return a.Type == AccountTypeAPIKey || a.Type == AccountTypeOAuth
|
||||
default:
|
||||
return false
|
||||
|
||||
@@ -58,7 +58,7 @@ func EvaluateAccountSchedulingThreshold(account *Account, thresholds map[string]
|
||||
winner = pickLatestResetSchedulingCandidate(anthropicThresholdCandidates(account), threshold, now)
|
||||
case PlatformGrok:
|
||||
winner = pickLatestResetSchedulingCandidate(grokThresholdCandidates(account), threshold, now)
|
||||
case PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformOpenCodeGo:
|
||||
case PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode:
|
||||
winner = pickLatestResetSchedulingCandidate(cnProviderThresholdCandidates(account, decision.Platform), threshold, now)
|
||||
case PlatformOllamaCloud:
|
||||
winner = pickLatestResetSchedulingCandidate(ollamaCloudThresholdCandidates(account), threshold, now)
|
||||
@@ -355,25 +355,33 @@ func grokThresholdCandidates(account *Account) []*accountSchedulingThresholdCand
|
||||
}
|
||||
}
|
||||
|
||||
// cnProviderThresholdCandidates 读取国产供应商 Coding Plan 账号的 5h / weekly 滚动窗口
|
||||
// 用量快照(由 CNProviderQuotaService 写入 account.Extra,键形如
|
||||
// <provider>_5h_used_percent / <provider>_weekly_reset_at)。payg 账号无此快照,
|
||||
// cnProviderThresholdCandidates 读取国产供应商 Coding Plan、OpenCode Go 与 Command Code
|
||||
// 账号的 5h / weekly(及月度)窗口用量快照(由 CNProviderQuotaService 写入 account.Extra,
|
||||
// 键形如 <provider>_5h_used_percent / <provider>_weekly_reset_at)。payg 账号无此快照,
|
||||
// 候选为空 → 不触发阈值停调(余额型走余额检测)。与 openai 的快照驱动停调一致:
|
||||
// 仅当用量超阈值且窗口尚未重置时才停调。
|
||||
func cnProviderThresholdCandidates(account *Account, provider string) []*accountSchedulingThresholdCandidate {
|
||||
if account == nil || len(account.Extra) == 0 {
|
||||
return nil
|
||||
}
|
||||
if provider == PlatformCommandCode && !commandCodeWindowsBinding(account.Extra) {
|
||||
return nil
|
||||
}
|
||||
candidates := []*accountSchedulingThresholdCandidate{
|
||||
cnThresholdCandidate(account.Extra, provider, "5h"),
|
||||
cnThresholdCandidate(account.Extra, provider, "weekly"),
|
||||
}
|
||||
if provider == PlatformOpenCodeGo {
|
||||
if cnQuotaHasMonthlyWindow(provider) {
|
||||
candidates = append(candidates, cnThresholdCandidate(account.Extra, provider, "monthly"))
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、Command Code)。
|
||||
func cnQuotaHasMonthlyWindow(provider string) bool {
|
||||
return provider == PlatformOpenCodeGo || provider == PlatformCommandCode
|
||||
}
|
||||
|
||||
func cnThresholdCandidate(extra map[string]any, provider, window string) *accountSchedulingThresholdCandidate {
|
||||
var usedKey, resetKey string
|
||||
switch window {
|
||||
|
||||
@@ -545,11 +545,12 @@ func (s *AccountService) TestCredentials(ctx context.Context, id int64) error {
|
||||
case PlatformTypeSafe:
|
||||
// TypeSafe credentials are API keys; inference failures drive health and cooldown state.
|
||||
return nil
|
||||
case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud:
|
||||
// 国产 OpenAI 兼容供应商、OpenCode 与 Ollama Cloud:凭证为 API Key,
|
||||
// 实际可用性经余额/额度探测与转发路径验证。
|
||||
return nil
|
||||
default:
|
||||
if IsMultiProtocolAPIKeyProvider(account.Platform) {
|
||||
// 多协议 API Key 供应商(国产厂商与聚合平台):凭证为 API Key,实际可用性
|
||||
// 经余额/额度探测与转发路径验证。
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unsupported platform: %s", account.Platform)
|
||||
}
|
||||
}
|
||||
@@ -385,7 +385,14 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int
|
||||
}
|
||||
|
||||
// Route to platform-specific test method
|
||||
if account.IsCNProvider() {
|
||||
// Ollama Cloud 有专属测试路径(默认测试模型取账号可出站模型、原生 Responses 探针),
|
||||
// 须先于下面按入站协议分流的通用分支。
|
||||
if account.IsOllamaCloud() {
|
||||
return s.testOllamaCloudAccountConnection(c, account, modelID, prompt)
|
||||
}
|
||||
|
||||
// 按入站协议分流的多协议供应商(国产厂商等):按账号协议选测试路径。
|
||||
if account.RoutesProtocolByInbound() {
|
||||
switch account.GetAPIProtocol() {
|
||||
case APIProtocolAdaptive:
|
||||
return s.testCNProviderAdaptiveConnection(c, account, modelID, prompt)
|
||||
@@ -414,44 +421,44 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int
|
||||
return s.routeAntigravityTest(c, account, modelID, prompt)
|
||||
}
|
||||
|
||||
if account.IsOpenCodeGo() {
|
||||
return s.testOpenCodeGoAccountConnection(c, account, modelID, prompt)
|
||||
// 按模型分流的多模型聚合平台(OpenCode、Command Code 等)。
|
||||
if account.routesByModel() {
|
||||
return s.testModelRoutedAccountConnection(c, account, modelID, prompt)
|
||||
}
|
||||
|
||||
if account.IsTypeSafe() {
|
||||
return s.testTypeSafeAccountConnection(c, account, prompt)
|
||||
}
|
||||
|
||||
if account.IsOllamaCloud() {
|
||||
return s.testOllamaCloudAccountConnection(c, account, modelID, prompt)
|
||||
}
|
||||
|
||||
return s.testClaudeAccountConnection(c, account, modelID)
|
||||
}
|
||||
|
||||
// testOpenCodeGoAccountConnection probes the native endpoint for the selected
|
||||
// model. Adaptive accounts (the default) follow OpenCodeGoModelProtocol:
|
||||
// testModelRoutedAccountConnection probes the native endpoint for the selected
|
||||
// model on providers that route by model (see ProviderRoutingByModel). Adaptive
|
||||
// accounts (the default) follow the provider's protocol rules, e.g. OpenCode Go:
|
||||
// grok/gpt/muse-spark → Responses, minimax/qwen → Anthropic, everything else
|
||||
// (including deepseek-v4-flash) → Chat Completions. A pinned api_protocol
|
||||
// overrides that catalog. Falling through to the generic Claude tester used
|
||||
// credentials.base_url + /v1/messages?beta=true, which 404s as HTML on
|
||||
// https://opencode.ai/zen/go/v1/v1/messages.
|
||||
func (s *AccountTestService) testOpenCodeGoAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
|
||||
func (s *AccountTestService) testModelRoutedAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
|
||||
testModelID := strings.TrimSpace(modelID)
|
||||
if testModelID == "" {
|
||||
testModelID = DefaultOpenCodeGoTestModel
|
||||
testModelID = account.providerDefaultTestModel()
|
||||
}
|
||||
if testModelID == "" {
|
||||
testModelID = openai.DefaultTestModel
|
||||
}
|
||||
testModelID = account.GetMappedModel(testModelID)
|
||||
if IsOpenCodeUnsupportedModel(testModelID) {
|
||||
if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(testModelID) {
|
||||
return fmt.Errorf("model %q is not supported on OpenCode standard gateway (gemini models require Google SDK endpoint, jev models require System One endpoint)", testModelID)
|
||||
}
|
||||
proto := account.GetAPIProtocol()
|
||||
switch proto {
|
||||
case APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses:
|
||||
default:
|
||||
proto = openCodeGoNativeProtocol(account, testModelID)
|
||||
// 与网关同一判定(含上游模型目录);测试没有入站协议,取模型的首选协议。
|
||||
protocol := account.resolveModelRoutedProtocol(testModelID)
|
||||
if s.openaiGatewayService != nil {
|
||||
protocol = s.openaiGatewayService.resolveUpstreamProtocolFor(c.Request.Context(), account, "", testModelID)
|
||||
}
|
||||
switch proto {
|
||||
switch protocol {
|
||||
case APIProtocolAnthropic:
|
||||
return s.testCNProviderAnthropicConnection(c, account, testModelID)
|
||||
case APIProtocolResponses:
|
||||
@@ -517,6 +524,9 @@ func defaultOllamaCloudTestModel(account *Account) string {
|
||||
|
||||
func (s *AccountTestService) testCNProviderChatCompletionsConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
|
||||
testModelID := strings.TrimSpace(modelID)
|
||||
if testModelID == "" {
|
||||
testModelID = account.providerDefaultTestModel()
|
||||
}
|
||||
if testModelID == "" {
|
||||
testModelID = openai.DefaultTestModel
|
||||
}
|
||||
|
||||
@@ -18,14 +18,19 @@ import (
|
||||
const accountTestSuppressCompletionContextKey = "account_test_suppress_completion"
|
||||
|
||||
// testCNProviderAdaptiveConnection verifies every native endpoint used by an
|
||||
// adaptive CN-provider account. Zhipu uses Chat Completions plus Anthropic;
|
||||
// DeepSeek and Kimi additionally use their native Responses endpoints.
|
||||
// adaptive account of a provider that routes by inbound protocol. Zhipu uses
|
||||
// Chat Completions plus Anthropic; DeepSeek and Kimi additionally use their
|
||||
// native Responses endpoints. Endpoints the provider profile does not offer are
|
||||
// skipped.
|
||||
func (s *AccountTestService) testCNProviderAdaptiveConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
|
||||
testModelID := strings.TrimSpace(modelID)
|
||||
if testModelID == "" {
|
||||
testModelID = openai.DefaultTestModel
|
||||
requestedModelID := strings.TrimSpace(modelID)
|
||||
if requestedModelID == "" {
|
||||
requestedModelID = account.providerDefaultTestModel()
|
||||
}
|
||||
testModelID = account.GetMappedModel(testModelID)
|
||||
if requestedModelID == "" {
|
||||
requestedModelID = openai.DefaultTestModel
|
||||
}
|
||||
testModelID := account.GetMappedModel(requestedModelID)
|
||||
|
||||
authToken := strings.TrimSpace(account.GetOpenAIProtocolAPIKey())
|
||||
if authToken == "" {
|
||||
@@ -36,12 +41,14 @@ func (s *AccountTestService) testCNProviderAdaptiveConnection(c *gin.Context, ac
|
||||
// completion events until every native adaptive endpoint has passed.
|
||||
c.Set(accountTestSuppressCompletionContextKey, true)
|
||||
defer c.Set(accountTestSuppressCompletionContextKey, false)
|
||||
if err := s.testCNProviderChatCompletionsConnection(c, account, modelID, prompt); err != nil {
|
||||
if err := s.testCNProviderChatCompletionsConnection(c, account, requestedModelID, prompt); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.testCNProviderAdaptiveAnthropicConnection(c, account, testModelID, authToken); err != nil {
|
||||
return err
|
||||
if account.providerSupportsProtocol(APIProtocolAnthropic) {
|
||||
if err := s.testCNProviderAdaptiveAnthropicConnection(c, account, testModelID, authToken); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if account.SupportsNativeCNResponses() {
|
||||
@@ -240,10 +247,10 @@ func (s *AccountTestService) testCNProviderAnthropicConnection(c *gin.Context, a
|
||||
if err != nil {
|
||||
return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid Anthropic base URL: %s", err.Error()))
|
||||
}
|
||||
if hint := cnAnthropicBaseURLMisconfigHint(baseURL); hint != "" {
|
||||
if hint := cnAnthropicBaseURLMisconfigHint(baseURL, account.routesByModel()); hint != "" {
|
||||
return s.sendErrorAndEnd(c, hint)
|
||||
}
|
||||
apiURL := strings.TrimRight(baseURL, "/") + "/v1/messages"
|
||||
apiURL := nativeAnthropicMessagesURL(account, baseURL)
|
||||
|
||||
c.Writer.Header().Set("Content-Type", "text/event-stream")
|
||||
c.Writer.Header().Set("Cache-Control", "no-cache")
|
||||
@@ -298,7 +305,9 @@ func (s *AccountTestService) testCNProviderAnthropicConnection(c *gin.Context, a
|
||||
// endpoint (paas path, version segment, or chat/completions / responses
|
||||
// suffix). The naive {base}/v1/messages join would 404 (e.g.
|
||||
// .../api/paas/v4/v1/messages) with no hint about the actual misconfiguration.
|
||||
func cnAnthropicBaseURLMisconfigHint(baseURL string) string {
|
||||
// versionAware is set for providers whose join is version-aware (see
|
||||
// nativeAnthropicMessagesURL), where a trailing version segment is valid.
|
||||
func cnAnthropicBaseURLMisconfigHint(baseURL string, versionAware bool) string {
|
||||
parsed, err := url.Parse(strings.TrimSpace(baseURL))
|
||||
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
|
||||
return ""
|
||||
@@ -310,7 +319,7 @@ func cnAnthropicBaseURLMisconfigHint(baseURL string) string {
|
||||
openAICompatShaped := strings.Contains(path, "/paas/") ||
|
||||
strings.HasSuffix(path, "/chat/completions") ||
|
||||
strings.HasSuffix(path, "/responses") ||
|
||||
openAIBaseURLHasVersionSuffix(path)
|
||||
(!versionAware && openAIBaseURLHasVersionSuffix(path))
|
||||
if !openAICompatShaped {
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -323,7 +323,7 @@ func (s *adminServiceImpl) DuplicateAccount(ctx context.Context, id int64, actor
|
||||
if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := NormalizeOpenCodeGoProtocolRulesCredentials(input.Credentials); err != nil {
|
||||
if err := NormalizeProtocolRulesCredentials(input.Credentials); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
duplicate, err := buildAccountForCreate(input, accountExtra)
|
||||
@@ -528,7 +528,7 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
|
||||
if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := NormalizeOpenCodeGoProtocolRulesCredentials(input.Credentials); err != nil {
|
||||
if err := NormalizeProtocolRulesCredentials(input.Credentials); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Never persist ephemeral SSO/password secrets after OAuth conversion.
|
||||
@@ -669,7 +669,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if err := NormalizeHeaderOverrideCredentials(account.Credentials); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := NormalizeOpenCodeGoProtocolRulesCredentials(account.Credentials); err != nil {
|
||||
if err := NormalizeProtocolRulesCredentials(account.Credentials); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Strip SSO/password residue that must never sit next to OAuth tokens.
|
||||
@@ -1131,7 +1131,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := NormalizeOpenCodeGoProtocolRulesCredentials(input.Credentials); err != nil {
|
||||
if err := NormalizeProtocolRulesCredentials(input.Credentials); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Bulk may mix platforms; always drop ephemeral SSO/password keys (cookie
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
@@ -321,10 +322,13 @@ func defaultAllowImageGenerationForPlatform(platform string) bool {
|
||||
func compositeDefaultModelsListCandidateIDs() []string {
|
||||
seen := make(map[string]struct{})
|
||||
ids := make([]string, 0)
|
||||
// TypeSafe stays out of the static composite candidates (jev-latest only works
|
||||
// through /v1/systemone); groups with TypeSafe accounts still get it from the
|
||||
// account model mappings collected by GetGroupModelsListCandidates.
|
||||
for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud} {
|
||||
for _, platform := range domain.CompositePrecedencePlatformIDs() {
|
||||
// TypeSafe stays out of the static composite candidates (jev-latest only works
|
||||
// through /v1/systemone); groups with TypeSafe accounts still get it from the
|
||||
// account model mappings collected by GetGroupModelsListCandidates.
|
||||
if platform == PlatformTypeSafe {
|
||||
continue
|
||||
}
|
||||
for _, id := range defaultModelsListCandidateIDs(platform) {
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
|
||||
@@ -24,7 +24,7 @@ func (a *Account) GetAnthropicAPIKeyAuthScheme() string {
|
||||
if a == nil || a.Type != AccountTypeAPIKey {
|
||||
return AnthropicAPIKeyAuthSchemeXAPIKey
|
||||
}
|
||||
if a.Platform != PlatformAnthropic && !a.IsCNProvider() && a.Platform != PlatformOllamaCloud {
|
||||
if a.Platform != PlatformAnthropic && !a.RoutesProtocolByInbound() {
|
||||
return AnthropicAPIKeyAuthSchemeXAPIKey
|
||||
}
|
||||
|
||||
|
||||
@@ -1937,9 +1937,9 @@ func (s *AuthService) snapshotPlatformQuotaDefaults(ctx context.Context, userID
|
||||
return nil
|
||||
}
|
||||
// 平台配额快照是 best-effort(fail-open):必须脱离调用方事务执行。
|
||||
// 否则某平台违反 user_platform_quotas 的 CHECK 约束(如尚未进约束的新平台)会让
|
||||
// 整个调用方事务被 Postgres 标记 aborted,把"无关紧要的默认配额快照"放大成
|
||||
// "整笔注册失败"(OAuth pending 路径曾因此 500 → 清 cookie → 404)。
|
||||
// 否则写入时的任何数据库错误(历史上是新平台尚未加入 user_platform_quotas 的
|
||||
// CHECK 约束)都会让整个调用方事务被 Postgres 标记 aborted,把"无关紧要的默认
|
||||
// 配额快照"放大成"整笔注册失败"(OAuth pending 路径曾因此 500 → 清 cookie → 404)。
|
||||
ctx = dbent.WithoutTx(ctx)
|
||||
// 仅为至少配置了一档限额的平台建行:user_platform_quotas 中不存在的行等价于不限额,
|
||||
// 三档全空的记录不携带任何可执行的限额。
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
@@ -368,7 +369,7 @@ func isPlatformPricingMatch(groupPlatform, pricingPlatform string) bool {
|
||||
// fallback used before a request target has been resolved.
|
||||
func matchingPlatforms(groupPlatform string) []string {
|
||||
if groupPlatform == PlatformComposite {
|
||||
return []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud}
|
||||
return domain.CompositePrecedencePlatformIDs()
|
||||
}
|
||||
return []string{groupPlatform}
|
||||
}
|
||||
|
||||
@@ -2127,7 +2127,7 @@ func TestMatchingPlatforms(t *testing.T) {
|
||||
{"anthropic returns itself", PlatformAnthropic, []string{PlatformAnthropic}},
|
||||
{"gemini returns itself", PlatformGemini, []string{PlatformGemini}},
|
||||
{"openai returns itself", PlatformOpenAI, []string{PlatformOpenAI}},
|
||||
{"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud}},
|
||||
{"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformCommandCode, PlatformCline, PlatformOllamaCloud}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Cline API(https://docs.cline.bot/api/overview):OpenAI 兼容的多模型聚合端点,
|
||||
// 基址 https://api.cline.bot/api/v1,只提供 Chat Completions(Cline 自己的客户端同样
|
||||
// 只走该端点),模型名带厂商前缀(如 anthropic/claude-sonnet-4-6)。Responses 与
|
||||
// Anthropic 入站由网关转换为 Chat Completions。
|
||||
//
|
||||
// 同一个 API Key 下有两个互不影响的额度来源(下称"钱包"),由模型名决定扣哪一个:
|
||||
// - 积分:cline-pass/* 与 cline-free/* 以外的模型按量扣账户积分,余额可查;
|
||||
// - ClinePass 订阅:cline-pass/* 模型,受 5 小时 / 7 天 / 30 天三档滚动用量上限限制,
|
||||
// 各档已用百分比与重置时间可查(/api/v1/users/me/plan/usage-limits);
|
||||
// - cline-free/* 免费模型不扣任何一边,只有逐模型的每日额度。
|
||||
//
|
||||
// 一边用完只影响该边的模型,所以超限冷却按钱包落在模型级冷却键上(见
|
||||
// clineWalletRateLimitKey),不停整个账号,也不需要管理员声明账号类型。
|
||||
|
||||
const (
|
||||
// DefaultClineTestModel 是连接测试的默认模型(按量积分,价格低、长期在售)。
|
||||
DefaultClineTestModel = "deepseek/deepseek-v4-flash"
|
||||
// DefaultClinePassTestModel 是订阅了 ClinePass 的账号连接测试的默认模型。
|
||||
DefaultClinePassTestModel = "cline-pass/glm-5.3-flash"
|
||||
|
||||
clineAPIHost = "api.cline.bot"
|
||||
|
||||
clinePassModelPrefix = "cline-pass/"
|
||||
clineFreeModelPrefix = "cline-free/"
|
||||
|
||||
// clinePassRateLimitKey / clineCreditsRateLimitKey 是两个钱包的模型级冷却键:
|
||||
// 命中后该钱包的全部模型都不再调度到该账号,另一边不受影响。
|
||||
clinePassRateLimitKey = "cline:pass"
|
||||
clineCreditsRateLimitKey = "cline:credits"
|
||||
)
|
||||
|
||||
// IsCline 报告账号是否为 Cline 平台账号。
|
||||
func (a *Account) IsCline() bool {
|
||||
return a != nil && a.Platform == PlatformCline
|
||||
}
|
||||
|
||||
// clineWalletRateLimitKey 返回模型所属钱包的冷却键;免费模型不属于任何钱包,返回空串。
|
||||
func clineWalletRateLimitKey(model string) string {
|
||||
model = strings.ToLower(strings.TrimSpace(model))
|
||||
switch {
|
||||
case model == "":
|
||||
return ""
|
||||
case strings.HasPrefix(model, clinePassModelPrefix):
|
||||
return clinePassRateLimitKey
|
||||
case strings.HasPrefix(model, clineFreeModelPrefix):
|
||||
return ""
|
||||
default:
|
||||
return clineCreditsRateLimitKey
|
||||
}
|
||||
}
|
||||
|
||||
// isOfficialClineHost 报告 URL 是否指向官方 Cline API 主机。
|
||||
func isOfficialClineHost(target string) bool {
|
||||
parsed, err := url.Parse(strings.TrimSpace(target))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(parsed.Scheme, "https") && strings.EqualFold(parsed.Hostname(), clineAPIHost)
|
||||
}
|
||||
|
||||
// clineAccountAPISupported 报告账号能否查询积分余额与 ClinePass 用量:API Key 账号且
|
||||
// 推理端点指向官方主机。自定义中转的 Key 不发往官方账号接口。
|
||||
func (a *Account) clineAccountAPISupported() bool {
|
||||
return a.IsCline() && a.Type == AccountTypeAPIKey && isOfficialClineHost(a.GetOpenAIBaseURL())
|
||||
}
|
||||
|
||||
// clinePassSubscribed 报告最近一次用量探测是否显示账号订阅了 ClinePass(有窗口快照)。
|
||||
func (a *Account) clinePassSubscribed() bool {
|
||||
if a == nil || a.Extra == nil {
|
||||
return false
|
||||
}
|
||||
for _, suffix := range []string{cnExtraSuffix5hUsed, cnExtraSuffixWeeklyUsed, cnExtraSuffixMonthlyUsed} {
|
||||
if value, ok := a.Extra[cnExtraKey(PlatformCline, suffix)]; ok && value != nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,648 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// clineTestAccount 只带 api_key:端点与测试模型全部来自 provider profile。
|
||||
func clineTestAccount(id int64) *Account {
|
||||
return &Account{
|
||||
ID: id,
|
||||
Name: "cline",
|
||||
Platform: PlatformCline,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "cline_test_key", "api_protocol": APIProtocolAdaptive},
|
||||
}
|
||||
}
|
||||
|
||||
// withClinePassSnapshot 模拟用量探测写入的 ClinePass 窗口快照。
|
||||
func withClinePassSnapshot(account *Account, extra map[string]any) *Account {
|
||||
account.Extra = map[string]any{"cline_5h_used_percent": 10.0, "cline_weekly_used_percent": 20.0, "cline_monthly_used_percent": 30.0}
|
||||
for key, value := range extra {
|
||||
account.Extra[key] = value
|
||||
}
|
||||
return account
|
||||
}
|
||||
|
||||
func TestClineProfileSingleModeChatCompletionsOnly(t *testing.T) {
|
||||
profile := LookupProviderProfile(PlatformCline)
|
||||
require.NotNil(t, profile)
|
||||
require.Len(t, profile.Modes, 1)
|
||||
|
||||
account := clineTestAccount(1)
|
||||
require.True(t, account.IsMultiProtocolAPIKey())
|
||||
require.True(t, account.RoutesProtocolByInbound())
|
||||
require.False(t, account.routesByModel())
|
||||
require.Equal(t, APIProtocolAdaptive, account.GetAPIProtocol())
|
||||
require.Equal(t, DefaultClineBaseURL, account.GetOpenAIBaseURL())
|
||||
require.False(t, account.SupportsNativeCNResponses())
|
||||
require.False(t, account.providerSupportsProtocol(APIProtocolAnthropic))
|
||||
for _, inbound := range []string{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolAnthropic} {
|
||||
require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, inbound, "anthropic/claude-sonnet-4-6", nil), inbound)
|
||||
}
|
||||
|
||||
require.False(t, account.clinePassSubscribed())
|
||||
require.Equal(t, DefaultClineTestModel, account.providerDefaultTestModel())
|
||||
subscribed := withClinePassSnapshot(clineTestAccount(2), nil)
|
||||
require.True(t, subscribed.clinePassSubscribed())
|
||||
require.Equal(t, DefaultClinePassTestModel, subscribed.providerDefaultTestModel())
|
||||
// 取消订阅后探测把窗口写成 nil。
|
||||
cancelled := withClinePassSnapshot(clineTestAccount(3), map[string]any{
|
||||
"cline_5h_used_percent": nil, "cline_weekly_used_percent": nil, "cline_monthly_used_percent": nil,
|
||||
})
|
||||
require.False(t, cancelled.clinePassSubscribed())
|
||||
}
|
||||
|
||||
// 经真实入口:三种入站都转换 / 直通到 Chat Completions,模型名带厂商前缀原样发往上游。
|
||||
func TestClineGatewayForwardsToChatCompletions(t *testing.T) {
|
||||
for _, ingress := range routingMatrixIngresses() {
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
body := routingMatrixCase{ingress: ingress, model: "anthropic/claude-sonnet-4-6"}.body()
|
||||
_ = ingress.forward(svc, adaptiveProtocolTestContext(ingress.path, body), clineTestAccount(3), body)
|
||||
|
||||
require.NotEmpty(t, upstream.requests, ingress.name)
|
||||
require.Equal(t, "https://api.cline.bot/api/v1/chat/completions", upstream.requests[len(upstream.requests)-1].URL.String(), ingress.name)
|
||||
require.Equal(t, "Bearer cline_test_key", upstream.requests[len(upstream.requests)-1].Header.Get("Authorization"), ingress.name)
|
||||
require.True(t, gjson.GetBytes(upstream.lastBody, "messages").Exists(), ingress.name)
|
||||
require.Equal(t, "anthropic/claude-sonnet-4-6", gjson.GetBytes(upstream.lastBody, "model").String(), ingress.name)
|
||||
}
|
||||
}
|
||||
|
||||
// 连接测试未指定模型时:订阅了 ClinePass 用订阅模型(不消耗积分),否则用按量模型;
|
||||
// ClinePass 钱包冷却中也用按量模型;自适应与固定 Chat Completions 一致。
|
||||
func TestAccountTestService_ClineDefaultTestModel(t *testing.T) {
|
||||
cases := []struct {
|
||||
subscribed bool
|
||||
passCooling bool
|
||||
apiProtocol string
|
||||
want string
|
||||
}{
|
||||
{false, false, "", DefaultClineTestModel},
|
||||
{true, false, "", DefaultClinePassTestModel},
|
||||
{false, false, APIProtocolChatCompletions, DefaultClineTestModel},
|
||||
{true, false, APIProtocolChatCompletions, DefaultClinePassTestModel},
|
||||
{true, true, "", DefaultClineTestModel},
|
||||
}
|
||||
for i, tc := range cases {
|
||||
account := clineTestAccount(int64(600 + i))
|
||||
if tc.subscribed {
|
||||
withClinePassSnapshot(account, nil)
|
||||
}
|
||||
if tc.passCooling {
|
||||
now := time.Now()
|
||||
setAccountModelRateLimitSnapshot(account, clinePassRateLimitKey, now.Add(time.Hour), clinePassLimitReason, now)
|
||||
}
|
||||
if tc.apiProtocol != "" {
|
||||
account.Credentials["api_protocol"] = tc.apiProtocol
|
||||
}
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err, tc)
|
||||
require.Len(t, upstream.requests, 1, tc)
|
||||
require.Equal(t, "https://api.cline.bot/api/v1/chat/completions", upstream.requests[0].URL.String(), tc)
|
||||
require.Equal(t, tc.want, gjson.GetBytes(upstream.lastBody, "model").String(), tc)
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`, tc)
|
||||
}
|
||||
}
|
||||
|
||||
// 响应体样例取自 Cline 客户端的判定文案与官方错误文档。
|
||||
const (
|
||||
clineInsufficientCreditsBody = `{"error":{"code":"insufficient_credits","message":"Insufficient credits","details":{"current_balance":0}}}`
|
||||
clineSpendLimitBody = `{"error":{"code":"SPEND_LIMIT_EXCEEDED","message":"Organization spend limit exceeded"}}`
|
||||
clineInferenceCapBody = `{"error":{"code":"INFERENCE_CAP_ERROR","message":"Inference cap reached"}}`
|
||||
clinePass5hBody = `{"error":{"code":429,"message":"You have reached your 5-hour ClinePass limit. Please try again later."}}`
|
||||
clinePassWeeklyBody = `{"error":{"code":429,"message":"You have reached your weekly ClinePass limit. Please try again later."}}`
|
||||
clinePassMonthlyBody = `{"error":{"code":429,"message":"You have reached your monthly ClinePass limit. Please try again later."}}`
|
||||
clineNotSubscribedBody = `{"error":{"code":403,"message":"The user is not subscribed to required model plan"}}`
|
||||
clineOrgPassBody = `{"error":{"code":403,"message":"Organization accounts cannot use individual model inference subscriptions"}}`
|
||||
clineFreeModelLimitBody = `{"error":{"code":429,"message":"Free limit reached on model cline-free/kimi-k3. Try again in 3h 20m"}}`
|
||||
clineRateLimitBody = `{"error":{"code":429,"message":"Rate limit exceeded"}}`
|
||||
)
|
||||
|
||||
func TestClassifyClineError(t *testing.T) {
|
||||
cases := map[string]clineErrorKind{
|
||||
clineInsufficientCreditsBody: clineCreditsExhausted,
|
||||
clineSpendLimitBody: clineSpendLimit,
|
||||
clineInferenceCapBody: clineInferenceCap,
|
||||
clinePass5hBody: clinePassLimit,
|
||||
clinePassWeeklyBody: clinePassLimit,
|
||||
clineNotSubscribedBody: clinePassUnavailable,
|
||||
clineOrgPassBody: clinePassUnavailable,
|
||||
clineFreeModelLimitBody: clineFreeModelLimit,
|
||||
clineRateLimitBody: clineErrorNone,
|
||||
`{"error":{"message":"You have reached your limit. Please try again later."}}`: clineErrorNone,
|
||||
}
|
||||
for body, want := range cases {
|
||||
kind, _ := parseClineError([]byte(body))
|
||||
require.Equal(t, want, kind, body)
|
||||
}
|
||||
|
||||
require.Equal(t, "5h", clinePassWindow([]byte(clinePass5hBody)))
|
||||
require.Equal(t, "weekly", clinePassWindow([]byte(clinePassWeeklyBody)))
|
||||
require.Equal(t, "monthly", clinePassWindow([]byte(clinePassMonthlyBody)))
|
||||
require.Equal(t, 3*time.Hour+20*time.Minute, clineFreeModelResetAfter([]byte(clineFreeModelLimitBody)))
|
||||
require.Zero(t, clineFreeModelResetAfter([]byte(`Free limit reached on model x. Try again in 3 weeks`)))
|
||||
}
|
||||
|
||||
// ClinePass 超限冷却到快照中该窗口的重置时间;没有可用快照时按窗口估计。
|
||||
func TestClinePassLimitCooldown(t *testing.T) {
|
||||
now := time.Now()
|
||||
require.Equal(t, clineLimitRecheck, clinePassLimitCooldown(clineTestAccount(1), "5h", now))
|
||||
require.Equal(t, clinePassWeeklyRecheck, clinePassLimitCooldown(clineTestAccount(1), "weekly", now))
|
||||
require.Equal(t, clinePassMonthlyRecheck, clinePassLimitCooldown(clineTestAccount(1), "monthly", now))
|
||||
|
||||
account := withClinePassSnapshot(clineTestAccount(2), map[string]any{
|
||||
"cline_weekly_reset_at": now.Add(50 * time.Hour).UTC().Format(time.RFC3339),
|
||||
"cline_5h_reset_at": now.Add(-time.Minute).UTC().Format(time.RFC3339),
|
||||
})
|
||||
require.InDelta(t, (50 * time.Hour).Seconds(), clinePassLimitCooldown(account, "weekly", now).Seconds(), 1)
|
||||
require.Equal(t, clineLimitRecheck, clinePassLimitCooldown(account, "5h", now), "past reset falls back to the estimate")
|
||||
}
|
||||
|
||||
// cline-pass/* 与其余付费模型各自落在钱包冷却键上,免费模型不属于任何钱包;调度按
|
||||
// 请求模型检查所属钱包。
|
||||
func TestClineWalletRateLimitKeys(t *testing.T) {
|
||||
require.Equal(t, clinePassRateLimitKey, clineWalletRateLimitKey("cline-pass/glm-5.3"))
|
||||
require.Equal(t, clinePassRateLimitKey, clineWalletRateLimitKey(" Cline-Pass/GLM-5.3 "))
|
||||
require.Equal(t, clineCreditsRateLimitKey, clineWalletRateLimitKey("deepseek/deepseek-v4-flash"))
|
||||
require.Empty(t, clineWalletRateLimitKey("cline-free/kimi-k3"))
|
||||
require.Empty(t, clineWalletRateLimitKey(""))
|
||||
|
||||
account := clineTestAccount(1)
|
||||
setAccountModelRateLimitSnapshot(account, clinePassRateLimitKey, time.Now().Add(time.Hour), clinePassLimitReason, time.Now())
|
||||
ctx := context.Background()
|
||||
require.True(t, account.isModelRateLimitedWithContext(ctx, "cline-pass/glm-5.3"))
|
||||
require.False(t, account.isModelRateLimitedWithContext(ctx, "deepseek/deepseek-v4-flash"))
|
||||
require.False(t, account.isModelRateLimitedWithContext(ctx, "cline-free/kimi-k3"))
|
||||
|
||||
setAccountModelRateLimitSnapshot(account, clineCreditsRateLimitKey, time.Now().Add(time.Hour), clineCreditsReason, time.Now())
|
||||
require.True(t, account.isModelRateLimitedWithContext(ctx, "deepseek/deepseek-v4-flash"))
|
||||
require.False(t, account.isModelRateLimitedWithContext(ctx, "cline-free/kimi-k3"))
|
||||
require.Equal(t, clineCreditsReason, account.modelRateLimitReason(clineCreditsRateLimitKey))
|
||||
|
||||
// 其他平台不受 Cline 钱包键影响。
|
||||
other := &Account{Platform: PlatformDeepseek, Extra: account.Extra}
|
||||
require.False(t, other.isModelRateLimitedWithContext(ctx, "cline-pass/glm-5.3"))
|
||||
}
|
||||
|
||||
// 已识别的错误只冷却请求模型所属的钱包(或免费模型本身),不停整个账号、不置 error。
|
||||
func TestHandleUpstreamError_ClineCoolsDownWallet(t *testing.T) {
|
||||
paid := "deepseek/deepseek-v4-flash"
|
||||
pass := "cline-pass/glm-5.3"
|
||||
now := time.Now()
|
||||
snapshot := withClinePassSnapshot(clineTestAccount(1), map[string]any{
|
||||
"cline_5h_reset_at": now.Add(2 * time.Hour).UTC().Format(time.RFC3339),
|
||||
})
|
||||
cases := []struct {
|
||||
name string
|
||||
account *Account
|
||||
model string
|
||||
status int
|
||||
body string
|
||||
scope string
|
||||
wait time.Duration
|
||||
reason string
|
||||
}{
|
||||
{"pass weekly", clineTestAccount(10), pass, http.StatusTooManyRequests, clinePassWeeklyBody, clinePassRateLimitKey, clinePassWeeklyRecheck, clinePassLimitReason},
|
||||
{"pass 5h from snapshot", snapshot, pass, http.StatusTooManyRequests, clinePass5hBody, clinePassRateLimitKey, 2 * time.Hour, clinePassLimitReason},
|
||||
{"not subscribed", clineTestAccount(11), pass, http.StatusForbidden, clineNotSubscribedBody, clinePassRateLimitKey, clineLimitRecheck, clinePassUnavailableReason},
|
||||
{"credits", clineTestAccount(12), paid, http.StatusPaymentRequired, clineInsufficientCreditsBody, clineCreditsRateLimitKey, cnBalanceCheckCooldown(nil), clineCreditsReason},
|
||||
{"unrecognized 402", clineTestAccount(13), paid, http.StatusPaymentRequired, `{"error":{"message":"Payment required"}}`, clineCreditsRateLimitKey, cnBalanceCheckCooldown(nil), clineCreditsReason},
|
||||
{"spend limit", clineTestAccount(14), paid, http.StatusTooManyRequests, clineSpendLimitBody, clineCreditsRateLimitKey, clineLimitRecheck, clineSpendLimitReason},
|
||||
{"inference cap on paid model", clineTestAccount(15), paid, http.StatusTooManyRequests, clineInferenceCapBody, clineCreditsRateLimitKey, clineLimitRecheck, clineInferenceCapReason},
|
||||
{"inference cap on pass model", clineTestAccount(16), pass, http.StatusTooManyRequests, clineInferenceCapBody, clinePassRateLimitKey, clineLimitRecheck, clineInferenceCapReason},
|
||||
{"unknown model uses the error's wallet", clineTestAccount(17), "", http.StatusForbidden, clineOrgPassBody, clinePassRateLimitKey, clineLimitRecheck, clinePassUnavailableReason},
|
||||
{"free model", clineTestAccount(18), "cline-free/kimi-k3", http.StatusTooManyRequests, clineFreeModelLimitBody, "cline-free/kimi-k3", 3*time.Hour + 20*time.Minute, clineFreeModelLimitReason},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
ctx := context.Background()
|
||||
if tc.model != "" {
|
||||
ctx = withTempUnschedulableModel(ctx, []string{tc.model})
|
||||
}
|
||||
repo := &commandCodeRateLimitRepo{}
|
||||
|
||||
shouldDisable := NewRateLimitService(repo, nil, &config.Config{}, nil, nil).HandleUpstreamError(ctx, tc.account,
|
||||
tc.status, http.Header{}, []byte(tc.body))
|
||||
|
||||
require.False(t, shouldDisable, tc.name)
|
||||
require.Equal(t, 0, repo.tempCalls, tc.name)
|
||||
require.Equal(t, 0, repo.setErrorCalls, tc.name)
|
||||
require.Equal(t, 0, repo.rateLimitedCalls, tc.name)
|
||||
require.Len(t, repo.modelLimits, 1, tc.name)
|
||||
require.WithinDuration(t, time.Now().Add(tc.wait), repo.modelLimits[tc.scope], time.Minute, tc.name)
|
||||
require.True(t, strings.HasPrefix(repo.reasons[tc.scope], tc.reason), tc.name+": "+repo.reasons[tc.scope])
|
||||
require.True(t, tc.account.isRateLimitActiveForKey(tc.scope), tc.name)
|
||||
}
|
||||
|
||||
// 普通频率限制交回默认 429 逻辑。
|
||||
plain := &commandCodeRateLimitRepo{}
|
||||
NewRateLimitService(plain, nil, &config.Config{}, nil, nil).HandleUpstreamError(withTempUnschedulableModel(context.Background(), []string{paid}),
|
||||
clineTestAccount(30), http.StatusTooManyRequests, http.Header{}, []byte(clineRateLimitBody))
|
||||
require.Empty(t, plain.modelLimits)
|
||||
require.Equal(t, 0, plain.tempCalls)
|
||||
}
|
||||
|
||||
// clineModelLimitFailRepo 让钱包冷却写入失败。
|
||||
type clineModelLimitFailRepo struct {
|
||||
commandCodeRateLimitRepo
|
||||
}
|
||||
|
||||
func (r *clineModelLimitFailRepo) SetModelRateLimit(context.Context, int64, string, time.Time, ...string) error {
|
||||
return errors.New("db unavailable")
|
||||
}
|
||||
|
||||
// 积分冷却写入失败时 402 也不落入默认分支永久置 error:探测只覆盖激活账号,置 error 后
|
||||
// 充值也无法自动恢复。
|
||||
func TestHandleUpstreamError_Cline402KeepsAccountWhenCooldownWriteFails(t *testing.T) {
|
||||
ctx := withTempUnschedulableModel(context.Background(), []string{"deepseek/deepseek-v4-flash"})
|
||||
for _, body := range []string{clineInsufficientCreditsBody, `{"error":{"message":"Payment required"}}`} {
|
||||
repo := &clineModelLimitFailRepo{}
|
||||
|
||||
shouldDisable := NewRateLimitService(repo, nil, &config.Config{}, nil, nil).HandleUpstreamError(ctx, clineTestAccount(19),
|
||||
http.StatusPaymentRequired, http.Header{}, []byte(body))
|
||||
|
||||
require.False(t, shouldDisable, body)
|
||||
require.Equal(t, 0, repo.setErrorCalls, body)
|
||||
require.Equal(t, 0, repo.tempCalls, body)
|
||||
}
|
||||
}
|
||||
|
||||
// clineAccountRepo 为余额 / 用量探测与周期检测提供 Cline 账号,并记录写入。
|
||||
type clineAccountRepo struct {
|
||||
AccountRepository
|
||||
accounts []Account
|
||||
mu sync.Mutex
|
||||
extraWrites map[int64][]map[string]any
|
||||
modelLimits map[int64]map[string]time.Time
|
||||
reasons map[int64]map[string]string
|
||||
paused []int64
|
||||
}
|
||||
|
||||
func (r *clineAccountRepo) ListByPlatform(_ context.Context, platform string) ([]Account, error) {
|
||||
if platform == PlatformCline {
|
||||
return r.accounts, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (r *clineAccountRepo) GetByID(_ context.Context, id int64) (*Account, error) {
|
||||
for i := range r.accounts {
|
||||
if r.accounts[i].ID == id {
|
||||
return &r.accounts[i], nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
|
||||
func (r *clineAccountRepo) UpdateExtra(_ context.Context, id int64, updates map[string]any) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.extraWrites == nil {
|
||||
r.extraWrites = map[int64][]map[string]any{}
|
||||
}
|
||||
r.extraWrites[id] = append(r.extraWrites[id], updates)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *clineAccountRepo) SetModelRateLimit(_ context.Context, id int64, scope string, resetAt time.Time, reason ...string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.modelLimits == nil {
|
||||
r.modelLimits = map[int64]map[string]time.Time{}
|
||||
r.reasons = map[int64]map[string]string{}
|
||||
}
|
||||
if r.modelLimits[id] == nil {
|
||||
r.modelLimits[id] = map[string]time.Time{}
|
||||
r.reasons[id] = map[string]string{}
|
||||
}
|
||||
r.modelLimits[id][scope] = resetAt
|
||||
if len(reason) > 0 {
|
||||
r.reasons[id][scope] = reason[0]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *clineAccountRepo) SetTempUnschedulable(_ context.Context, id int64, _ time.Time, _ string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.paused = append(r.paused, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
const (
|
||||
clineUsageLimitsPath = "/api/v1/users/me/plan/usage-limits"
|
||||
clineUsageLimitsBody = `{"data":{"limits":[{"type":"five_hour","percentUsed":12.5,"resetsAt":"2099-01-01T05:00:00.123456Z"},{"type":"weekly","percentUsed":40},{"type":"monthly","percentUsed":0}]},"success":true}`
|
||||
)
|
||||
|
||||
func newClineAccountUpstream(usageLimits commandCodeAlphaResponse, balance string) *commandCodeAlphaUpstream {
|
||||
return &commandCodeAlphaUpstream{responses: map[string]commandCodeAlphaResponse{
|
||||
clineUsageLimitsPath: usageLimits,
|
||||
"/api/v1/users/me": {status: http.StatusOK, body: `{"success":true,"data":{"id":"u-1","email":"a@example.com"}}`},
|
||||
"/api/v1/users/u-1/balance": {status: http.StatusOK, body: balance},
|
||||
}}
|
||||
}
|
||||
|
||||
// balance 是百万分之一积分(1 积分 = 1 美元),按 Cline 的展示精度保留 4 位小数。
|
||||
func TestClineBalanceProbeConvertsMicrocredits(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
balance string
|
||||
want float64
|
||||
}{
|
||||
{`{"balance":12340000,"userId":"u-1"}`, 12.34},
|
||||
{`{"success":true,"data":{"balance":"500000","userId":"u-1"}}`, 0.5},
|
||||
{`{"balance":1234567,"userId":"u-1"}`, 1.2346},
|
||||
} {
|
||||
account := clineTestAccount(40)
|
||||
upstream := newClineAccountUpstream(commandCodeAlphaResponse{}, tc.balance)
|
||||
repo := &cnBalanceProbeRepo{account: account}
|
||||
svc := NewCNProviderBalanceService(repo, nil, upstream, &config.Config{})
|
||||
|
||||
result, err := svc.QueryBalance(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.Success)
|
||||
require.True(t, result.Persisted)
|
||||
require.InDelta(t, tc.want, result.Balance, 1e-9)
|
||||
require.Equal(t, "USD", result.Currency)
|
||||
require.Len(t, upstream.requests, 2)
|
||||
require.Equal(t, "Bearer cline_test_key", upstream.requests[0].Header.Get("Authorization"))
|
||||
require.InDelta(t, tc.want, repo.extraWrites[0]["cline_balance"], 1e-9)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClineBalanceProbeFailures(t *testing.T) {
|
||||
account := clineTestAccount(41)
|
||||
upstream := &commandCodeAlphaUpstream{responses: map[string]commandCodeAlphaResponse{
|
||||
"/api/v1/users/me": {status: http.StatusUnauthorized, body: `{"error":"Unauthorized"}`},
|
||||
}}
|
||||
repo := &cnBalanceProbeRepo{account: account}
|
||||
result, err := NewCNProviderBalanceService(repo, nil, upstream, &config.Config{}).QueryBalance(context.Background(), account.ID)
|
||||
require.NoError(t, err)
|
||||
require.False(t, result.Success)
|
||||
require.Equal(t, http.StatusUnauthorized, result.StatusCode)
|
||||
require.Contains(t, result.Error, "HTTP 401")
|
||||
require.Empty(t, repo.extraWrites)
|
||||
|
||||
envelope := &commandCodeAlphaUpstream{responses: map[string]commandCodeAlphaResponse{
|
||||
"/api/v1/users/me": {status: http.StatusOK, body: `{"success":false,"error":"token expired"}`},
|
||||
}}
|
||||
result, err = NewCNProviderBalanceService(&cnBalanceProbeRepo{account: account}, nil, envelope, &config.Config{}).QueryBalance(context.Background(), account.ID)
|
||||
require.NoError(t, err)
|
||||
require.False(t, result.Success)
|
||||
require.Contains(t, result.Error, "token expired")
|
||||
}
|
||||
|
||||
// 余额与用量只查官方主机上的 API Key 账号:自定义中转的 Key 不发往官方账号接口。
|
||||
func TestClineAccountAPIRequiresOfficialHost(t *testing.T) {
|
||||
require.NoError(t, validatePayGAccount(clineTestAccount(50)))
|
||||
require.NoError(t, validateCodingPlanAccount(clineTestAccount(50)))
|
||||
require.Equal(t, PlatformCline, clineTestAccount(50).GetCodingPlanProvider())
|
||||
|
||||
relay := clineTestAccount(52)
|
||||
relay.Credentials["base_url"] = "https://relay.example.com/v1"
|
||||
relay.Credentials["api_protocol"] = APIProtocolChatCompletions
|
||||
require.Error(t, validatePayGAccount(relay))
|
||||
require.Error(t, validateCodingPlanAccount(relay))
|
||||
require.Empty(t, relay.GetCodingPlanProvider())
|
||||
}
|
||||
|
||||
func clineUsageTestConfig() *config.Config {
|
||||
cfg := &config.Config{}
|
||||
cfg.Gateway.CNProviders.BalanceThreshold = 0.5
|
||||
return cfg
|
||||
}
|
||||
|
||||
// 一次探测刷新三档窗口与积分余额;两个钱包都可用时不写冷却。
|
||||
func TestClineUsageProbeWritesWindowsAndBalance(t *testing.T) {
|
||||
account := clineTestAccount(60)
|
||||
repo := &clineAccountRepo{accounts: []Account{*account}}
|
||||
upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: clineUsageLimitsBody}, `{"success":true,"data":{"balance":12340000}}`)
|
||||
|
||||
result, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.Success)
|
||||
require.True(t, result.CredentialValid)
|
||||
require.True(t, result.Persisted)
|
||||
require.Equal(t, "ClinePass", result.PlanLevel)
|
||||
require.Equal(t, []CNQuotaTier{
|
||||
{Window: "5h", UsedPercent: 12.5, ResetAt: "2099-01-01T05:00:00Z"},
|
||||
{Window: "weekly", UsedPercent: 40},
|
||||
{Window: "monthly", UsedPercent: 0},
|
||||
}, result.Tiers)
|
||||
require.NotNil(t, result.Balance)
|
||||
require.InDelta(t, 12.34, result.Balance.Balance, 1e-9)
|
||||
require.Equal(t, "Bearer cline_test_key", upstream.requests[0].Header.Get("Authorization"))
|
||||
|
||||
written := repo.extraWrites[60][0]
|
||||
require.Equal(t, 12.5, written["cline_5h_used_percent"])
|
||||
require.Equal(t, "2099-01-01T05:00:00Z", written["cline_5h_reset_at"])
|
||||
require.Equal(t, 40.0, written["cline_weekly_used_percent"])
|
||||
require.Contains(t, written, "cline_weekly_reset_at")
|
||||
require.Nil(t, written["cline_weekly_reset_at"], "a window that has not started has no reset time")
|
||||
require.InDelta(t, 12.34, written["cline_balance"], 1e-9)
|
||||
require.Empty(t, repo.modelLimits)
|
||||
}
|
||||
|
||||
// 窗口用满冷却 ClinePass 到重置时间;积分低于阈值冷却积分钱包;都不停整个账号。
|
||||
func TestClineUsageProbeCoolsDownExhaustedWallets(t *testing.T) {
|
||||
resetAt := time.Now().Add(72 * time.Hour).UTC().Truncate(time.Second)
|
||||
body := `{"data":{"limits":[{"type":"five_hour","percentUsed":30},{"type":"weekly","percentUsed":100,"resetsAt":"` +
|
||||
resetAt.Format(time.RFC3339) + `"}]},"success":true}`
|
||||
account := clineTestAccount(61)
|
||||
repo := &clineAccountRepo{accounts: []Account{*account}}
|
||||
upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: body}, `{"success":true,"data":{"balance":200000}}`)
|
||||
|
||||
_, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.True(t, repo.modelLimits[61][clinePassRateLimitKey].Equal(resetAt))
|
||||
require.Equal(t, clinePassLimitReason+": weekly window used up", repo.reasons[61][clinePassRateLimitKey])
|
||||
require.WithinDuration(t, time.Now().Add(cnBalanceCheckCooldown(nil)), repo.modelLimits[61][clineCreditsRateLimitKey], time.Minute)
|
||||
require.True(t, strings.HasPrefix(repo.reasons[61][clineCreditsRateLimitKey], clineCreditsLowReason), repo.reasons[61][clineCreditsRateLimitKey])
|
||||
require.Empty(t, repo.paused)
|
||||
}
|
||||
|
||||
// 没有订阅(404 或空列表):清掉旧窗口快照,ClinePass 模型不调度到该账号。
|
||||
func TestClineUsageProbeWithoutSubscription(t *testing.T) {
|
||||
for _, usage := range []commandCodeAlphaResponse{
|
||||
{status: http.StatusNotFound, body: `{"success":false,"error":"no plan history found for user"}`},
|
||||
{status: http.StatusOK, body: `{"success":true,"data":{"limits":[]}}`},
|
||||
} {
|
||||
account := withClinePassSnapshot(clineTestAccount(62), nil)
|
||||
repo := &clineAccountRepo{accounts: []Account{*account}}
|
||||
upstream := newClineAccountUpstream(usage, `{"success":true,"data":{"balance":5000000}}`)
|
||||
|
||||
result, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.Success)
|
||||
require.Empty(t, result.Tiers)
|
||||
require.Empty(t, result.PlanLevel)
|
||||
written := repo.extraWrites[62][0]
|
||||
for _, key := range []string{"cline_5h_used_percent", "cline_weekly_used_percent", "cline_monthly_used_percent"} {
|
||||
require.Contains(t, written, key)
|
||||
require.Nil(t, written[key])
|
||||
}
|
||||
require.True(t, strings.HasPrefix(repo.reasons[62][clinePassRateLimitKey], clinePassUnavailableReason))
|
||||
require.NotContains(t, repo.modelLimits[62], clineCreditsRateLimitKey)
|
||||
}
|
||||
}
|
||||
|
||||
// 数据显示钱包恢复可用时解除冷却;组织花费上限无从探测,不提前解除。
|
||||
func TestClineUsageProbeClearsRecoveredWallets(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
creditsReason string
|
||||
cleared bool
|
||||
}{
|
||||
{clineCreditsReason + ": Insufficient credits", true},
|
||||
{clineCreditsLowReason + ": balance 0.1 USD below threshold 0.50", true},
|
||||
{clineSpendLimitReason + ": Organization spend limit exceeded", false},
|
||||
} {
|
||||
account := clineTestAccount(63)
|
||||
now := time.Now()
|
||||
setAccountModelRateLimitSnapshot(account, clinePassRateLimitKey, now.Add(6*time.Hour), clinePassLimitReason, now)
|
||||
setAccountModelRateLimitSnapshot(account, clineCreditsRateLimitKey, now.Add(time.Hour), tc.creditsReason, now)
|
||||
repo := &clineAccountRepo{accounts: []Account{*account}}
|
||||
upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: clineUsageLimitsBody}, `{"success":true,"data":{"balance":5000000}}`)
|
||||
|
||||
_, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.False(t, repo.modelLimits[63][clinePassRateLimitKey].After(time.Now()), tc.creditsReason)
|
||||
_, touched := repo.modelLimits[63][clineCreditsRateLimitKey]
|
||||
require.Equal(t, tc.cleared, touched, tc.creditsReason)
|
||||
if tc.cleared {
|
||||
require.False(t, repo.modelLimits[63][clineCreditsRateLimitKey].After(time.Now()), tc.creditsReason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ClinePass 同样只解除探测能证明已恢复的冷却(窗口用满、未订阅):组织账户、所需订阅
|
||||
// 档位与推理额度上限反映不到用量接口里,提前解除会让每个检测周期都重放一次失败请求。
|
||||
func TestClineUsageProbeClearsOnlyProvablePassCooldowns(t *testing.T) {
|
||||
ctx := withTempUnschedulableModel(context.Background(), []string{"cline-pass/glm-5.3"})
|
||||
balance := `{"success":true,"data":{"balance":5000000}}`
|
||||
for _, tc := range []struct {
|
||||
status int
|
||||
body string
|
||||
cleared bool
|
||||
}{
|
||||
{http.StatusTooManyRequests, clinePassWeeklyBody, true},
|
||||
{http.StatusForbidden, clineNotSubscribedBody, false},
|
||||
{http.StatusForbidden, clineOrgPassBody, false},
|
||||
{http.StatusTooManyRequests, clineInferenceCapBody, false},
|
||||
} {
|
||||
account := clineTestAccount(65)
|
||||
NewRateLimitService(&commandCodeRateLimitRepo{}, nil, &config.Config{}, nil, nil).HandleUpstreamError(ctx, account,
|
||||
tc.status, http.Header{}, []byte(tc.body))
|
||||
require.True(t, account.isRateLimitActiveForKey(clinePassRateLimitKey), tc.body)
|
||||
repo := &clineAccountRepo{accounts: []Account{*account}}
|
||||
upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: clineUsageLimitsBody}, balance)
|
||||
|
||||
_, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
_, touched := repo.modelLimits[65][clinePassRateLimitKey]
|
||||
require.Equal(t, tc.cleared, touched, tc.body)
|
||||
}
|
||||
|
||||
// 探测发现未订阅设的冷却,订阅后的下一次探测解除。
|
||||
repo := &clineAccountRepo{accounts: []Account{*clineTestAccount(66)}}
|
||||
unsubscribed := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusNotFound,
|
||||
body: `{"success":false,"error":"no plan history found for user"}`}, balance)
|
||||
_, err := NewCNProviderQuotaService(repo, nil, unsubscribed, clineUsageTestConfig()).QueryUsage(context.Background(), 66)
|
||||
require.NoError(t, err)
|
||||
require.True(t, repo.modelLimits[66][clinePassRateLimitKey].After(time.Now()))
|
||||
|
||||
subscribed := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: clineUsageLimitsBody}, balance)
|
||||
_, err = NewCNProviderQuotaService(repo, nil, subscribed, clineUsageTestConfig()).QueryUsage(context.Background(), 66)
|
||||
require.NoError(t, err)
|
||||
require.False(t, repo.modelLimits[66][clinePassRateLimitKey].After(time.Now()))
|
||||
}
|
||||
|
||||
// 用量接口鉴权失败:探测失败但不写快照、不动冷却。
|
||||
func TestClineUsageProbeAuthFailure(t *testing.T) {
|
||||
account := clineTestAccount(64)
|
||||
repo := &clineAccountRepo{accounts: []Account{*account}}
|
||||
upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusUnauthorized, body: `{"error":"Unauthorized"}`}, `{}`)
|
||||
|
||||
result, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.False(t, result.Success)
|
||||
require.False(t, result.CredentialValid)
|
||||
require.Equal(t, http.StatusUnauthorized, result.StatusCode)
|
||||
require.Empty(t, repo.extraWrites)
|
||||
require.Empty(t, repo.modelLimits)
|
||||
}
|
||||
|
||||
// 周期检测探测官方主机上的全部激活账号(含手动停调的,钱包冷却与调度开关无关),
|
||||
// 只冷却钱包,不停整个账号。
|
||||
func TestCNProviderBalanceCheckRunOnceProbesClineUsage(t *testing.T) {
|
||||
official := *clineTestAccount(1)
|
||||
manualOff := *clineTestAccount(2)
|
||||
manualOff.Schedulable = false
|
||||
relay := *clineTestAccount(3)
|
||||
relay.Credentials["base_url"] = "https://relay.example.com/v1"
|
||||
relay.Credentials["api_protocol"] = APIProtocolChatCompletions
|
||||
|
||||
repo := &clineAccountRepo{accounts: []Account{official, manualOff, relay}}
|
||||
upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: clineUsageLimitsBody}, `{"success":true,"data":{"balance":200000}}`)
|
||||
cfg := clineUsageTestConfig()
|
||||
svc := &CNProviderBalanceCheckService{
|
||||
accountRepo: repo,
|
||||
balanceService: NewCNProviderBalanceService(repo, nil, upstream, cfg),
|
||||
quotaService: NewCNProviderQuotaService(repo, nil, upstream, cfg),
|
||||
cfg: cfg,
|
||||
}
|
||||
|
||||
svc.runOnce()
|
||||
|
||||
require.Len(t, upstream.requests, 6, "usage-limits + me + balance for each official account")
|
||||
require.Len(t, repo.extraWrites, 2)
|
||||
require.Contains(t, repo.modelLimits[1], clineCreditsRateLimitKey)
|
||||
require.Contains(t, repo.modelLimits[2], clineCreditsRateLimitKey)
|
||||
require.Empty(t, repo.paused)
|
||||
}
|
||||
|
||||
// 同一轮检测里每个账号走自己平台登记的检测函数:积分同样低于阈值,Command Code 停整个
|
||||
// 账号,Cline 不停(钱包冷却在探测中处理)。
|
||||
func TestCNProviderBalanceCheckRunOnceDispatchesAccountProbesByPlatform(t *testing.T) {
|
||||
commandCode := *commandCodeUsageAccount()
|
||||
commandCode.ID, commandCode.Schedulable = 1, true
|
||||
cline := *clineTestAccount(2)
|
||||
repo := &commandCodeCheckRepo{accounts: []Account{commandCode, cline}}
|
||||
prober := &commandCodeBalanceProber{balance: 0.2}
|
||||
svc := &CNProviderBalanceCheckService{accountRepo: repo, quotaService: prober, cfg: clineUsageTestConfig()}
|
||||
|
||||
svc.runOnce()
|
||||
|
||||
require.ElementsMatch(t, []int64{1, 2}, prober.probed)
|
||||
require.Equal(t, []int64{1}, repo.paused)
|
||||
}
|
||||
|
||||
// 官方主机不做上游计费探测:中转站的计费接口在官方 API 上不存在,只会把 Key 发往官方主机。
|
||||
func TestClineOfficialHostSkipsUpstreamBillingProbe(t *testing.T) {
|
||||
require.True(t, upstreamBillingProbeTargetIsOfficialAPI(DefaultClineBaseURL))
|
||||
require.False(t, upstreamBillingProbeTargetIsOfficialAPI("https://relay.example.com/v1"))
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// Cline 积分余额与 ClinePass 用量来自账号接口(Cline 控制台与客户端同源),账号 API Key
|
||||
// 可直接访问(Bearer <key>;实测带 workos: 前缀反而 401):
|
||||
//
|
||||
// GET /api/v1/users/me -> {id, email, ...}
|
||||
// GET /api/v1/users/{id}/balance -> {balance, userId}
|
||||
// GET /api/v1/users/me/plan/usage-limits -> {limits:[{type, percentUsed, resetsAt?}]}
|
||||
//
|
||||
// 响应包在 {success, error, data} 信封里。balance 单位为百万分之一积分(1 积分 =
|
||||
// 1 美元;Cline CLI 的 normalizeCreditBalance 除以 1e6,扩展先除 100 再除 10000),
|
||||
// 按 Cline 的展示精度保留 4 位小数。usage-limits 的 type 为 five_hour / weekly /
|
||||
// monthly(套餐里对应最近 5 小时 / 7 天 / 30 天的滚动用量上限),percentUsed 为 0-100,
|
||||
// 窗口未开始时没有 resetsAt;未订阅时返回 404(no plan history found for user)或空列表。
|
||||
|
||||
const clineAPIBase = "https://" + clineAPIHost
|
||||
|
||||
var errClineInvalidResponse = errors.New("invalid cline account response")
|
||||
|
||||
// clineHTTPError 是账号接口的非 2xx 响应。
|
||||
type clineHTTPError struct {
|
||||
status int
|
||||
body string
|
||||
}
|
||||
|
||||
func (e *clineHTTPError) Error() string {
|
||||
return fmt.Sprintf("HTTP %d: %s", e.status, e.body)
|
||||
}
|
||||
|
||||
type clineAccountClient struct {
|
||||
cfg *config.Config
|
||||
httpUpstream HTTPUpstream
|
||||
account *Account
|
||||
apiKey string
|
||||
proxyURL string
|
||||
// errPrefix 是应用错误码前缀(CN_BALANCE / CN_QUOTA),与调用方服务的错误码一致。
|
||||
errPrefix string
|
||||
}
|
||||
|
||||
func newClineAccountClient(cfg *config.Config, httpUpstream HTTPUpstream, account *Account, proxyURL, errPrefix string) *clineAccountClient {
|
||||
return &clineAccountClient{
|
||||
cfg: cfg,
|
||||
httpUpstream: httpUpstream,
|
||||
account: account,
|
||||
apiKey: strings.TrimSpace(account.GetCNAPIKey()),
|
||||
proxyURL: proxyURL,
|
||||
errPrefix: errPrefix,
|
||||
}
|
||||
}
|
||||
|
||||
// get 请求一个账号接口,返回拆掉 {success, error, data} 信封后的 JSON。
|
||||
func (c *clineAccountClient) get(ctx context.Context, path string) (gjson.Result, error) {
|
||||
validatedURL, err := cnValidateProbeURL(c.cfg, clineAPIBase+path)
|
||||
if err != nil {
|
||||
return gjson.Result{}, infraerrors.New(http.StatusForbidden, c.errPrefix+"_URL_REJECTED", err.Error())
|
||||
}
|
||||
callCtx, cancel := context.WithTimeout(ctx, cnQuotaUpstreamTimeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(callCtx, http.MethodGet, validatedURL, nil)
|
||||
if err != nil {
|
||||
return gjson.Result{}, infraerrors.Newf(http.StatusInternalServerError, c.errPrefix+"_REQUEST_BUILD_FAILED", "build request: %v", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.apiKey)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
c.account.ApplyHeaderOverrides(req.Header)
|
||||
|
||||
resp, err := c.httpUpstream.Do(req, c.proxyURL, c.account.ID, maxInt(c.account.Concurrency, 1))
|
||||
if err != nil {
|
||||
return gjson.Result{}, fmt.Errorf("upstream request failed: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, cnQuotaMaxBodyBytes))
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return gjson.Result{}, &clineHTTPError{status: resp.StatusCode, body: truncate(strings.TrimSpace(string(body)), 240)}
|
||||
}
|
||||
if !gjson.ValidBytes(body) {
|
||||
return gjson.Result{}, fmt.Errorf("%w: %s", errClineInvalidResponse, path)
|
||||
}
|
||||
parsed := gjson.ParseBytes(body)
|
||||
if success := parsed.Get("success"); success.Exists() {
|
||||
if !success.Bool() {
|
||||
return gjson.Result{}, &clineHTTPError{status: resp.StatusCode, body: truncate(parsed.Get("error").String(), 240)}
|
||||
}
|
||||
return parsed.Get("data"), nil
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
// balance 查询积分余额(美元)。
|
||||
func (c *clineAccountClient) balance(ctx context.Context) (float64, error) {
|
||||
me, err := c.get(ctx, "/api/v1/users/me")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
userID := strings.TrimSpace(me.Get("id").String())
|
||||
if userID == "" {
|
||||
return 0, fmt.Errorf("%w: missing user id", errClineInvalidResponse)
|
||||
}
|
||||
balance, err := c.get(ctx, "/api/v1/users/"+url.PathEscape(userID)+"/balance")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
micro := balance.Get("balance")
|
||||
if !micro.Exists() || (micro.Type != gjson.Number && micro.Type != gjson.String) {
|
||||
return 0, fmt.Errorf("%w: missing balance", errClineInvalidResponse)
|
||||
}
|
||||
return math.Round(micro.Float()/100) / 10000, nil
|
||||
}
|
||||
|
||||
// passLimits 查询 ClinePass 三档窗口;subscribed=false 表示没有订阅。
|
||||
func (c *clineAccountClient) passLimits(ctx context.Context) (tiers []CNQuotaTier, subscribed bool, err error) {
|
||||
data, err := c.get(ctx, "/api/v1/users/me/plan/usage-limits")
|
||||
if err != nil {
|
||||
var httpErr *clineHTTPError
|
||||
if errors.As(err, &httpErr) && httpErr.status == http.StatusNotFound {
|
||||
return nil, false, nil
|
||||
}
|
||||
return nil, false, err
|
||||
}
|
||||
limits := data.Get("limits")
|
||||
if !limits.IsArray() {
|
||||
return nil, false, fmt.Errorf("%w: missing limits", errClineInvalidResponse)
|
||||
}
|
||||
windows := map[string]string{"five_hour": "5h", "weekly": "weekly", "monthly": "monthly"}
|
||||
for _, item := range limits.Array() {
|
||||
window, ok := windows[strings.ToLower(strings.TrimSpace(item.Get("type").String()))]
|
||||
used := item.Get("percentUsed")
|
||||
if !ok || used.Type != gjson.Number {
|
||||
continue
|
||||
}
|
||||
tier := CNQuotaTier{Window: window, UsedPercent: used.Float()}
|
||||
if resetAt, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(item.Get("resetsAt").String())); err == nil {
|
||||
tier.ResetAt = resetAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
tiers = append(tiers, tier)
|
||||
}
|
||||
return tiers, len(tiers) > 0, nil
|
||||
}
|
||||
|
||||
// clineFetchFailure 把取数错误转换为探测失败的状态码与文案;ok=false 表示应作为错误返回。
|
||||
func clineFetchFailure(err error) (status int, message string, ok bool) {
|
||||
var httpErr *clineHTTPError
|
||||
switch {
|
||||
case errors.As(err, &httpErr):
|
||||
return httpErr.status, fmt.Sprintf("API error (HTTP %d): %s", httpErr.status, httpErr.body), true
|
||||
case errors.Is(err, errClineInvalidResponse):
|
||||
return http.StatusOK, "Invalid response", true
|
||||
default:
|
||||
return 0, "", false
|
||||
}
|
||||
}
|
||||
|
||||
func clineApplicationError(err error, errPrefix string) error {
|
||||
if isApplicationError(err) {
|
||||
return err
|
||||
}
|
||||
return infraerrors.Newf(http.StatusBadGateway, errPrefix+"_REQUEST_FAILED", "%v", err)
|
||||
}
|
||||
|
||||
func clineBalanceResult(usd float64, now time.Time) *CNProviderBalanceResult {
|
||||
return &CNProviderBalanceResult{
|
||||
Provider: PlatformCline,
|
||||
Success: true,
|
||||
Balance: usd,
|
||||
Currency: "USD",
|
||||
Balances: []CNProviderBalanceEntry{{Currency: "USD", Balance: usd}},
|
||||
Available: true,
|
||||
StatusCode: http.StatusOK,
|
||||
FetchedAt: now.Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
// queryClineBalance 只查积分余额(美元)并落余额快照。
|
||||
func (s *CNProviderBalanceService) queryClineBalance(ctx context.Context, account *Account) (*CNProviderBalanceResult, error) {
|
||||
client := newClineAccountClient(s.cfg, s.httpUpstream, account, s.resolveProxyURL(ctx, account), "CN_BALANCE")
|
||||
if client.apiKey == "" {
|
||||
return nil, infraerrors.New(http.StatusBadRequest, "CN_BALANCE_NO_APIKEY", "account api_key is empty")
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
usd, err := client.balance(ctx)
|
||||
if err != nil {
|
||||
status, message, ok := clineFetchFailure(err)
|
||||
if !ok {
|
||||
return nil, clineApplicationError(err, "CN_BALANCE")
|
||||
}
|
||||
return &CNProviderBalanceResult{Provider: PlatformCline, StatusCode: status, FetchedAt: now.Unix(), Available: true,
|
||||
Error: "Balance query failed: " + message}, nil
|
||||
}
|
||||
result := clineBalanceResult(usd, now)
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, cnBalanceExtraUpdates(PlatformCline, result, now)); err != nil {
|
||||
slog.Warn("cn_balance_persist_failed", "account_id", account.ID, "provider", PlatformCline, "error", err)
|
||||
} else {
|
||||
result.Persisted = true
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// queryClineUsage 查询 ClinePass 窗口与积分余额,落快照,并按结果设置或解除两个钱包的
|
||||
// 冷却(见 applyClineWallets)。余额查询失败不影响窗口结果。
|
||||
func (s *CNProviderQuotaService) queryClineUsage(ctx context.Context, account *Account) (*CNProviderQuotaProbeResult, error) {
|
||||
client := newClineAccountClient(s.cfg, s.httpUpstream, account, s.resolveProxyURL(ctx, account), "CN_QUOTA")
|
||||
if client.apiKey == "" {
|
||||
return nil, infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NO_APIKEY", "account api_key is empty")
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
result := &CNProviderQuotaProbeResult{
|
||||
Provider: PlatformCline,
|
||||
Source: "cline_usage_limits",
|
||||
FetchedAt: now.Unix(),
|
||||
}
|
||||
tiers, subscribed, err := client.passLimits(ctx)
|
||||
if err != nil {
|
||||
status, message, ok := clineFetchFailure(err)
|
||||
if !ok {
|
||||
return nil, clineApplicationError(err, "CN_QUOTA")
|
||||
}
|
||||
result.StatusCode = status
|
||||
result.Error = message
|
||||
result.CredentialValid = status != http.StatusUnauthorized && status != http.StatusForbidden
|
||||
return result, nil
|
||||
}
|
||||
result.StatusCode = http.StatusOK
|
||||
result.Success = true
|
||||
result.CredentialValid = true
|
||||
result.Tiers = tiers
|
||||
if subscribed {
|
||||
result.PlanLevel = "ClinePass"
|
||||
}
|
||||
|
||||
updates := cnQuotaExtraUpdates(PlatformCline, tiers, now)
|
||||
present := make(map[string]CNQuotaTier, len(tiers))
|
||||
for _, tier := range tiers {
|
||||
present[tier.Window] = tier
|
||||
}
|
||||
// 缺席的窗口写 nil:取消订阅后不沿用旧快照(clinePassSubscribed 据此判断);窗口尚未
|
||||
// 开始时没有重置时间,同样清掉上一次的值。
|
||||
for _, window := range []struct{ name, used, reset string }{
|
||||
{"5h", cnExtraSuffix5hUsed, cnExtraSuffix5hReset},
|
||||
{"weekly", cnExtraSuffixWeeklyUsed, cnExtraSuffixWeeklyReset},
|
||||
{"monthly", cnExtraSuffixMonthlyUsed, cnExtraSuffixMonthlyReset},
|
||||
} {
|
||||
tier, ok := present[window.name]
|
||||
if !ok {
|
||||
updates[cnExtraKey(PlatformCline, window.used)] = nil
|
||||
}
|
||||
if tier.ResetAt == "" {
|
||||
updates[cnExtraKey(PlatformCline, window.reset)] = nil
|
||||
}
|
||||
}
|
||||
if usd, err := client.balance(ctx); err != nil {
|
||||
slog.Warn("cline_balance_probe_failed", "account_id", account.ID, "error", err)
|
||||
} else {
|
||||
result.Balance = clineBalanceResult(usd, now)
|
||||
for key, value := range cnBalanceExtraUpdates(PlatformCline, result.Balance, now) {
|
||||
updates[key] = value
|
||||
}
|
||||
}
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil {
|
||||
slog.Warn("cn_quota_persist_failed", "account_id", account.ID, "provider", PlatformCline, "error", err)
|
||||
} else {
|
||||
result.Persisted = true
|
||||
if result.Balance != nil {
|
||||
result.Balance.Persisted = true
|
||||
}
|
||||
}
|
||||
s.applyClineWallets(ctx, account, subscribed, tiers, result.Balance, now)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
const (
|
||||
clineCreditsLowReason = "cline_credits_low"
|
||||
// clinePassNoSubscriptionReason 是探测发现未订阅时的原因;与请求侧的未订阅 / 组织账户
|
||||
// 共用 clinePassUnavailableReason 前缀,单独区分出探测能证明已恢复的这一种。
|
||||
clinePassNoSubscriptionReason = clinePassUnavailableReason + ": no ClinePass subscription"
|
||||
)
|
||||
|
||||
// applyClineWallets 按探测结果设置或解除两个钱包的冷却:
|
||||
// - ClinePass:未订阅,或有窗口用满(≥100%)时冷却到该窗口的重置时间;可用时只解除
|
||||
// 窗口用满与未订阅的冷却(组织账户、所需订阅档位与推理额度上限反映不到用量接口里,
|
||||
// 仍等到期后由请求重新确认);
|
||||
// - 积分:余额低于阈值时冷却,恢复后只解除积分类原因的冷却(组织花费上限无从探测,
|
||||
// 仍等到期后由请求重新确认)。
|
||||
//
|
||||
// 没有重置时间时冷却 2 个检测周期,由下一次探测续期或解除。
|
||||
func (s *CNProviderQuotaService) applyClineWallets(ctx context.Context, account *Account, subscribed bool, tiers []CNQuotaTier, balance *CNProviderBalanceResult, now time.Time) {
|
||||
fallback := now.Add(cnBalanceCheckCooldown(s.cfg))
|
||||
|
||||
switch until, reason := clinePassWalletState(subscribed, tiers, now, fallback); {
|
||||
case until != nil:
|
||||
s.setClineWalletLimit(ctx, account, clinePassRateLimitKey, *until, reason, now)
|
||||
case account.isRateLimitActiveForKey(clinePassRateLimitKey):
|
||||
reason := account.modelRateLimitReason(clinePassRateLimitKey)
|
||||
if strings.HasPrefix(reason, clinePassLimitReason) || strings.HasPrefix(reason, clinePassNoSubscriptionReason) {
|
||||
s.setClineWalletLimit(ctx, account, clinePassRateLimitKey, now, "", now)
|
||||
}
|
||||
}
|
||||
|
||||
if balance == nil {
|
||||
return
|
||||
}
|
||||
threshold := 0.0
|
||||
if s.cfg != nil {
|
||||
threshold = s.cfg.Gateway.CNProviders.BalanceThreshold
|
||||
}
|
||||
switch low := balance.Balance <= 0 || balance.Balance < threshold; {
|
||||
case low:
|
||||
s.setClineWalletLimit(ctx, account, clineCreditsRateLimitKey, fallback,
|
||||
fmt.Sprintf("%s: balance %.4g USD below threshold %.2f", clineCreditsLowReason, balance.Balance, threshold), now)
|
||||
case account.isRateLimitActiveForKey(clineCreditsRateLimitKey):
|
||||
reason := account.modelRateLimitReason(clineCreditsRateLimitKey)
|
||||
if strings.HasPrefix(reason, clineCreditsReason) || strings.HasPrefix(reason, clineCreditsLowReason) {
|
||||
s.setClineWalletLimit(ctx, account, clineCreditsRateLimitKey, now, "", now)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// clinePassWalletState 返回 ClinePass 钱包应冷却到的时间;nil 表示可用。
|
||||
func clinePassWalletState(subscribed bool, tiers []CNQuotaTier, now, fallback time.Time) (*time.Time, string) {
|
||||
if !subscribed {
|
||||
return &fallback, clinePassNoSubscriptionReason
|
||||
}
|
||||
var until *time.Time
|
||||
var exhausted []string
|
||||
for _, tier := range tiers {
|
||||
if tier.UsedPercent < 100 {
|
||||
continue
|
||||
}
|
||||
exhausted = append(exhausted, tier.Window)
|
||||
resetAt := fallback
|
||||
if parsed := parseSchedulingResetAt(tier.ResetAt); parsed != nil && parsed.After(now) && parsed.Sub(now) <= clinePassMaxCooldown {
|
||||
resetAt = *parsed
|
||||
}
|
||||
if until == nil || resetAt.After(*until) {
|
||||
until = &resetAt
|
||||
}
|
||||
}
|
||||
if until == nil {
|
||||
return nil, ""
|
||||
}
|
||||
return until, clinePassLimitReason + ": " + strings.Join(exhausted, ", ") + " window used up"
|
||||
}
|
||||
|
||||
// setClineWalletLimit 写钱包冷却;until 不晚于 now 时即解除。
|
||||
func (s *CNProviderQuotaService) setClineWalletLimit(ctx context.Context, account *Account, scope string, until time.Time, reason string, now time.Time) {
|
||||
setAccountModelRateLimitSnapshot(account, scope, until, reason, now)
|
||||
if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, scope, until, reason); err != nil {
|
||||
slog.Warn("cline_wallet_limit_set_failed", "account_id", account.ID, "scope", scope, "error", err)
|
||||
return
|
||||
}
|
||||
slog.Info("cline_wallet_limit", "account_id", account.ID, "scope", scope, "until", until.UTC(), "cleared", !until.After(now))
|
||||
}
|
||||
@@ -27,6 +27,8 @@ const cnQuotaProbeConcurrency = 4
|
||||
// 克隆自 AccountExpiryService 的 Start/Stop/runOnce + ticker 骨架。
|
||||
// 余额探测仅覆盖有公开余额端点的 kimi / deepseek;智谱无余额端点,仅靠响应式 429/402。
|
||||
// 额度探测覆盖 kimi / zhipu 的 coding plan 账号(deepseek 无 coding 套餐)。
|
||||
// Command Code 账号一次探测同时刷新窗口快照与积分余额,积分低于阈值时同样临时停调。
|
||||
// Cline 账号同样一次探测刷新 ClinePass 窗口与积分,只冷却用完的一边(见 cline_usage.go)。
|
||||
type CNProviderBalanceCheckService struct {
|
||||
accountRepo AccountRepository
|
||||
balanceService *CNProviderBalanceService
|
||||
@@ -154,7 +156,8 @@ func (s *CNProviderBalanceCheckService) runOnce() {
|
||||
}
|
||||
|
||||
// 预算按工作量放大:4 并发 × 15s/批 + payg 每账号 5s,下限 30s 上限 300s。
|
||||
batches := (len(quotaTargets) + cnQuotaProbeConcurrency - 1) / cnQuotaProbeConcurrency
|
||||
accountTargets := s.collectAccountProbeTargets()
|
||||
batches := (len(quotaTargets) + len(accountTargets) + cnQuotaProbeConcurrency - 1) / cnQuotaProbeConcurrency
|
||||
timeout := 30*time.Second + time.Duration(batches)*15*time.Second + time.Duration(len(paygTargets))*5*time.Second
|
||||
if timeout > 300*time.Second {
|
||||
timeout = 300 * time.Second
|
||||
@@ -188,11 +191,106 @@ func (s *CNProviderBalanceCheckService) runOnce() {
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
if len(accountTargets) > 0 {
|
||||
sem := make(chan struct{}, cnQuotaProbeConcurrency)
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
for _, target := range accountTargets {
|
||||
wg.Add(1)
|
||||
go func(t accountProbeTarget) {
|
||||
defer wg.Done()
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
switch t.check(ctx, t.account, threshold) {
|
||||
case cnBalancePaused:
|
||||
mu.Lock()
|
||||
paused++
|
||||
mu.Unlock()
|
||||
case cnBalanceCleared:
|
||||
mu.Lock()
|
||||
cleared++
|
||||
mu.Unlock()
|
||||
}
|
||||
}(target)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
if paused > 0 || cleared > 0 {
|
||||
log.Printf("[CNBalance] paused=%d cleared=%d (threshold=%.2f)", paused, cleared, threshold)
|
||||
}
|
||||
}
|
||||
|
||||
// accountProbeCheck 是走账号接口探测的平台的周期检测函数。
|
||||
type accountProbeCheck func(ctx context.Context, account *Account, threshold float64) cnBalanceCheckOutcome
|
||||
|
||||
// accountProbeTarget 是一个待检测账号与其平台的检测函数。
|
||||
type accountProbeTarget struct {
|
||||
account *Account
|
||||
check accountProbeCheck
|
||||
}
|
||||
|
||||
// collectAccountProbeTargets 选出走账号接口探测的平台上、官方主机上激活的账号,并配上
|
||||
// 该平台的检测函数。一次探测同时刷新窗口快照与积分余额:
|
||||
// - Command Code:手动可调度的账号再按积分余额停调 / 恢复(窗口快照供阈值停调读取);
|
||||
// - Cline:探测中按结果设置或解除两个钱包的冷却,不停整个账号。
|
||||
func (s *CNProviderBalanceCheckService) collectAccountProbeTargets() []accountProbeTarget {
|
||||
if s.quotaService == nil {
|
||||
return nil
|
||||
}
|
||||
var targets []accountProbeTarget
|
||||
for _, p := range []struct {
|
||||
platform string
|
||||
supported func(*Account) bool
|
||||
check accountProbeCheck
|
||||
}{
|
||||
{PlatformCommandCode, (*Account).commandCodeUsageSupported, s.checkCommandCode},
|
||||
{PlatformCline, (*Account).clineAccountAPISupported, s.checkCline},
|
||||
} {
|
||||
accounts, err := s.accountRepo.ListByPlatform(context.Background(), p.platform)
|
||||
if err != nil {
|
||||
log.Printf("[CNBalance] list %s accounts failed: %v", p.platform, err)
|
||||
continue
|
||||
}
|
||||
for i := range accounts {
|
||||
if account := &accounts[i]; account.IsActive() && p.supported(account) {
|
||||
targets = append(targets, accountProbeTarget{account: account, check: p.check})
|
||||
}
|
||||
}
|
||||
}
|
||||
return targets
|
||||
}
|
||||
|
||||
// checkCommandCode 探测 Command Code 窗口与积分;手动可调度的账号再按积分余额停调 / 恢复。
|
||||
func (s *CNProviderBalanceCheckService) checkCommandCode(ctx context.Context, account *Account, threshold float64) cnBalanceCheckOutcome {
|
||||
result, err := s.quotaService.QueryUsage(ctx, account.ID)
|
||||
if err != nil {
|
||||
log.Printf("[CNBalance] command code usage account %d failed: %v", account.ID, err)
|
||||
return cnBalanceNoChange
|
||||
}
|
||||
if result == nil || !result.Success || result.Balance == nil {
|
||||
if result != nil && result.Error != "" {
|
||||
log.Printf("[CNBalance] command code usage account %d error: %s", account.ID, result.Error)
|
||||
}
|
||||
return cnBalanceNoChange
|
||||
}
|
||||
if !account.Schedulable {
|
||||
return cnBalanceNoChange
|
||||
}
|
||||
return s.applyBalanceResult(ctx, account, result.Balance, threshold)
|
||||
}
|
||||
|
||||
// checkCline 探测 Cline 窗口与积分;钱包冷却在探测中按结果设置或解除,不停整个账号。
|
||||
func (s *CNProviderBalanceCheckService) checkCline(ctx context.Context, account *Account, _ float64) cnBalanceCheckOutcome {
|
||||
result, err := s.quotaService.QueryUsage(ctx, account.ID)
|
||||
if err != nil {
|
||||
log.Printf("[CNBalance] cline usage account %d failed: %v", account.ID, err)
|
||||
} else if result != nil && !result.Success && result.Error != "" {
|
||||
log.Printf("[CNBalance] cline usage account %d error: %s", account.ID, result.Error)
|
||||
}
|
||||
return cnBalanceNoChange
|
||||
}
|
||||
|
||||
// probeQuota 探测单个 coding plan 账号的滚动窗口用量并落 extra 快照。
|
||||
// 不在此处做停调/恢复决策:调度阈值评估读取快照统一判定(含暂停账号的续停)。
|
||||
func (s *CNProviderBalanceCheckService) probeQuota(ctx context.Context, accountID int64, platform string) {
|
||||
@@ -224,7 +322,11 @@ func (s *CNProviderBalanceCheckService) checkOne(ctx context.Context, account *A
|
||||
if err != nil || result == nil || !result.Success {
|
||||
return cnBalanceNoChange
|
||||
}
|
||||
return s.applyBalanceResult(ctx, account, result, threshold)
|
||||
}
|
||||
|
||||
// applyBalanceResult 按余额探测结果停调或恢复账号。
|
||||
func (s *CNProviderBalanceCheckService) applyBalanceResult(ctx context.Context, account *Account, result *CNProviderBalanceResult, threshold float64) cnBalanceCheckOutcome {
|
||||
// 双币种(deepseek CNY+USD)任一币种余额达标即可继续调度;仅当全部低于
|
||||
// 阈值(或不可用)才停调。
|
||||
low := !result.Available || allCNBalancesBelowThreshold(result, threshold)
|
||||
@@ -274,15 +376,5 @@ func allCNBalancesBelowThreshold(result *CNProviderBalanceResult, threshold floa
|
||||
|
||||
// cooldown 返回临时停调持续时长(= 2× 检测周期),与响应式 402/429 路径一致。
|
||||
func (s *CNProviderBalanceCheckService) cooldown() time.Duration {
|
||||
minutes := 10
|
||||
if s.cfg != nil {
|
||||
if cfgMin := s.cfg.Gateway.CNProviders.BalanceCheckIntervalMinutes; cfgMin > 0 {
|
||||
minutes = cfgMin
|
||||
}
|
||||
}
|
||||
cooldown := time.Duration(minutes) * time.Minute * 2
|
||||
if cooldown < time.Minute {
|
||||
cooldown = 10 * time.Minute
|
||||
}
|
||||
return cooldown
|
||||
return cnBalanceCheckCooldown(s.cfg)
|
||||
}
|
||||
@@ -123,6 +123,12 @@ func (s *CNProviderBalanceService) QueryBalanceForAccount(ctx context.Context, a
|
||||
}
|
||||
|
||||
func (s *CNProviderBalanceService) queryBalanceForAccount(ctx context.Context, account *Account) (*CNProviderBalanceResult, error) {
|
||||
if account.IsCommandCode() {
|
||||
return s.queryCommandCodeBalance(ctx, account)
|
||||
}
|
||||
if account.IsCline() {
|
||||
return s.queryClineBalance(ctx, account)
|
||||
}
|
||||
provider := account.Platform
|
||||
if provider != PlatformKimi && provider != PlatformDeepseek {
|
||||
return nil, infraerrors.New(http.StatusBadRequest, "CN_BALANCE_NO_ENDPOINT", "account provider has no balance endpoint")
|
||||
@@ -219,22 +225,7 @@ func (s *CNProviderBalanceService) queryBalanceForAccount(ctx context.Context, a
|
||||
result.Available = available
|
||||
result.Success = true
|
||||
|
||||
balanceUpdates := make([]any, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
balanceUpdates = append(balanceUpdates, map[string]any{
|
||||
"currency": entry.Currency,
|
||||
"balance": entry.Balance,
|
||||
})
|
||||
}
|
||||
updates := map[string]any{
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixBalance): result.Balance,
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixCurrency): result.Currency,
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixAvailable): available,
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixUpdated): now.Format(time.RFC3339),
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixBalances): balanceUpdates,
|
||||
// 余额探测成功即清除响应式 402/429 写下的 balance_low 标记。
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixLow): false,
|
||||
}
|
||||
updates := cnBalanceExtraUpdates(provider, result, now)
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil {
|
||||
slog.Warn("cn_balance_persist_failed", "account_id", account.ID, "provider", provider, "error", err)
|
||||
} else {
|
||||
@@ -243,6 +234,26 @@ func (s *CNProviderBalanceService) queryBalanceForAccount(ctx context.Context, a
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// cnBalanceExtraUpdates 构造 provider 维度的余额快照更新。
|
||||
func cnBalanceExtraUpdates(provider string, result *CNProviderBalanceResult, now time.Time) map[string]any {
|
||||
balanceUpdates := make([]any, 0, len(result.Balances))
|
||||
for _, entry := range result.Balances {
|
||||
balanceUpdates = append(balanceUpdates, map[string]any{
|
||||
"currency": entry.Currency,
|
||||
"balance": entry.Balance,
|
||||
})
|
||||
}
|
||||
return map[string]any{
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixBalance): result.Balance,
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixCurrency): result.Currency,
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixAvailable): result.Available,
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixUpdated): now.Format(time.RFC3339),
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixBalances): balanceUpdates,
|
||||
// 余额探测成功即清除响应式 402/429 写下的 balance_low 标记。
|
||||
cnExtraKey(provider, cnBalanceExtraSuffixLow): false,
|
||||
}
|
||||
}
|
||||
|
||||
// loadPayGAccount 加载 payg 模式的国产供应商账号(余额仅对 payg 有意义;coding 走额度)。
|
||||
func (s *CNProviderBalanceService) loadPayGAccount(ctx context.Context, accountID int64) (*Account, error) {
|
||||
account, err := s.accountRepo.GetByID(ctx, accountID)
|
||||
@@ -261,6 +272,20 @@ func validatePayGAccount(account *Account) error {
|
||||
if account == nil {
|
||||
return infraerrors.New(http.StatusNotFound, "CN_BALANCE_ACCOUNT_NOT_FOUND", "account not found")
|
||||
}
|
||||
// Cline 积分余额只查官方主机。
|
||||
if account.IsCline() {
|
||||
if !account.clineAccountAPISupported() {
|
||||
return infraerrors.New(http.StatusBadRequest, "CN_BALANCE_NO_ENDPOINT", "cline balance is only available for api key accounts on the official host")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Command Code 积分余额与套餐窗口同源,只查官方主机。
|
||||
if account.IsCommandCode() {
|
||||
if !account.commandCodeUsageSupported() {
|
||||
return infraerrors.New(http.StatusBadRequest, "CN_BALANCE_NO_ENDPOINT", "command code balance is only available for api key accounts on the official host")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !account.IsCNProvider() {
|
||||
return infraerrors.New(http.StatusBadRequest, "CN_BALANCE_INVALID_PLATFORM", "account is not a CN provider account")
|
||||
}
|
||||
|
||||
@@ -62,9 +62,13 @@ type CNProviderQuotaProbeResult struct {
|
||||
FetchedAt int64 `json:"fetched_at"`
|
||||
Persisted bool `json:"persisted"`
|
||||
Error string `json:"error,omitempty"`
|
||||
|
||||
// Balance 为同一次探测得到的余额(Command Code 积分与窗口同源),其余供应商为空。
|
||||
Balance *CNProviderBalanceResult `json:"balance,omitempty"`
|
||||
}
|
||||
|
||||
// CNProviderQuotaService 探测 Kimi / Zhipu Coding Plan 的滚动窗口用量。
|
||||
// CNProviderQuotaService 探测 Kimi / Zhipu / MiniMax Coding Plan、OpenCode Go、
|
||||
// Command Code 与 Cline(ClinePass)的滚动窗口用量。
|
||||
type CNProviderQuotaService struct {
|
||||
accountRepo AccountRepository
|
||||
proxyRepo ProxyRepository
|
||||
@@ -131,6 +135,12 @@ func (s *CNProviderQuotaService) QueryUsageForAccount(ctx context.Context, accou
|
||||
|
||||
func (s *CNProviderQuotaService) queryUsageForAccount(ctx context.Context, account *Account) (*CNProviderQuotaProbeResult, error) {
|
||||
provider := account.GetCodingPlanProvider()
|
||||
if provider == PlatformCommandCode {
|
||||
return s.queryCommandCodeUsage(ctx, account)
|
||||
}
|
||||
if provider == PlatformCline {
|
||||
return s.queryClineUsage(ctx, account)
|
||||
}
|
||||
if provider != PlatformKimi && provider != PlatformZhipu && provider != PlatformMiniMax && provider != PlatformOpenCodeGo {
|
||||
return nil, infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NOT_CODING_PLAN", "account is not a kimi/zhipu/minimax coding plan or opencode go account")
|
||||
}
|
||||
@@ -290,6 +300,18 @@ func validateCodingPlanAccount(account *Account) error {
|
||||
if account.IsOpenCodeGoPlan() {
|
||||
return nil
|
||||
}
|
||||
if account.IsCommandCode() {
|
||||
if !account.commandCodeUsageSupported() {
|
||||
return infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NOT_CODING_PLAN", "command code usage is only available for api key accounts on the official host")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if account.IsCline() {
|
||||
if !account.clineAccountAPISupported() {
|
||||
return infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NOT_CODING_PLAN", "cline usage is only available for api key accounts on the official host")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if account.IsOpenCodeGo() {
|
||||
return infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NOT_CODING_PLAN", "opencode zen accounts have no subscription quota window")
|
||||
}
|
||||
|
||||
@@ -674,8 +674,9 @@ func TestAdaptiveProtocolBaseURLs(t *testing.T) {
|
||||
}{
|
||||
{"kimi payg", PlatformKimi, AccountModePayG, DefaultKimiPayGBaseURL, DefaultKimiPayGAnthropicBaseURL, DefaultKimiPayGBaseURL},
|
||||
{"kimi coding", PlatformKimi, AccountModeCoding, DefaultKimiCodingBaseURL, DefaultKimiCodingAnthropicBaseURL, DefaultKimiCodingBaseURL},
|
||||
{"zhipu payg", PlatformZhipu, AccountModePayG, DefaultZhipuPayGBaseURL, DefaultZhipuAnthropicBaseURL, DefaultZhipuPayGBaseURL},
|
||||
{"zhipu coding", PlatformZhipu, AccountModeCoding, DefaultZhipuCodingBaseURL, DefaultZhipuAnthropicBaseURL, DefaultZhipuCodingBaseURL},
|
||||
// 智谱没有原生 Responses 端点:profile 不登记 responses 条目,默认基址为空。
|
||||
{"zhipu payg", PlatformZhipu, AccountModePayG, DefaultZhipuPayGBaseURL, DefaultZhipuAnthropicBaseURL, ""},
|
||||
{"zhipu coding", PlatformZhipu, AccountModeCoding, DefaultZhipuCodingBaseURL, DefaultZhipuAnthropicBaseURL, ""},
|
||||
{"deepseek", PlatformDeepseek, AccountModePayG, DefaultDeepseekBaseURL, DefaultDeepseekAnthropicBaseURL, DefaultDeepseekBaseURL},
|
||||
{"minimax payg", PlatformMiniMax, AccountModePayG, DefaultMiniMaxBaseURL, DefaultMiniMaxAnthropicBaseURL, DefaultMiniMaxBaseURL},
|
||||
{"minimax coding", PlatformMiniMax, AccountModeCoding, DefaultMiniMaxBaseURL, DefaultMiniMaxAnthropicBaseURL, DefaultMiniMaxBaseURL},
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package service
|
||||
|
||||
// Command Code Provider API(https://commandcode.ai/docs/provider):同一 API Key 下
|
||||
// 按模型分流到三种原生端点,基址 https://api.commandcode.ai/provider/v1:
|
||||
// - Claude 系模型只在 /messages(Anthropic Messages)提供,发往其他端点返回 400;
|
||||
// - OpenAI 与开源模型提供 /chat/completions,多数也提供 /responses。
|
||||
// 每个模型支持的端点由 /models 的 supported_endpoints 给出(公开接口),网关据此在
|
||||
// 模型支持入站协议时同协议直通(见 model_protocol_catalog.go);目录就绪前使用下面的
|
||||
// 内置规则。模型名可带厂商前缀(如 deepseek/deepseek-v4-flash),原样发往上游。
|
||||
|
||||
// DefaultCommandCodeTestModel 是管理端连接测试未指定模型时使用的模型(Chat Completions)。
|
||||
const DefaultCommandCodeTestModel = "deepseek/deepseek-v4-flash"
|
||||
|
||||
// DefaultCommandCodeProtocolRules 是 Command Code 的内置分流表:Claude 只走 Anthropic;
|
||||
// GPT 同时支持 Responses 与 Chat Completions(入站同协议直通,其余入站首选 Responses);
|
||||
// 其余模型只保证 Chat Completions,是否支持 Responses 以上游模型目录为准。
|
||||
func DefaultCommandCodeProtocolRules() []ProtocolRule {
|
||||
return []ProtocolRule{
|
||||
{Pattern: "claude-*", Protocol: APIProtocolAnthropic},
|
||||
{Pattern: "gpt-*", Protocol: APIProtocolResponses, Protocols: []string{APIProtocolResponses, APIProtocolChatCompletions}},
|
||||
}
|
||||
}
|
||||
|
||||
// IsCommandCode 报告账号是否为 Command Code 平台账号。
|
||||
func (a *Account) IsCommandCode() bool {
|
||||
return a != nil && a.Platform == PlatformCommandCode
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// commandCodeTestAccount 只带 api_key:端点与分流规则全部来自 provider profile。
|
||||
func commandCodeTestAccount(id int64) *Account {
|
||||
return &Account{
|
||||
ID: id,
|
||||
Name: "cc",
|
||||
Platform: PlatformCommandCode,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "user_test_key"},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandCodeProfileRoutesByModel(t *testing.T) {
|
||||
account := commandCodeTestAccount(1)
|
||||
require.True(t, account.IsMultiProtocolAPIKey())
|
||||
require.True(t, account.routesByModel())
|
||||
require.False(t, account.RoutesProtocolByInbound())
|
||||
require.Equal(t, APIProtocolAdaptive, account.GetAPIProtocol())
|
||||
require.Equal(t, DefaultCommandCodeBaseURL, account.GetOpenAIBaseURL())
|
||||
require.Equal(t, DefaultCommandCodeAnthropicBaseURL, account.GetCNProtocolBaseURL(APIProtocolAnthropic))
|
||||
require.Equal(t, DefaultCommandCodeBaseURL, account.GetCNProtocolBaseURL(APIProtocolResponses))
|
||||
|
||||
// 未取到模型目录时按内置规则:Claude 只走 Anthropic;GPT 支持 Responses 与 Chat
|
||||
// Completions(同协议直通,Anthropic 入站走首选 Responses);其余只保证 Chat Completions。
|
||||
for _, inbound := range []string{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolAnthropic} {
|
||||
require.Equal(t, APIProtocolAnthropic, resolveUpstreamProtocol(account, inbound, "claude-sonnet-4-6", nil), inbound)
|
||||
require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, inbound, "deepseek/deepseek-v4-flash", nil), inbound)
|
||||
}
|
||||
require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(account, APIProtocolResponses, "gpt-5.5", nil))
|
||||
require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolChatCompletions, "gpt-5.5", nil))
|
||||
require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(account, APIProtocolAnthropic, "gpt-5.5", nil))
|
||||
|
||||
// 显式协议优先于内置规则。
|
||||
account.Credentials["api_protocol"] = APIProtocolChatCompletions
|
||||
require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolAnthropic, "claude-sonnet-4-6", nil))
|
||||
}
|
||||
|
||||
func TestCommandCodeNativeAnthropicTargetURL(t *testing.T) {
|
||||
svc := &OpenAIGatewayService{}
|
||||
targetURL, err := svc.nativeAnthropicTargetURL(commandCodeTestAccount(2))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "https://api.commandcode.ai/provider/v1/messages", targetURL)
|
||||
}
|
||||
|
||||
func TestAccountTestService_CommandCodeClaudeUsesAnthropicMessages(t *testing.T) {
|
||||
account := commandCodeTestAccount(501)
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNAnthropicTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "claude-sonnet-4-6", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "https://api.commandcode.ai/provider/v1/messages", upstream.requests[0].URL.String())
|
||||
require.Equal(t, "user_test_key", upstream.requests[0].Header.Get("x-api-key"))
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
|
||||
// 连接测试与转发共用端点拼接:按模型分流的平台,Anthropic 基址带 /v1 也合法。
|
||||
func TestAccountTestService_CommandCodeAnthropicBaseWithVersion(t *testing.T) {
|
||||
account := commandCodeTestAccount(504)
|
||||
account.Credentials["api_base_urls"] = map[string]any{APIProtocolAnthropic: "https://api.commandcode.ai/provider/v1"}
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNAnthropicTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "claude-sonnet-4-6", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "https://api.commandcode.ai/provider/v1/messages", upstream.requests[0].URL.String())
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
|
||||
target, err := (&OpenAIGatewayService{cfg: rawChatCompletionsTestConfig()}).nativeAnthropicTargetURL(account)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, upstream.requests[0].URL.String(), target)
|
||||
}
|
||||
|
||||
// 连接测试与网关同一判定:模型目录决定协议时,测试也按目录选择端点。
|
||||
func TestAccountTestService_CommandCodeUsesModelCatalog(t *testing.T) {
|
||||
base := fmt.Sprintf("http://cc-test-%d.example/provider/v1", time.Now().UnixNano())
|
||||
account := commandCodeTestAccount(505)
|
||||
account.Credentials["api_base_urls"] = map[string]any{
|
||||
APIProtocolChatCompletions: base,
|
||||
APIProtocolResponses: base,
|
||||
}
|
||||
url := buildOpenAIModelsURL(base)
|
||||
upstreamModelProtocols.store(modelProtocolCatalogKey(account, url),
|
||||
map[string][]string{"vendor/responses-only": {APIProtocolResponses}}, nil, time.Now())
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNResponsesTestResponse())
|
||||
svc.openaiGatewayService = &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "vendor/responses-only", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, base+"/responses", upstream.requests[0].URL.String())
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
|
||||
func TestAccountTestService_CommandCodeGPTUsesResponses(t *testing.T) {
|
||||
account := commandCodeTestAccount(502)
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNResponsesTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "gpt-5.5", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "https://api.commandcode.ai/provider/v1/responses", upstream.requests[0].URL.String())
|
||||
require.Equal(t, "Bearer user_test_key", upstream.requests[0].Header.Get("Authorization"))
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
|
||||
func TestAccountTestService_CommandCodeEmptyModelUsesProfileDefault(t *testing.T) {
|
||||
account := commandCodeTestAccount(503)
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "https://api.commandcode.ai/provider/v1/chat/completions", upstream.requests[0].URL.String())
|
||||
require.Equal(t, DefaultCommandCodeTestModel, gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
|
||||
// 仅在 profile 登记、按入站协议分流的新供应商:adaptive 测试走原生端点探测,
|
||||
// 跳过 profile 未提供的 Anthropic 端点,不再落入 Claude 测试路径。
|
||||
func TestAccountTestService_ByInboundProviderSkipsMissingNativeEndpoints(t *testing.T) {
|
||||
const platform = "test_inbound_only_chat"
|
||||
providerProfiles[platform] = &ProviderProfile{
|
||||
Platform: platform, DefaultMode: AccountModePayG, Routing: ProviderRoutingByInbound,
|
||||
DefaultTestModel: "inbound-test-model",
|
||||
Modes: map[string]ProviderEndpoints{AccountModePayG: {BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: "https://inbound.example.com/v1",
|
||||
}}},
|
||||
}
|
||||
t.Cleanup(func() { delete(providerProfiles, platform) })
|
||||
|
||||
account := &Account{
|
||||
ID: 601, Name: "inbound", Platform: platform, Type: AccountTypeAPIKey, Status: StatusActive, Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "sk-inbound", "api_protocol": APIProtocolAdaptive},
|
||||
}
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "https://inbound.example.com/v1/chat/completions", upstream.requests[0].URL.String())
|
||||
require.Equal(t, "inbound-test-model", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
|
||||
// 官方主机不做上游计费探测:中转站的计费接口在官方 API 上不存在,只会把 Key 发往官方主机。
|
||||
func TestCommandCodeOfficialHostSkipsUpstreamBillingProbe(t *testing.T) {
|
||||
require.True(t, upstreamBillingProbeTargetIsOfficialAPI(DefaultCommandCodeBaseURL))
|
||||
require.True(t, upstreamBillingProbeTargetIsOfficialAPI(DefaultCommandCodeAnthropicBaseURL))
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
)
|
||||
|
||||
// Command Code 的积分与用量窗口来自 /alpha 下四个只读接口(官方 CLI /usage 同源,
|
||||
// 社区插件实测复核),全部使用账号 API Key(Bearer):
|
||||
//
|
||||
// GET /alpha/whoami -> {user, org};个人账户 org 为 null
|
||||
// GET /alpha/billing/credits[?orgId=] -> {credits:{monthlyCredits, purchasedCredits, freeCredits},
|
||||
// windowLimits:{limited, fiveHour, weekly}}
|
||||
// GET /alpha/billing/subscriptions[?orgId=] -> {data:{planId, currentPeriodStart, currentPeriodEnd}}
|
||||
// GET /alpha/usage/summary[?orgId=][&since=] -> {totalCost, totalMonthlyCredits}
|
||||
//
|
||||
// 积分单位为美元。windowLimits 与 credits 平级;fiveHour / weekly 的 used、cap 为积分,
|
||||
// resetAt 为 epoch 毫秒;limited=false(按量计费)时没有滚动窗口。月度窗口上游只给
|
||||
// 剩余量(credits.monthlyCredits),上限按「本周期已用 + 剩余」还原。个人账户不能带
|
||||
// orgId 参数(空值返回 400),只有组织账户才带。
|
||||
//
|
||||
// 订阅套餐的滚动窗口只限制套餐内积分:有充值积分时请求跳过窗口检查,此时窗口快照
|
||||
// 不参与阈值停调与 429 冷却(见 commandCodeWindowsBinding),已有的窗口冷却在探测到
|
||||
// 充值积分后解除(见 clearCommandCodeWindowCooldown)。
|
||||
|
||||
const (
|
||||
commandCodeAPIBase = "https://api.commandcode.ai"
|
||||
|
||||
// commandCodeExtraSuffixPurchasedCredits 记录充值积分,供阈值停调与 429 冷却判断
|
||||
// 滚动窗口是否生效。
|
||||
commandCodeExtraSuffixPurchasedCredits = "purchased_credits"
|
||||
)
|
||||
|
||||
var errCommandCodeInvalidResponse = errors.New("invalid command code usage response")
|
||||
|
||||
// commandCodePlanNames 与官方 CLI 的 planId 展示名一致;未收录的原样展示。
|
||||
var commandCodePlanNames = map[string]string{
|
||||
"individual-go": "Go",
|
||||
"individual-goat": "GOAT",
|
||||
"individual-pro": "Pro",
|
||||
"individual-pro-v1": "Pro",
|
||||
"individual-provider": "Provider",
|
||||
"individual-max": "Max",
|
||||
"individual-ultra": "Ultra",
|
||||
"teams-pro": "Teams Pro",
|
||||
}
|
||||
|
||||
// commandCodeUsageSupported 报告账号能否查询 Command Code 用量:API Key 账号且推理
|
||||
// 端点指向官方主机。自定义中转的 Key 不发往官方用量接口。
|
||||
func (a *Account) commandCodeUsageSupported() bool {
|
||||
return a.IsCommandCode() && a.Type == AccountTypeAPIKey && isOfficialCommandCodeHost(a.GetOpenAIBaseURL())
|
||||
}
|
||||
|
||||
// commandCodeNumber 兼容数字与数字字符串。
|
||||
type commandCodeNumber float64
|
||||
|
||||
func (n *commandCodeNumber) UnmarshalJSON(data []byte) error {
|
||||
data = bytes.TrimSpace(data)
|
||||
if len(data) == 0 || bytes.Equal(data, []byte("null")) {
|
||||
*n = 0
|
||||
return nil
|
||||
}
|
||||
if data[0] == '"' {
|
||||
var s string
|
||||
if err := json.Unmarshal(data, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
v, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*n = commandCodeNumber(v)
|
||||
return nil
|
||||
}
|
||||
var v float64
|
||||
if err := json.Unmarshal(data, &v); err != nil {
|
||||
return err
|
||||
}
|
||||
*n = commandCodeNumber(v)
|
||||
return nil
|
||||
}
|
||||
|
||||
type commandCodeWindow struct {
|
||||
Used commandCodeNumber `json:"used"`
|
||||
Cap commandCodeNumber `json:"cap"`
|
||||
ResetAt commandCodeNumber `json:"resetAt"`
|
||||
}
|
||||
|
||||
type commandCodeCredits struct {
|
||||
MonthlyCredits commandCodeNumber `json:"monthlyCredits"`
|
||||
PurchasedCredits commandCodeNumber `json:"purchasedCredits"`
|
||||
FreeCredits commandCodeNumber `json:"freeCredits"`
|
||||
}
|
||||
|
||||
type commandCodeCreditsPayload struct {
|
||||
Credits *commandCodeCredits `json:"credits"`
|
||||
WindowLimits struct {
|
||||
Limited bool `json:"limited"`
|
||||
FiveHour *commandCodeWindow `json:"fiveHour"`
|
||||
Weekly *commandCodeWindow `json:"weekly"`
|
||||
} `json:"windowLimits"`
|
||||
}
|
||||
|
||||
type commandCodeSubscriptionPayload struct {
|
||||
Data struct {
|
||||
PlanID string `json:"planId"`
|
||||
CurrentPeriodStart string `json:"currentPeriodStart"`
|
||||
CurrentPeriodEnd string `json:"currentPeriodEnd"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type commandCodeSummaryPayload struct {
|
||||
TotalCost *commandCodeNumber `json:"totalCost"`
|
||||
TotalMonthlyCredits *commandCodeNumber `json:"totalMonthlyCredits"`
|
||||
}
|
||||
|
||||
// commandCodeUsage 是一次取数的汇总;subscription / summary 取数失败时为 nil,并置
|
||||
// periodFetchFailed:此时无从判断月度窗口是否存在,不能当作没有月度窗口。
|
||||
type commandCodeUsage struct {
|
||||
credits commandCodeCreditsPayload
|
||||
subscription *commandCodeSubscriptionPayload
|
||||
summary *commandCodeSummaryPayload
|
||||
periodFetchFailed bool
|
||||
}
|
||||
|
||||
// commandCodeHTTPError 是 /alpha 接口的非 2xx 响应。
|
||||
type commandCodeHTTPError struct {
|
||||
status int
|
||||
body string
|
||||
}
|
||||
|
||||
func (e *commandCodeHTTPError) Error() string {
|
||||
return fmt.Sprintf("HTTP %d: %s", e.status, e.body)
|
||||
}
|
||||
|
||||
func (e *commandCodeHTTPError) unauthorized() bool {
|
||||
return e.status == http.StatusUnauthorized || e.status == http.StatusForbidden
|
||||
}
|
||||
|
||||
func isCommandCodeAuthError(err error) bool {
|
||||
var httpErr *commandCodeHTTPError
|
||||
return errors.As(err, &httpErr) && httpErr.unauthorized()
|
||||
}
|
||||
|
||||
type commandCodeUsageClient struct {
|
||||
cfg *config.Config
|
||||
httpUpstream HTTPUpstream
|
||||
account *Account
|
||||
apiKey string
|
||||
proxyURL string
|
||||
}
|
||||
|
||||
// get 请求一个 /alpha 接口并解码 JSON。
|
||||
func (c *commandCodeUsageClient) get(ctx context.Context, path string, query url.Values, out any) error {
|
||||
target := commandCodeAPIBase + path
|
||||
if len(query) > 0 {
|
||||
target += "?" + query.Encode()
|
||||
}
|
||||
validatedURL, err := cnValidateProbeURL(c.cfg, target)
|
||||
if err != nil {
|
||||
return infraerrors.New(http.StatusForbidden, "CN_QUOTA_URL_REJECTED", err.Error())
|
||||
}
|
||||
callCtx, cancel := context.WithTimeout(ctx, cnQuotaUpstreamTimeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(callCtx, http.MethodGet, validatedURL, nil)
|
||||
if err != nil {
|
||||
return infraerrors.Newf(http.StatusInternalServerError, "CN_QUOTA_REQUEST_BUILD_FAILED", "build request: %v", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.apiKey)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
c.account.ApplyHeaderOverrides(req.Header)
|
||||
|
||||
resp, err := c.httpUpstream.Do(req, c.proxyURL, c.account.ID, maxInt(c.account.Concurrency, 1))
|
||||
if err != nil {
|
||||
return fmt.Errorf("upstream request failed: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, cnQuotaMaxBodyBytes))
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return &commandCodeHTTPError{status: resp.StatusCode, body: truncate(strings.TrimSpace(string(body)), 240)}
|
||||
}
|
||||
if err := json.Unmarshal(body, out); err != nil {
|
||||
return fmt.Errorf("%w: %s: %v", errCommandCodeInvalidResponse, path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetch 取积分与窗口;withPeriod 时再取订阅周期与本周期用量以还原月度窗口。
|
||||
// whoami 用来取 orgId,任何失败都整体返回:无从判断是否组织账户时,按个人账户查会把
|
||||
// 组织账号查成成员的个人钱包,并据此按余额停调。
|
||||
func (c *commandCodeUsageClient) fetch(ctx context.Context, withPeriod bool) (*commandCodeUsage, error) {
|
||||
var whoami struct {
|
||||
Org *struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"org"`
|
||||
}
|
||||
query := url.Values{}
|
||||
if err := c.get(ctx, "/alpha/whoami", nil, &whoami); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if whoami.Org != nil && strings.TrimSpace(whoami.Org.ID) != "" {
|
||||
query.Set("orgId", strings.TrimSpace(whoami.Org.ID))
|
||||
}
|
||||
|
||||
usage := &commandCodeUsage{}
|
||||
if err := c.get(ctx, "/alpha/billing/credits", query, &usage.credits); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if usage.credits.Credits == nil {
|
||||
return nil, fmt.Errorf("%w: credits missing", errCommandCodeInvalidResponse)
|
||||
}
|
||||
if !withPeriod {
|
||||
return usage, nil
|
||||
}
|
||||
|
||||
var subscription commandCodeSubscriptionPayload
|
||||
if err := c.get(ctx, "/alpha/billing/subscriptions", query, &subscription); err != nil {
|
||||
if isCommandCodeAuthError(err) {
|
||||
return nil, err
|
||||
}
|
||||
slog.Warn("command_code_subscription_failed", "account_id", c.account.ID, "error", err)
|
||||
usage.periodFetchFailed = true
|
||||
return usage, nil
|
||||
}
|
||||
usage.subscription = &subscription
|
||||
periodStart := strings.TrimSpace(subscription.Data.CurrentPeriodStart)
|
||||
if periodStart == "" {
|
||||
return usage, nil
|
||||
}
|
||||
summaryQuery := url.Values{}
|
||||
for key, values := range query {
|
||||
summaryQuery[key] = values
|
||||
}
|
||||
summaryQuery.Set("since", periodStart)
|
||||
var summary commandCodeSummaryPayload
|
||||
if err := c.get(ctx, "/alpha/usage/summary", summaryQuery, &summary); err != nil {
|
||||
if isCommandCodeAuthError(err) {
|
||||
return nil, err
|
||||
}
|
||||
slog.Warn("command_code_usage_summary_failed", "account_id", c.account.ID, "error", err)
|
||||
usage.periodFetchFailed = true
|
||||
return usage, nil
|
||||
}
|
||||
usage.summary = &summary
|
||||
return usage, nil
|
||||
}
|
||||
|
||||
func isApplicationError(err error) bool {
|
||||
var appErr *infraerrors.ApplicationError
|
||||
return errors.As(err, &appErr)
|
||||
}
|
||||
|
||||
func commandCodePercent(used, limit float64) float64 {
|
||||
percent := used / limit * 100
|
||||
if percent < 0 {
|
||||
percent = 0
|
||||
}
|
||||
return math.Round(percent*100) / 100
|
||||
}
|
||||
|
||||
// tiers 返回 5h / weekly(限额套餐)与月度窗口。
|
||||
func (u *commandCodeUsage) tiers() []CNQuotaTier {
|
||||
var tiers []CNQuotaTier
|
||||
limits := u.credits.WindowLimits
|
||||
if limits.Limited {
|
||||
for _, item := range []struct {
|
||||
window string
|
||||
limit *commandCodeWindow
|
||||
}{
|
||||
{window: "5h", limit: limits.FiveHour},
|
||||
{window: "weekly", limit: limits.Weekly},
|
||||
} {
|
||||
if item.limit == nil || item.limit.Cap <= 0 {
|
||||
continue
|
||||
}
|
||||
tiers = append(tiers, CNQuotaTier{
|
||||
Window: item.window,
|
||||
UsedPercent: commandCodePercent(float64(item.limit.Used), float64(item.limit.Cap)),
|
||||
ResetAt: cnMillisToRFC3339(int64(item.limit.ResetAt)),
|
||||
})
|
||||
}
|
||||
}
|
||||
if u.summary != nil && u.subscription != nil {
|
||||
used := 0.0
|
||||
switch {
|
||||
case u.summary.TotalMonthlyCredits != nil:
|
||||
used = float64(*u.summary.TotalMonthlyCredits)
|
||||
case u.summary.TotalCost != nil:
|
||||
used = float64(*u.summary.TotalCost)
|
||||
}
|
||||
if limit := used + float64(u.credits.Credits.MonthlyCredits); limit > 0 {
|
||||
tiers = append(tiers, CNQuotaTier{
|
||||
Window: "monthly",
|
||||
UsedPercent: commandCodePercent(used, limit),
|
||||
ResetAt: cnNormalizeResetTime(u.subscription.Data.CurrentPeriodEnd),
|
||||
})
|
||||
}
|
||||
}
|
||||
return tiers
|
||||
}
|
||||
|
||||
func (u *commandCodeUsage) planName() string {
|
||||
if u.subscription == nil {
|
||||
return ""
|
||||
}
|
||||
planID := strings.TrimSpace(u.subscription.Data.PlanID)
|
||||
if name, ok := commandCodePlanNames[planID]; ok {
|
||||
return name
|
||||
}
|
||||
return planID
|
||||
}
|
||||
|
||||
// balance 返回可用积分合计(套餐剩余 + 充值 + 赠送,美元)。
|
||||
func (u *commandCodeUsage) balance(now time.Time) *CNProviderBalanceResult {
|
||||
credits := u.credits.Credits
|
||||
total := float64(credits.MonthlyCredits + credits.PurchasedCredits + credits.FreeCredits)
|
||||
total = math.Round(total*10000) / 10000
|
||||
return &CNProviderBalanceResult{
|
||||
Provider: PlatformCommandCode,
|
||||
Success: true,
|
||||
Balance: total,
|
||||
Currency: "USD",
|
||||
Balances: []CNProviderBalanceEntry{{Currency: "USD", Balance: total}},
|
||||
Available: true,
|
||||
StatusCode: http.StatusOK,
|
||||
FetchedAt: now.Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
// clearCommandCodeWindowCooldown 在探测到充值积分时解除窗口用满的临时停调:充值积分
|
||||
// 不受滚动窗口限制,上游已允许继续请求。只清除 commandCodeUsageLimitReason 前缀的停调,
|
||||
// 积分不足、花费上限、管理员规则等其他原因的停调不受影响。
|
||||
func clearCommandCodeWindowCooldown(ctx context.Context, repo AccountRepository, account *Account, usage *commandCodeUsage, now time.Time) bool {
|
||||
if usage == nil || usage.credits.Credits == nil || usage.credits.Credits.PurchasedCredits <= 0 {
|
||||
return false
|
||||
}
|
||||
if account.TempUnschedulableUntil == nil || !now.Before(*account.TempUnschedulableUntil) ||
|
||||
!strings.HasPrefix(account.TempUnschedulableReason, commandCodeUsageLimitReason) {
|
||||
return false
|
||||
}
|
||||
if err := repo.ClearTempUnschedulable(ctx, account.ID); err != nil {
|
||||
slog.Warn("command_code_usage_limit_clear_failed", "account_id", account.ID, "error", err)
|
||||
return false
|
||||
}
|
||||
slog.Info("command_code_usage_limit_cleared", "account_id", account.ID,
|
||||
"purchased_credits", float64(usage.credits.Credits.PurchasedCredits))
|
||||
return true
|
||||
}
|
||||
|
||||
// commandCodeWindowsBinding 报告账号快照中的滚动 / 月度窗口是否限制调度:
|
||||
// 有充值积分时上游跳过窗口检查,窗口用满也不会被拒绝。
|
||||
func commandCodeWindowsBinding(extra map[string]any) bool {
|
||||
purchased, ok := cnParseF64(extra[cnExtraKey(PlatformCommandCode, commandCodeExtraSuffixPurchasedCredits)])
|
||||
return !ok || purchased <= 0
|
||||
}
|
||||
|
||||
// commandCodeUsageExtraUpdates 构造窗口 + 余额快照。缺席的窗口写 nil,避免套餐
|
||||
// 变化后沿用旧快照;窗口尚未开始时没有重置时间,同样清掉上一个窗口的值;月度窗口
|
||||
// 取数失败时保留旧快照;传 nil tiers 时只写余额。
|
||||
func commandCodeUsageExtraUpdates(usage *commandCodeUsage, tiers []CNQuotaTier, balance *CNProviderBalanceResult, now time.Time, withTiers bool) map[string]any {
|
||||
updates := cnBalanceExtraUpdates(PlatformCommandCode, balance, now)
|
||||
updates[cnExtraKey(PlatformCommandCode, commandCodeExtraSuffixPurchasedCredits)] = float64(usage.credits.Credits.PurchasedCredits)
|
||||
if !withTiers {
|
||||
return updates
|
||||
}
|
||||
for key, value := range cnQuotaExtraUpdates(PlatformCommandCode, tiers, now) {
|
||||
updates[key] = value
|
||||
}
|
||||
present := make(map[string]CNQuotaTier, len(tiers))
|
||||
for _, tier := range tiers {
|
||||
present[tier.Window] = tier
|
||||
}
|
||||
for _, window := range []struct {
|
||||
name, used, reset string
|
||||
}{
|
||||
{"5h", cnExtraSuffix5hUsed, cnExtraSuffix5hReset},
|
||||
{"weekly", cnExtraSuffixWeeklyUsed, cnExtraSuffixWeeklyReset},
|
||||
{"monthly", cnExtraSuffixMonthlyUsed, cnExtraSuffixMonthlyReset},
|
||||
} {
|
||||
tier, ok := present[window.name]
|
||||
if !ok && window.name == "monthly" && usage.periodFetchFailed {
|
||||
continue
|
||||
}
|
||||
if !ok {
|
||||
updates[cnExtraKey(PlatformCommandCode, window.used)] = nil
|
||||
}
|
||||
if tier.ResetAt == "" {
|
||||
updates[cnExtraKey(PlatformCommandCode, window.reset)] = nil
|
||||
}
|
||||
}
|
||||
return updates
|
||||
}
|
||||
|
||||
func newCommandCodeUsageClient(cfg *config.Config, httpUpstream HTTPUpstream, account *Account, proxyURL string) *commandCodeUsageClient {
|
||||
return &commandCodeUsageClient{
|
||||
cfg: cfg,
|
||||
httpUpstream: httpUpstream,
|
||||
account: account,
|
||||
apiKey: strings.TrimSpace(account.GetCNAPIKey()),
|
||||
proxyURL: proxyURL,
|
||||
}
|
||||
}
|
||||
|
||||
// commandCodeFetchFailure 把取数错误转换为探测失败文案;ok=false 表示应作为错误返回。
|
||||
func commandCodeFetchFailure(err error) (status int, message string, ok bool) {
|
||||
var httpErr *commandCodeHTTPError
|
||||
switch {
|
||||
case errors.As(err, &httpErr) && httpErr.unauthorized():
|
||||
return httpErr.status, fmt.Sprintf("Authentication failed (HTTP %d)", httpErr.status), true
|
||||
case errors.As(err, &httpErr):
|
||||
return httpErr.status, fmt.Sprintf("API error (HTTP %d): %s", httpErr.status, httpErr.body), true
|
||||
case errors.Is(err, errCommandCodeInvalidResponse):
|
||||
return http.StatusOK, "Invalid usage response", true
|
||||
default:
|
||||
return 0, "", false
|
||||
}
|
||||
}
|
||||
|
||||
// queryCommandCodeUsage 查询 Command Code 积分与窗口,落窗口与余额快照。
|
||||
func (s *CNProviderQuotaService) queryCommandCodeUsage(ctx context.Context, account *Account) (*CNProviderQuotaProbeResult, error) {
|
||||
client := newCommandCodeUsageClient(s.cfg, s.httpUpstream, account, s.resolveProxyURL(ctx, account))
|
||||
if client.apiKey == "" {
|
||||
return nil, infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NO_APIKEY", "account api_key is empty")
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
result := &CNProviderQuotaProbeResult{
|
||||
Provider: PlatformCommandCode,
|
||||
Source: "command_code_usage",
|
||||
FetchedAt: now.Unix(),
|
||||
}
|
||||
usage, err := client.fetch(ctx, true)
|
||||
if err != nil {
|
||||
status, message, ok := commandCodeFetchFailure(err)
|
||||
if !ok {
|
||||
if isApplicationError(err) {
|
||||
return nil, err
|
||||
}
|
||||
return nil, infraerrors.Newf(http.StatusBadGateway, "CN_QUOTA_REQUEST_FAILED", "%v", err)
|
||||
}
|
||||
result.StatusCode = status
|
||||
result.Error = message
|
||||
return result, nil
|
||||
}
|
||||
|
||||
tiers := usage.tiers()
|
||||
balance := usage.balance(now)
|
||||
result.StatusCode = http.StatusOK
|
||||
result.Tiers = tiers
|
||||
result.PlanLevel = usage.planName()
|
||||
result.Balance = balance
|
||||
result.Success = true
|
||||
result.CredentialValid = true
|
||||
|
||||
updates := commandCodeUsageExtraUpdates(usage, tiers, balance, now, true)
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil {
|
||||
slog.Warn("cn_quota_persist_failed", "account_id", account.ID, "provider", PlatformCommandCode, "error", err)
|
||||
} else {
|
||||
result.Persisted = true
|
||||
balance.Persisted = true
|
||||
}
|
||||
clearCommandCodeWindowCooldown(ctx, s.accountRepo, account, usage, now)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// queryCommandCodeBalance 只查积分余额(whoami + credits),落余额快照。
|
||||
func (s *CNProviderBalanceService) queryCommandCodeBalance(ctx context.Context, account *Account) (*CNProviderBalanceResult, error) {
|
||||
client := newCommandCodeUsageClient(s.cfg, s.httpUpstream, account, s.resolveProxyURL(ctx, account))
|
||||
if client.apiKey == "" {
|
||||
return nil, infraerrors.New(http.StatusBadRequest, "CN_BALANCE_NO_APIKEY", "account api_key is empty")
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
usage, err := client.fetch(ctx, false)
|
||||
if err != nil {
|
||||
status, message, ok := commandCodeFetchFailure(err)
|
||||
if !ok {
|
||||
if isApplicationError(err) {
|
||||
return nil, err
|
||||
}
|
||||
return nil, infraerrors.Newf(http.StatusBadGateway, "CN_BALANCE_REQUEST_FAILED", "%v", err)
|
||||
}
|
||||
return &CNProviderBalanceResult{
|
||||
Provider: PlatformCommandCode,
|
||||
StatusCode: status,
|
||||
FetchedAt: now.Unix(),
|
||||
Available: true,
|
||||
Error: message,
|
||||
}, nil
|
||||
}
|
||||
result := usage.balance(now)
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, commandCodeUsageExtraUpdates(usage, nil, result, now, false)); err != nil {
|
||||
slog.Warn("cn_balance_persist_failed", "account_id", account.ID, "provider", PlatformCommandCode, "error", err)
|
||||
} else {
|
||||
result.Persisted = true
|
||||
}
|
||||
clearCommandCodeWindowCooldown(ctx, s.accountRepo, account, usage, now)
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// commandCodeAlphaUpstream 按路径返回 /alpha 接口响应,并记录请求。
|
||||
type commandCodeAlphaUpstream struct {
|
||||
mu sync.Mutex
|
||||
responses map[string]commandCodeAlphaResponse
|
||||
requests []*http.Request
|
||||
}
|
||||
|
||||
type commandCodeAlphaResponse struct {
|
||||
status int
|
||||
body string
|
||||
}
|
||||
|
||||
func (u *commandCodeAlphaUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
u.mu.Lock()
|
||||
u.requests = append(u.requests, req)
|
||||
u.mu.Unlock()
|
||||
resp, ok := u.responses[req.URL.Path]
|
||||
if !ok {
|
||||
resp = commandCodeAlphaResponse{status: http.StatusNotFound, body: `{"error":"not found"}`}
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: resp.status,
|
||||
Body: io.NopCloser(strings.NewReader(resp.body)),
|
||||
Header: make(http.Header),
|
||||
Request: req,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (u *commandCodeAlphaUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
return u.Do(req, proxyURL, accountID, concurrency)
|
||||
}
|
||||
|
||||
func (u *commandCodeAlphaUpstream) request(path string) *http.Request {
|
||||
for _, req := range u.requests {
|
||||
if req.URL.Path == path {
|
||||
return req
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const (
|
||||
commandCodeTestCredits = `{
|
||||
"credits": {"belowThreshold": false, "monthlyCredits": "34.9", "purchasedCredits": 0, "freeCredits": 0.1},
|
||||
"windowLimits": {
|
||||
"limited": true,
|
||||
"fiveHour": {"used": 1.5, "cap": 14, "resetAt": 1790000000000},
|
||||
"weekly": {"used": 35, "cap": 35, "resetAt": 1790400000000}
|
||||
}
|
||||
}`
|
||||
commandCodeTestSubscription = `{"data": {"planId": "individual-goat", "status": "active",
|
||||
"currentPeriodStart": "2026-09-01T00:00:00Z", "currentPeriodEnd": "2026-10-01T00:00:00Z"}}`
|
||||
commandCodeTestSummary = `{"totalCost": 40, "totalMonthlyCredits": 35.1}`
|
||||
)
|
||||
|
||||
func commandCodeUsageAccount() *Account {
|
||||
account := commandCodeTestAccount(77)
|
||||
account.Concurrency = 1
|
||||
return account
|
||||
}
|
||||
|
||||
func newCommandCodeAlphaUpstream(whoami string) *commandCodeAlphaUpstream {
|
||||
return &commandCodeAlphaUpstream{responses: map[string]commandCodeAlphaResponse{
|
||||
"/alpha/whoami": {status: http.StatusOK, body: whoami},
|
||||
"/alpha/billing/credits": {status: http.StatusOK, body: commandCodeTestCredits},
|
||||
"/alpha/billing/subscriptions": {status: http.StatusOK, body: commandCodeTestSubscription},
|
||||
"/alpha/usage/summary": {status: http.StatusOK, body: commandCodeTestSummary},
|
||||
}}
|
||||
}
|
||||
|
||||
func TestCommandCodeQuotaProbeParsesWindowsAndBalance(t *testing.T) {
|
||||
account := commandCodeUsageAccount()
|
||||
upstream := newCommandCodeAlphaUpstream(`{"user": {"userName": "alice"}, "org": null}`)
|
||||
repo := &cnBalanceProbeRepo{account: account}
|
||||
svc := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{})
|
||||
|
||||
result, err := svc.QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.Success)
|
||||
require.True(t, result.Persisted)
|
||||
require.Equal(t, PlatformCommandCode, result.Provider)
|
||||
require.Equal(t, "GOAT", result.PlanLevel)
|
||||
require.Equal(t, []CNQuotaTier{
|
||||
{Window: "5h", UsedPercent: 10.71, ResetAt: time.UnixMilli(1790000000000).UTC().Format(time.RFC3339)},
|
||||
{Window: "weekly", UsedPercent: 100, ResetAt: time.UnixMilli(1790400000000).UTC().Format(time.RFC3339)},
|
||||
{Window: "monthly", UsedPercent: 50.14, ResetAt: "2026-10-01T00:00:00Z"},
|
||||
}, result.Tiers)
|
||||
require.NotNil(t, result.Balance)
|
||||
require.InDelta(t, 35.0, result.Balance.Balance, 1e-9)
|
||||
require.Equal(t, "USD", result.Balance.Currency)
|
||||
|
||||
// 个人账户不带 orgId;本周期用量从订阅周期起点统计。
|
||||
for _, req := range upstream.requests {
|
||||
require.Equal(t, "Bearer user_test_key", req.Header.Get("Authorization"))
|
||||
require.Equal(t, "api.commandcode.ai", req.URL.Host)
|
||||
require.False(t, req.URL.Query().Has("orgId"), req.URL.String())
|
||||
}
|
||||
require.Equal(t, "2026-09-01T00:00:00Z", upstream.request("/alpha/usage/summary").URL.Query().Get("since"))
|
||||
|
||||
require.Len(t, repo.extraWrites, 1)
|
||||
extra := repo.extraWrites[0]
|
||||
require.Equal(t, 10.71, extra["command_code_5h_used_percent"])
|
||||
require.Equal(t, 100.0, extra["command_code_weekly_used_percent"])
|
||||
require.Equal(t, 50.14, extra["command_code_monthly_used_percent"])
|
||||
require.Equal(t, "2026-10-01T00:00:00Z", extra["command_code_monthly_reset_at"])
|
||||
require.InDelta(t, 35.0, extra["command_code_balance"], 1e-9)
|
||||
require.Equal(t, "USD", extra["command_code_balance_currency"])
|
||||
require.Equal(t, 0.0, extra["command_code_purchased_credits"])
|
||||
require.Equal(t, false, extra["command_code_balance_low"])
|
||||
}
|
||||
|
||||
func TestCommandCodeQuotaProbePassesOrgID(t *testing.T) {
|
||||
account := commandCodeUsageAccount()
|
||||
upstream := newCommandCodeAlphaUpstream(`{"user": {"userName": "alice"}, "org": {"id": "9a0f5d0e-6d2c-4f36-9c55-0b8b0c0d1e2f", "login": "team"}}`)
|
||||
svc := NewCNProviderQuotaService(&cnBalanceProbeRepo{account: account}, nil, upstream, &config.Config{})
|
||||
|
||||
_, err := svc.QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
for _, path := range []string{"/alpha/billing/credits", "/alpha/billing/subscriptions", "/alpha/usage/summary"} {
|
||||
require.Equal(t, "9a0f5d0e-6d2c-4f36-9c55-0b8b0c0d1e2f", upstream.request(path).URL.Query().Get("orgId"), path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandCodeQuotaProbeUnlimitedPlanClearsRollingWindows(t *testing.T) {
|
||||
account := commandCodeUsageAccount()
|
||||
upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
|
||||
upstream.responses["/alpha/billing/credits"] = commandCodeAlphaResponse{status: http.StatusOK, body: `{
|
||||
"credits": {"monthlyCredits": 10, "purchasedCredits": 25, "freeCredits": 0},
|
||||
"windowLimits": {"limited": false}
|
||||
}`}
|
||||
upstream.responses["/alpha/usage/summary"] = commandCodeAlphaResponse{status: http.StatusOK, body: `{"totalCost": 5}`}
|
||||
repo := &cnBalanceProbeRepo{account: account}
|
||||
svc := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{})
|
||||
|
||||
result, err := svc.QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []CNQuotaTier{{Window: "monthly", UsedPercent: 33.33, ResetAt: "2026-10-01T00:00:00Z"}}, result.Tiers)
|
||||
extra := repo.extraWrites[0]
|
||||
for _, key := range []string{"command_code_5h_used_percent", "command_code_5h_reset_at", "command_code_weekly_used_percent", "command_code_weekly_reset_at"} {
|
||||
value, ok := extra[key]
|
||||
require.True(t, ok, key)
|
||||
require.Nil(t, value, key)
|
||||
}
|
||||
require.Equal(t, 25.0, extra["command_code_purchased_credits"])
|
||||
require.InDelta(t, 35.0, extra["command_code_balance"], 1e-9)
|
||||
}
|
||||
|
||||
// 窗口尚未开始(resetAt 为空)时清掉上一个窗口的重置时间,不与新的用量配对。
|
||||
func TestCommandCodeQuotaProbeClearsResetOfUnstartedWindow(t *testing.T) {
|
||||
account := commandCodeUsageAccount()
|
||||
upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
|
||||
upstream.responses["/alpha/billing/credits"] = commandCodeAlphaResponse{status: http.StatusOK, body: `{
|
||||
"credits": {"monthlyCredits": 34.9, "purchasedCredits": 0, "freeCredits": 0},
|
||||
"windowLimits": {
|
||||
"limited": true,
|
||||
"fiveHour": {"used": 0, "cap": 14, "resetAt": null},
|
||||
"weekly": {"used": 35, "cap": 35, "resetAt": 1790400000000}
|
||||
}
|
||||
}`}
|
||||
repo := &cnBalanceProbeRepo{account: account}
|
||||
|
||||
_, err := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{}).QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
extra := repo.extraWrites[0]
|
||||
require.Equal(t, 0.0, extra["command_code_5h_used_percent"])
|
||||
value, written := extra["command_code_5h_reset_at"]
|
||||
require.True(t, written)
|
||||
require.Nil(t, value)
|
||||
require.Equal(t, time.UnixMilli(1790400000000).UTC().Format(time.RFC3339), extra["command_code_weekly_reset_at"])
|
||||
require.Equal(t, "2026-10-01T00:00:00Z", extra["command_code_monthly_reset_at"])
|
||||
}
|
||||
|
||||
func TestCommandCodeQuotaProbeAuthFailureDoesNotPersist(t *testing.T) {
|
||||
account := commandCodeUsageAccount()
|
||||
upstream := newCommandCodeAlphaUpstream(`{}`)
|
||||
upstream.responses["/alpha/whoami"] = commandCodeAlphaResponse{status: http.StatusUnauthorized, body: `{"error":"unauthorized"}`}
|
||||
repo := &cnBalanceProbeRepo{account: account}
|
||||
svc := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{})
|
||||
|
||||
result, err := svc.QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.False(t, result.Success)
|
||||
require.Equal(t, http.StatusUnauthorized, result.StatusCode)
|
||||
require.Equal(t, "Authentication failed (HTTP 401)", result.Error)
|
||||
require.Empty(t, repo.extraWrites)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
}
|
||||
|
||||
// 订阅周期或本周期用量取数失败:滚动窗口照常更新,月度快照保留上一次的值(无从判断
|
||||
// 月度窗口是否还在);订阅确实没有周期时才清掉月度快照。
|
||||
// whoami 失败(非鉴权错误)时无从判断是否组织账户:探测整体失败,不按个人账户去查
|
||||
// credits,也不写快照。
|
||||
func TestCommandCodeProbeFailsWhenWhoamiFails(t *testing.T) {
|
||||
for _, whoami := range []commandCodeAlphaResponse{
|
||||
{status: http.StatusBadGateway, body: `bad gateway`},
|
||||
{status: http.StatusOK, body: `not json`},
|
||||
} {
|
||||
account := commandCodeUsageAccount()
|
||||
upstream := newCommandCodeAlphaUpstream(`{}`)
|
||||
upstream.responses["/alpha/whoami"] = whoami
|
||||
repo := &cnBalanceProbeRepo{account: account}
|
||||
|
||||
result, err := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{}).QueryUsage(context.Background(), account.ID)
|
||||
require.NoError(t, err, whoami.body)
|
||||
require.False(t, result.Success, whoami.body)
|
||||
require.NotEmpty(t, result.Error, whoami.body)
|
||||
|
||||
balance, err := NewCNProviderBalanceService(repo, nil, upstream, &config.Config{}).QueryBalance(context.Background(), account.ID)
|
||||
require.NoError(t, err, whoami.body)
|
||||
require.False(t, balance.Success, whoami.body)
|
||||
|
||||
require.Nil(t, upstream.request("/alpha/billing/credits"), whoami.body)
|
||||
require.Empty(t, repo.extraWrites, whoami.body)
|
||||
}
|
||||
|
||||
// 请求本身失败(网络错误)同样整体失败。
|
||||
account := commandCodeUsageAccount()
|
||||
repo := &cnBalanceProbeRepo{account: account}
|
||||
_, err := NewCNProviderQuotaService(repo, nil, failingCommandCodeUpstream{}, &config.Config{}).QueryUsage(context.Background(), account.ID)
|
||||
require.Error(t, err)
|
||||
require.Empty(t, repo.extraWrites)
|
||||
}
|
||||
|
||||
// failingCommandCodeUpstream 让每个请求都在网络层失败。
|
||||
type failingCommandCodeUpstream struct{}
|
||||
|
||||
func (failingCommandCodeUpstream) Do(*http.Request, string, int64, int) (*http.Response, error) {
|
||||
return nil, errors.New("dial tcp: i/o timeout")
|
||||
}
|
||||
|
||||
func (u failingCommandCodeUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
return u.Do(req, proxyURL, accountID, concurrency)
|
||||
}
|
||||
|
||||
func TestCommandCodeQuotaProbeKeepsWindowsWhenPeriodEndpointsFail(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
path string
|
||||
response commandCodeAlphaResponse
|
||||
planLevel string
|
||||
keepMonthly bool
|
||||
}{
|
||||
{"subscriptions failed", "/alpha/billing/subscriptions", commandCodeAlphaResponse{status: http.StatusInternalServerError, body: `oops`}, "", true},
|
||||
{"summary failed", "/alpha/usage/summary", commandCodeAlphaResponse{status: http.StatusBadGateway, body: `oops`}, "GOAT", true},
|
||||
{"no subscription period", "/alpha/billing/subscriptions", commandCodeAlphaResponse{status: http.StatusOK, body: `{"data":{}}`}, "", false},
|
||||
} {
|
||||
account := commandCodeUsageAccount()
|
||||
upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
|
||||
upstream.responses[tc.path] = tc.response
|
||||
repo := &cnBalanceProbeRepo{account: account}
|
||||
|
||||
result, err := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{}).QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err, tc.name)
|
||||
require.True(t, result.Success, tc.name)
|
||||
require.Len(t, result.Tiers, 2, tc.name)
|
||||
require.Equal(t, tc.planLevel, result.PlanLevel, tc.name)
|
||||
if tc.path == "/alpha/billing/subscriptions" {
|
||||
require.Nil(t, upstream.request("/alpha/usage/summary"), tc.name)
|
||||
}
|
||||
extra := repo.extraWrites[0]
|
||||
require.Equal(t, 10.71, extra["command_code_5h_used_percent"], tc.name)
|
||||
for _, key := range []string{"command_code_monthly_used_percent", "command_code_monthly_reset_at"} {
|
||||
value, written := extra[key]
|
||||
require.Equal(t, !tc.keepMonthly, written, tc.name+": "+key)
|
||||
require.Nil(t, value, tc.name+": "+key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandCodeUsageRequiresOfficialHost(t *testing.T) {
|
||||
account := commandCodeUsageAccount()
|
||||
require.Equal(t, PlatformCommandCode, account.GetCodingPlanProvider())
|
||||
require.NoError(t, validateCodingPlanAccount(account))
|
||||
require.NoError(t, validatePayGAccount(account))
|
||||
|
||||
account.Credentials["base_url"] = "https://relay.example.com/v1"
|
||||
account.Credentials["api_protocol"] = APIProtocolChatCompletions
|
||||
require.Empty(t, account.GetCodingPlanProvider())
|
||||
require.Error(t, validateCodingPlanAccount(account))
|
||||
require.Error(t, validatePayGAccount(account))
|
||||
}
|
||||
|
||||
func TestCommandCodeBalanceProbeFetchesCreditsOnly(t *testing.T) {
|
||||
account := commandCodeUsageAccount()
|
||||
upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
|
||||
repo := &cnBalanceProbeRepo{account: account}
|
||||
svc := NewCNProviderBalanceService(repo, nil, upstream, &config.Config{})
|
||||
|
||||
result, err := svc.QueryBalance(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.Success)
|
||||
require.True(t, result.Persisted)
|
||||
require.InDelta(t, 35.0, result.Balance, 1e-9)
|
||||
require.Len(t, upstream.requests, 2)
|
||||
require.Len(t, repo.extraWrites, 1)
|
||||
_, hasWindow := repo.extraWrites[0]["command_code_5h_used_percent"]
|
||||
require.False(t, hasWindow)
|
||||
require.InDelta(t, 35.0, repo.extraWrites[0]["command_code_balance"], 1e-9)
|
||||
}
|
||||
|
||||
func TestCommandCodeWindowsIgnoredWithPurchasedCredits(t *testing.T) {
|
||||
future := time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339)
|
||||
account := commandCodeUsageAccount()
|
||||
account.Extra = map[string]any{
|
||||
"command_code_5h_used_percent": 100.0,
|
||||
"command_code_5h_reset_at": future,
|
||||
"command_code_purchased_credits": 0.0,
|
||||
}
|
||||
require.NotEmpty(t, cnProviderThresholdCandidates(account, PlatformCommandCode))
|
||||
require.NotNil(t, cnProviderQuotaSnapshotReset(account, time.Now()))
|
||||
|
||||
account.Extra["command_code_purchased_credits"] = 12.5
|
||||
require.Empty(t, cnProviderThresholdCandidates(account, PlatformCommandCode))
|
||||
require.Nil(t, cnProviderQuotaSnapshotReset(account, time.Now()))
|
||||
}
|
||||
|
||||
// commandCodeCheckRepo 按平台列出账号,并记录周期检测对账号的停调。
|
||||
type commandCodeCheckRepo struct {
|
||||
AccountRepository
|
||||
accounts []Account
|
||||
mu sync.Mutex
|
||||
paused []int64
|
||||
}
|
||||
|
||||
func (r *commandCodeCheckRepo) ListByPlatform(_ context.Context, platform string) ([]Account, error) {
|
||||
var accounts []Account
|
||||
for _, account := range r.accounts {
|
||||
if account.Platform == platform {
|
||||
accounts = append(accounts, account)
|
||||
}
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
func (r *commandCodeCheckRepo) SetTempUnschedulable(_ context.Context, id int64, _ time.Time, _ string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.paused = append(r.paused, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
type commandCodeBalanceProber struct {
|
||||
mu sync.Mutex
|
||||
probed []int64
|
||||
balance float64
|
||||
}
|
||||
|
||||
func (p *commandCodeBalanceProber) QueryUsage(_ context.Context, accountID int64) (*CNProviderQuotaProbeResult, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.probed = append(p.probed, accountID)
|
||||
return &CNProviderQuotaProbeResult{
|
||||
Success: true,
|
||||
Balance: &CNProviderBalanceResult{Success: true, Balance: p.balance, Currency: "USD", Available: true},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func TestCNProviderBalanceCheckRunOnceProbesCommandCode(t *testing.T) {
|
||||
official := *commandCodeUsageAccount()
|
||||
official.ID, official.Schedulable = 1, true
|
||||
manualOff := *commandCodeUsageAccount()
|
||||
manualOff.ID, manualOff.Schedulable = 2, false
|
||||
relay := *commandCodeTestAccount(3)
|
||||
relay.Schedulable = true
|
||||
relay.Credentials = map[string]any{"api_key": "k", "api_protocol": APIProtocolChatCompletions, "base_url": "https://relay.example.com/v1"}
|
||||
inactive := *commandCodeUsageAccount()
|
||||
inactive.ID, inactive.Status = 4, StatusDisabled
|
||||
|
||||
repo := &commandCodeCheckRepo{accounts: []Account{official, manualOff, relay, inactive}}
|
||||
prober := &commandCodeBalanceProber{balance: 0.2}
|
||||
cfg := &config.Config{}
|
||||
cfg.Gateway.CNProviders.BalanceThreshold = 0.5
|
||||
svc := &CNProviderBalanceCheckService{accountRepo: repo, quotaService: prober, cfg: cfg}
|
||||
|
||||
svc.runOnce()
|
||||
|
||||
require.ElementsMatch(t, []int64{1, 2}, prober.probed)
|
||||
require.Equal(t, []int64{1}, repo.paused)
|
||||
}
|
||||
|
||||
// 积分不足(402)是可恢复状态:临时停调并标记 balance_low,不能永久置 error。
|
||||
func TestHandleUpstreamError_CommandCode402PausesInsteadOfError(t *testing.T) {
|
||||
repo := &rateLimitAccountRepoStub{}
|
||||
service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
|
||||
account := commandCodeUsageAccount()
|
||||
|
||||
shouldDisable := service.HandleUpstreamError(context.Background(), account, http.StatusPaymentRequired,
|
||||
http.Header{}, []byte(`{"error":{"message":"Insufficient credits"}}`))
|
||||
|
||||
require.True(t, shouldDisable)
|
||||
require.Equal(t, 0, repo.setErrorCalls)
|
||||
require.Equal(t, 1, repo.tempCalls)
|
||||
require.Contains(t, repo.lastTempReason, cnBalanceLowReasonPrefix)
|
||||
require.Equal(t, true, repo.lastExtraUpdates["command_code_balance_low"])
|
||||
}
|
||||
|
||||
func TestHandleUpstreamError_CommandCode429InsufficientBalancePauses(t *testing.T) {
|
||||
repo := &rateLimitAccountRepoStub{}
|
||||
service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
|
||||
account := commandCodeUsageAccount()
|
||||
|
||||
service.HandleUpstreamError(context.Background(), account, http.StatusTooManyRequests,
|
||||
http.Header{}, []byte(`{"error":{"type":"insufficient_credits","message":"no credits left"}}`))
|
||||
|
||||
require.Equal(t, 0, repo.setErrorCalls)
|
||||
require.Equal(t, 1, repo.tempCalls)
|
||||
require.Contains(t, repo.lastTempReason, cnBalanceLowReasonPrefix)
|
||||
require.Equal(t, 0, repo.rateLimitedCalls)
|
||||
}
|
||||
|
||||
// commandCodeRateLimitRepo 记录 Command Code 响应式处理写入的临时停调与模型级限流。
|
||||
type commandCodeRateLimitRepo struct {
|
||||
rateLimitAccountRepoStub
|
||||
tempUntil time.Time
|
||||
modelLimits map[string]time.Time
|
||||
reasons map[string]string
|
||||
}
|
||||
|
||||
func (r *commandCodeRateLimitRepo) SetTempUnschedulable(ctx context.Context, id int64, until time.Time, reason string) error {
|
||||
r.tempUntil = until
|
||||
return r.rateLimitAccountRepoStub.SetTempUnschedulable(ctx, id, until, reason)
|
||||
}
|
||||
|
||||
func (r *commandCodeRateLimitRepo) SetModelRateLimit(_ context.Context, _ int64, scope string, resetAt time.Time, reason ...string) error {
|
||||
if r.modelLimits == nil {
|
||||
r.modelLimits = map[string]time.Time{}
|
||||
r.reasons = map[string]string{}
|
||||
}
|
||||
r.modelLimits[scope] = resetAt
|
||||
if len(reason) > 0 {
|
||||
r.reasons[scope] = reason[0]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 窗口用满:按文案中的重置时间写带原因的临时停调(充值后可据原因解除),不依赖额度快照。
|
||||
func TestHandleUpstreamError_CommandCodeWindowLimitCoolsDownToMessageReset(t *testing.T) {
|
||||
for _, status := range []int{http.StatusTooManyRequests, http.StatusForbidden, http.StatusPaymentRequired} {
|
||||
repo := &commandCodeRateLimitRepo{}
|
||||
service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
|
||||
account := commandCodeUsageAccount()
|
||||
|
||||
shouldDisable := service.HandleUpstreamError(context.Background(), account, status, http.Header{},
|
||||
[]byte(`{"error":{"type":"usage_exceeded","message":"You've reached your 5-hour usage limit. Resets in 2h 41m (3:00 PM)."}}`))
|
||||
|
||||
require.Equal(t, status != http.StatusTooManyRequests, shouldDisable, status)
|
||||
require.Equal(t, 0, repo.setErrorCalls, status)
|
||||
require.Equal(t, 0, repo.rateLimitedCalls, status)
|
||||
require.Equal(t, 1, repo.tempCalls, status)
|
||||
require.True(t, strings.HasPrefix(repo.lastTempReason, commandCodeUsageLimitReason+": "), repo.lastTempReason)
|
||||
expected := time.Now().Add(2*time.Hour + 41*time.Minute)
|
||||
require.WithinDuration(t, expected, repo.tempUntil, time.Minute, status)
|
||||
}
|
||||
}
|
||||
|
||||
// 文案没有重置时间时回落额度快照中最早的窗口重置点。
|
||||
func TestHandleUpstreamError_CommandCodeWindowLimitFallsBackToSnapshot(t *testing.T) {
|
||||
repo := &commandCodeRateLimitRepo{}
|
||||
service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
|
||||
account := commandCodeUsageAccount()
|
||||
account.Extra = map[string]any{
|
||||
"command_code_5h_used_percent": 100.0,
|
||||
"command_code_5h_reset_at": time.Now().Add(90 * time.Minute).UTC().Format(time.RFC3339),
|
||||
"command_code_purchased_credits": 0.0,
|
||||
}
|
||||
|
||||
service.HandleUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{},
|
||||
[]byte(`{"error":{"message":"You've reached your weekly usage limit."}}`))
|
||||
|
||||
require.Equal(t, 1, repo.tempCalls)
|
||||
require.WithinDuration(t, time.Now().Add(90*time.Minute), repo.tempUntil, time.Minute)
|
||||
}
|
||||
|
||||
// 普通频率限制很快恢复:即使快照里有窗口重置点,也不冷却到窗口重置。
|
||||
func TestHandleUpstreamError_CommandCodeRateLimitUsesDefaultCooldown(t *testing.T) {
|
||||
repo := &commandCodeRateLimitRepo{}
|
||||
service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
|
||||
account := commandCodeUsageAccount()
|
||||
account.Extra = map[string]any{
|
||||
"command_code_5h_used_percent": 97.0,
|
||||
"command_code_5h_reset_at": time.Now().Add(4 * time.Hour).UTC().Format(time.RFC3339),
|
||||
"command_code_purchased_credits": 0.0,
|
||||
}
|
||||
|
||||
service.HandleUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{},
|
||||
[]byte(`{"error":{"type":"rate_limit","message":"Rate limit exceeded. Please wait a moment and try again."}}`))
|
||||
|
||||
require.Equal(t, 0, repo.setErrorCalls)
|
||||
require.Equal(t, 0, repo.tempCalls)
|
||||
if repo.rateLimitedCalls > 0 {
|
||||
require.True(t, repo.lastRateLimitedAt.Before(time.Now().Add(30*time.Minute)), "must not cool down to the 5h window reset")
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
commandCodeSpendLimitBody = `{"error":{"type":"usage_exceeded","message":"You've reached the $10.00/mo spending limit your organization set for GLM-5. It resets in 3 days."}}`
|
||||
commandCodeMemberSpendLimitBody = `{"error":{"type":"usage_exceeded","message":"You've reached the $50.00/mo spending limit your organization set. It resets in 12 days."}}`
|
||||
)
|
||||
|
||||
// 组织为某个模型设的花费上限只限当前模型:写模型级限流到文案中的重置时间,不停整个账号。
|
||||
func TestHandleUpstreamError_CommandCodeSpendLimitIsModelScoped(t *testing.T) {
|
||||
repo := &commandCodeRateLimitRepo{}
|
||||
service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
|
||||
account := commandCodeUsageAccount()
|
||||
ctx := withTempUnschedulableModel(context.Background(), []string{"glm-5"})
|
||||
|
||||
shouldDisable := service.HandleUpstreamError(ctx, account, http.StatusForbidden, http.Header{}, []byte(commandCodeSpendLimitBody))
|
||||
|
||||
require.False(t, shouldDisable)
|
||||
require.Equal(t, 0, repo.setErrorCalls)
|
||||
require.Equal(t, 0, repo.tempCalls)
|
||||
require.Equal(t, 0, repo.rateLimitedCalls)
|
||||
require.Contains(t, repo.modelLimits, "glm-5")
|
||||
require.WithinDuration(t, time.Now().Add(72*time.Hour), repo.modelLimits["glm-5"], time.Minute)
|
||||
require.Equal(t, commandCodeSpendLimitReason, repo.reasons["glm-5"])
|
||||
}
|
||||
|
||||
// 成员总额度耗尽:即使请求模型已知也按账号冷却,但最长一小时(管理员可能调高上限)。
|
||||
func TestHandleUpstreamError_CommandCodeMemberSpendLimitIsAccountScoped(t *testing.T) {
|
||||
repo := &commandCodeRateLimitRepo{}
|
||||
service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
|
||||
account := commandCodeUsageAccount()
|
||||
ctx := withTempUnschedulableModel(context.Background(), []string{"glm-5"})
|
||||
|
||||
shouldDisable := service.HandleUpstreamError(ctx, account, http.StatusForbidden, http.Header{}, []byte(commandCodeMemberSpendLimitBody))
|
||||
|
||||
require.True(t, shouldDisable)
|
||||
require.Empty(t, repo.modelLimits)
|
||||
require.Equal(t, 0, repo.setErrorCalls)
|
||||
require.Equal(t, 1, repo.tempCalls)
|
||||
require.Equal(t, commandCodeSpendLimitReason, repo.lastTempReason)
|
||||
require.WithinDuration(t, time.Now().Add(commandCodeAccountSpendLimitRecheck), repo.tempUntil, time.Minute)
|
||||
|
||||
// 文案中的重置时间早于一小时时以文案为准。
|
||||
soon := &commandCodeRateLimitRepo{}
|
||||
NewRateLimitService(soon, nil, &config.Config{}, nil, nil).HandleUpstreamError(ctx, account, http.StatusTooManyRequests, http.Header{},
|
||||
[]byte(`{"error":{"message":"You've reached the $50.00/mo spending limit your organization set. It resets in 20 minutes."}}`))
|
||||
require.WithinDuration(t, time.Now().Add(20*time.Minute), soon.tempUntil, time.Minute)
|
||||
}
|
||||
|
||||
// 不知道模型时按账号冷却(最长一小时),不停账号数天,也不进入 403 累计禁用。
|
||||
func TestHandleUpstreamError_CommandCodeSpendLimitWithoutModelShortCooldown(t *testing.T) {
|
||||
repo := &commandCodeRateLimitRepo{}
|
||||
service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
|
||||
account := commandCodeUsageAccount()
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
service.HandleUpstreamError(context.Background(), account, http.StatusForbidden, http.Header{}, []byte(commandCodeSpendLimitBody))
|
||||
}
|
||||
|
||||
require.Equal(t, 0, repo.setErrorCalls)
|
||||
require.Empty(t, repo.modelLimits)
|
||||
require.Equal(t, 5, repo.tempCalls)
|
||||
require.False(t, repo.tempUntil.After(time.Now().Add(commandCodeAccountSpendLimitRecheck)))
|
||||
}
|
||||
|
||||
func TestCommandCodeSpendLimitScope(t *testing.T) {
|
||||
require.True(t, commandCodeSpendLimitIsModelScoped([]byte(commandCodeSpendLimitBody)))
|
||||
require.True(t, commandCodeSpendLimitIsModelScoped([]byte(`spending limit your organization set for gpt-5.5. It resets in 2 days.`)))
|
||||
require.False(t, commandCodeSpendLimitIsModelScoped([]byte(commandCodeMemberSpendLimitBody)))
|
||||
require.False(t, commandCodeSpendLimitIsModelScoped([]byte(`You've reached the $50.00/mo spending limit your organization set for you.`)))
|
||||
require.False(t, commandCodeSpendLimitIsModelScoped([]byte(`spending limit reached`)))
|
||||
}
|
||||
|
||||
// commandCodeStatefulRepo 把停调写回同一个账号对象,用于验证完整的状态转换。
|
||||
type commandCodeStatefulRepo struct {
|
||||
AccountRepository
|
||||
account *Account
|
||||
clearCalls int
|
||||
}
|
||||
|
||||
func (r *commandCodeStatefulRepo) GetByID(_ context.Context, _ int64) (*Account, error) {
|
||||
clone := *r.account
|
||||
return &clone, nil
|
||||
}
|
||||
|
||||
func (r *commandCodeStatefulRepo) UpdateExtra(_ context.Context, _ int64, _ map[string]any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *commandCodeStatefulRepo) SetTempUnschedulable(_ context.Context, _ int64, until time.Time, reason string) error {
|
||||
r.account.TempUnschedulableUntil = &until
|
||||
r.account.TempUnschedulableReason = reason
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *commandCodeStatefulRepo) ClearTempUnschedulable(_ context.Context, _ int64) error {
|
||||
r.clearCalls++
|
||||
r.account.TempUnschedulableUntil = nil
|
||||
r.account.TempUnschedulableReason = ""
|
||||
return nil
|
||||
}
|
||||
|
||||
func commandCodeCreditsBody(purchased float64) string {
|
||||
return fmt.Sprintf(`{"credits":{"monthlyCredits":0,"purchasedCredits":%g,"freeCredits":0},
|
||||
"windowLimits":{"limited":true,"fiveHour":{"used":14,"cap":14,"resetAt":1790000000000}}}`, purchased)
|
||||
}
|
||||
|
||||
// 窗口用满进入冷却 → 充值 → 下一次额度探测发现充值积分 → 恢复可调度。
|
||||
func TestCommandCodeWindowCooldownClearedAfterTopUp(t *testing.T) {
|
||||
account := commandCodeUsageAccount()
|
||||
account.Schedulable = true
|
||||
repo := &commandCodeStatefulRepo{account: account}
|
||||
rateLimit := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
|
||||
|
||||
rateLimit.HandleUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{},
|
||||
[]byte(`{"error":{"message":"You've reached your 5-hour usage limit. Resets in 3h 10m."}}`))
|
||||
require.False(t, account.IsSchedulable())
|
||||
|
||||
// 未充值:探测不解除冷却。
|
||||
upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
|
||||
upstream.responses["/alpha/billing/credits"] = commandCodeAlphaResponse{status: http.StatusOK, body: commandCodeCreditsBody(0)}
|
||||
quota := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{})
|
||||
_, err := quota.QueryUsage(context.Background(), account.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, repo.clearCalls)
|
||||
require.False(t, account.IsSchedulable())
|
||||
|
||||
// 充值后:额度探测与余额探测都能解除窗口冷却。
|
||||
upstream.responses["/alpha/billing/credits"] = commandCodeAlphaResponse{status: http.StatusOK, body: commandCodeCreditsBody(20)}
|
||||
_, err = quota.QueryUsage(context.Background(), account.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, repo.clearCalls)
|
||||
require.True(t, account.IsSchedulable())
|
||||
|
||||
rateLimit.HandleUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{},
|
||||
[]byte(`{"error":{"message":"You've reached your weekly usage limit. Resets in 2 days."}}`))
|
||||
require.False(t, account.IsSchedulable())
|
||||
_, err = NewCNProviderBalanceService(repo, nil, upstream, &config.Config{}).QueryBalance(context.Background(), account.ID)
|
||||
require.NoError(t, err)
|
||||
require.True(t, account.IsSchedulable())
|
||||
}
|
||||
|
||||
// 充值积分只解除窗口冷却:积分不足、花费上限等其他原因的停调保持不变。
|
||||
func TestCommandCodeTopUpKeepsOtherCooldowns(t *testing.T) {
|
||||
for _, reason := range []string{cnBalanceLowReason("no credits"), commandCodeSpendLimitReason, "manual rule"} {
|
||||
until := time.Now().Add(time.Hour)
|
||||
account := commandCodeUsageAccount()
|
||||
account.Schedulable = true
|
||||
account.TempUnschedulableUntil = &until
|
||||
account.TempUnschedulableReason = reason
|
||||
repo := &commandCodeStatefulRepo{account: account}
|
||||
upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
|
||||
upstream.responses["/alpha/billing/credits"] = commandCodeAlphaResponse{status: http.StatusOK, body: commandCodeCreditsBody(20)}
|
||||
|
||||
_, err := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{}).QueryUsage(context.Background(), account.ID)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, repo.clearCalls, reason)
|
||||
require.False(t, account.IsSchedulable(), reason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyCommandCodeUsageError(t *testing.T) {
|
||||
cases := map[string]commandCodeUsageErrorKind{
|
||||
`{"error":{"message":"You've reached your 5-hour usage limit. Resets in 2h 41m (3:00 PM)."}}`: commandCodeUsageWindowLimit,
|
||||
`{"error":{"message":"You've reached your weekly usage limit."}}`: commandCodeUsageWindowLimit,
|
||||
commandCodeSpendLimitBody: commandCodeUsageSpendLimit,
|
||||
`{"error":{"type":"usage_exceeded","message":"Monthly credits spent."}}`: commandCodeUsageCreditsExhausted,
|
||||
`{"error":{"message":"Insufficient credits"}}`: commandCodeUsageCreditsExhausted,
|
||||
`{"error":{"type":"rate_limit","message":"Rate limit exceeded. Please wait a moment."}}`: commandCodeUsageErrorNone,
|
||||
`{"error":{"message":"forbidden"}}`: commandCodeUsageErrorNone,
|
||||
}
|
||||
for body, want := range cases {
|
||||
require.Equal(t, want, classifyCommandCodeUsageError([]byte(body)), body)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
)
|
||||
|
||||
@@ -289,11 +290,5 @@ func (s *GatewayService) resolveCompositeRouteDecision(ctx context.Context, grou
|
||||
}
|
||||
|
||||
func isConcreteRequestPlatform(platform string) bool {
|
||||
switch platform {
|
||||
case PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return domain.IsConcretePlatform(platform)
|
||||
}
|
||||
@@ -269,13 +269,13 @@ func TestCompositeGroupSchedulerHasAllCanonicalPlatformBuckets(t *testing.T) {
|
||||
platforms = append(platforms, platform)
|
||||
}
|
||||
require.ElementsMatch(t,
|
||||
[]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud},
|
||||
[]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformCommandCode, PlatformCline, PlatformOllamaCloud},
|
||||
platforms,
|
||||
)
|
||||
}
|
||||
|
||||
func TestCompositeConcretePlatformsIncludeCNProviders(t *testing.T) {
|
||||
for _, platform := range []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe} {
|
||||
for _, platform := range []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformCommandCode, PlatformCline} {
|
||||
require.True(t, isConcreteRequestPlatform(platform))
|
||||
require.True(t, canCopyAccountsFromGroupPlatform(PlatformComposite, platform))
|
||||
}
|
||||
|
||||
@@ -44,12 +44,14 @@ const (
|
||||
PlatformAntigravity = domain.PlatformAntigravity
|
||||
PlatformGrok = domain.PlatformGrok
|
||||
// 国产 OpenAI 兼容供应商(与 grok 一样经 OpenAI 网关转发)。
|
||||
PlatformKimi = domain.PlatformKimi
|
||||
PlatformZhipu = domain.PlatformZhipu
|
||||
PlatformDeepseek = domain.PlatformDeepseek
|
||||
PlatformMiniMax = domain.PlatformMiniMax
|
||||
PlatformTypeSafe = domain.PlatformTypeSafe
|
||||
PlatformOpenCodeGo = domain.PlatformOpenCodeGo
|
||||
PlatformKimi = domain.PlatformKimi
|
||||
PlatformZhipu = domain.PlatformZhipu
|
||||
PlatformDeepseek = domain.PlatformDeepseek
|
||||
PlatformMiniMax = domain.PlatformMiniMax
|
||||
PlatformOpenCodeGo = domain.PlatformOpenCodeGo
|
||||
PlatformTypeSafe = domain.PlatformTypeSafe
|
||||
PlatformCommandCode = domain.PlatformCommandCode
|
||||
PlatformCline = domain.PlatformCline
|
||||
// PlatformOllamaCloud 是 Ollama Cloud 订阅制聚合上游。
|
||||
PlatformOllamaCloud = domain.PlatformOllamaCloud
|
||||
PlatformComposite = domain.PlatformComposite
|
||||
@@ -93,6 +95,10 @@ const (
|
||||
DefaultOpenCodeZenBaseURL = "https://opencode.ai/zen/v1"
|
||||
// Ollama Cloud:Chat Completions / Responses 共用带 /v1 的基址。
|
||||
DefaultOllamaCloudBaseURL = "https://ollama.com/v1"
|
||||
// Command Code Provider API:Chat Completions / Responses / models 共用 /provider/v1 基址。
|
||||
DefaultCommandCodeBaseURL = "https://api.commandcode.ai/provider/v1"
|
||||
// Cline API:只提供 Chat Completions({base}/chat/completions)与模型列表。
|
||||
DefaultClineBaseURL = "https://api.cline.bot/api/v1"
|
||||
)
|
||||
|
||||
// 国产供应商 Anthropic 协议端点的默认 base_url(上游路径为 {base}/v1/messages)。
|
||||
@@ -108,16 +114,14 @@ const (
|
||||
DefaultOpenCodeZenAnthropicBaseURL = "https://opencode.ai/zen"
|
||||
// Ollama Cloud Anthropic 基址不含 /v1:nativeAnthropicTargetURL 会再拼 /v1/messages。
|
||||
DefaultOllamaCloudAnthropicBaseURL = "https://ollama.com"
|
||||
// Command Code 的 Anthropic 端点为 /provider/v1/messages(Claude 系模型只在此端点提供)。
|
||||
DefaultCommandCodeAnthropicBaseURL = "https://api.commandcode.ai/provider"
|
||||
)
|
||||
|
||||
// IsCNProvider 报告 platform 是否为国产 OpenAI 兼容供应商(kimi/zhipu/deepseek/minimax)。
|
||||
// IsCNProvider 报告 platform 是否为国产 OpenAI 兼容供应商(kimi/zhipu/deepseek/minimax),
|
||||
// 以平台清单(domain/platforms.go)为准。
|
||||
func IsCNProvider(platform string) bool {
|
||||
switch platform {
|
||||
case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return domain.IsCNProviderPlatform(platform)
|
||||
}
|
||||
|
||||
// IsOpenCodeGo 报告 platform 是否为 OpenCode Go 订阅网关。
|
||||
@@ -131,32 +135,20 @@ func IsOllamaCloud(platform string) bool {
|
||||
}
|
||||
|
||||
// IsMultiProtocolAPIKeyProvider 报告 platform 是否为多协议 API Key 网关
|
||||
// (国产供应商 + OpenCode + Ollama Cloud):走 OpenAI 网关、支持 adaptive 协议分流。
|
||||
// (国产供应商 + OpenCode):走 OpenAI 网关、支持 adaptive 协议分流。
|
||||
// 归属以 provider profile 登记为准(见 provider_profile.go)。
|
||||
func IsMultiProtocolAPIKeyProvider(platform string) bool {
|
||||
return IsCNProvider(platform) || platform == PlatformOpenCodeGo || IsOllamaCloud(platform)
|
||||
return LookupProviderProfile(platform) != nil
|
||||
}
|
||||
|
||||
// AllowedQuotaPlatforms 是允许设置 user × platform quota 的平台列表(单一权威来源)。
|
||||
// ent/schema/user_platform_quota.go 的 Validate 函数独立维护(构建期约束),
|
||||
// 若新增平台需同步修改该 schema。
|
||||
var AllowedQuotaPlatforms = []string{
|
||||
PlatformAnthropic,
|
||||
PlatformOpenAI,
|
||||
PlatformGemini,
|
||||
PlatformAntigravity,
|
||||
PlatformGrok,
|
||||
PlatformKimi,
|
||||
PlatformZhipu,
|
||||
PlatformDeepseek,
|
||||
PlatformMiniMax,
|
||||
PlatformOpenCodeGo,
|
||||
PlatformTypeSafe,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
// AllowedQuotaPlatforms 是允许设置 user × platform quota 的平台列表:全部已登记的
|
||||
// 具体平台(domain/platforms.go),ent/schema/user_platform_quota.go 的校验同源。
|
||||
var AllowedQuotaPlatforms = domain.ConcretePlatformIDs()
|
||||
|
||||
// AllowedSchedulingThresholdPlatforms 是允许设置账号自动停调阈值的平台列表。
|
||||
// openai/anthropic/grok 有原生用量窗口;kimi/zhipu/minimax 的 Coding Plan 同样暴露
|
||||
// 5h/weekly 滚动窗口,纳入阈值评估。deepseek 为余额型,走余额检测而非阈值。
|
||||
// OpenCode Go 与 Command Code 的订阅套餐另有月度窗口。
|
||||
// ollama_cloud 仅 legacy 账号有 5h/7d 滚动窗口可等 reset;credits 型是月度美元
|
||||
// 信用池、没有窗口 reset,评估器候选恒空(见 ollamaCloudThresholdCandidates)。
|
||||
var AllowedSchedulingThresholdPlatforms = []string{
|
||||
@@ -167,6 +159,7 @@ var AllowedSchedulingThresholdPlatforms = []string{
|
||||
PlatformZhipu,
|
||||
PlatformMiniMax,
|
||||
PlatformOpenCodeGo,
|
||||
PlatformCommandCode,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"unsafe"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
|
||||
"github.com/Wei-Shaw/sub2api/internal/util/responseheaders"
|
||||
@@ -1491,14 +1492,10 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64,
|
||||
|
||||
// compositeOwnershipQueryPlatforms 返回 ownership 候选扫描的平台全集。
|
||||
// ListModelAvailabilityCandidates 要求显式传入平台列表(空列表返回空结果),
|
||||
// 这里传入全部可承接请求的具体平台,与旧 ListSchedulableByGroupID 的扫描范围
|
||||
// 保持一致,组隔离由该查询的 groupID 维度保证。
|
||||
// 这里传入全部可承接请求的具体平台(平台清单),与旧 ListSchedulableByGroupID 的
|
||||
// 扫描范围保持一致,组隔离由该查询的 groupID 维度保证。
|
||||
func compositeOwnershipQueryPlatforms() []string {
|
||||
return []string{
|
||||
PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo,
|
||||
PlatformTypeSafe, PlatformOllamaCloud,
|
||||
}
|
||||
return domain.ConcretePlatformIDs()
|
||||
}
|
||||
|
||||
// resolveCompositeModelOwnership 基于持久化配置判断一个公开模型由组内哪些平台
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// 上游模型目录中的协议能力。部分聚合平台(Command Code)在 {Chat Completions 基址}/models
|
||||
// 的每个模型上给出 supported_endpoints,例如:
|
||||
//
|
||||
// {"id":"deepseek/deepseek-v4-flash","supported_endpoints":["/chat/completions","/responses"]}
|
||||
// {"id":"claude-sonnet-4-6","supported_endpoints":["/messages"]}
|
||||
//
|
||||
// 按模型分流时据此判断模型是否支持入站协议:支持就同协议直通,省去一次协议转换
|
||||
// (见 modelProtocolSet)。
|
||||
//
|
||||
// 缓存范围:所有目录均按账号和地址隔离,包括官方默认地址。目录可能随 Key、租户
|
||||
// 或请求头不同,鉴权失败的刷新退避也不能影响其他账号(见 modelProtocolCatalogKey)。
|
||||
//
|
||||
// 刷新在后台进行:过期时继续使用旧目录。目录从未加载成功时,首批请求最多等待
|
||||
// modelProtocolCatalogFirstLoadWait,各请求共用本轮刷新开始时的截止时间,并响应请求
|
||||
// 取消。超时后同一轮刷新中的后续请求立即回落内置规则,失败退避期内不再等待。
|
||||
|
||||
const (
|
||||
modelProtocolCatalogTTL = 30 * time.Minute
|
||||
modelProtocolCatalogRetryBackoff = 5 * time.Minute
|
||||
modelProtocolCatalogTimeout = 15 * time.Second
|
||||
modelProtocolCatalogFirstLoadWait = 2 * time.Second
|
||||
modelProtocolCatalogMaxBodyBytes = 2 << 20
|
||||
)
|
||||
|
||||
type modelProtocolCatalogEntry struct {
|
||||
// models 以小写模型 ID 为键,值为上游声明的协议(保持上游顺序)。
|
||||
models map[string][]string
|
||||
fetchedAt time.Time
|
||||
retryAt time.Time
|
||||
refreshing bool
|
||||
// done 在进行中的刷新结束时关闭。
|
||||
done chan struct{}
|
||||
// firstLoadDeadline 是本轮冷启动刷新共享的等待截止时间。
|
||||
firstLoadDeadline time.Time
|
||||
}
|
||||
|
||||
type modelProtocolCatalog struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]*modelProtocolCatalogEntry
|
||||
}
|
||||
|
||||
// upstreamModelProtocols 是全进程共享的模型协议目录。
|
||||
var upstreamModelProtocols modelProtocolCatalog
|
||||
|
||||
func (c *modelProtocolCatalog) entryLocked(key string) *modelProtocolCatalogEntry {
|
||||
if c.entries == nil {
|
||||
c.entries = make(map[string]*modelProtocolCatalogEntry)
|
||||
}
|
||||
entry := c.entries[key]
|
||||
if entry == nil {
|
||||
entry = &modelProtocolCatalogEntry{}
|
||||
c.entries[key] = entry
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
// lookup 返回 key 目录中 model 支持的协议;目录尚未就绪或模型不在目录中时返回 nil。
|
||||
// 目录缺失或过期、且不在刷新中也不在失败退避期时,异步调用 refresh(由其调用 store);
|
||||
// 目录从未加载成功且刷新进行中时,只等待本轮冷启动窗口的剩余时间。
|
||||
func (c *modelProtocolCatalog) lookup(ctx context.Context, key, model string, now time.Time, refresh func()) []string {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
entry := c.entryLocked(key)
|
||||
stale := entry.models == nil || now.Sub(entry.fetchedAt) >= modelProtocolCatalogTTL
|
||||
if stale && !entry.refreshing && !now.Before(entry.retryAt) && refresh != nil {
|
||||
entry.refreshing = true
|
||||
entry.done = make(chan struct{})
|
||||
if entry.models == nil {
|
||||
entry.firstLoadDeadline = now.Add(modelProtocolCatalogFirstLoadWait)
|
||||
}
|
||||
go refresh()
|
||||
}
|
||||
if entry.models == nil && entry.refreshing && now.Before(entry.firstLoadDeadline) {
|
||||
done := entry.done
|
||||
deadline := entry.firstLoadDeadline
|
||||
c.mu.Unlock()
|
||||
timer := time.NewTimer(time.Until(deadline))
|
||||
select {
|
||||
case <-done:
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
timer.Stop()
|
||||
c.mu.Lock()
|
||||
}
|
||||
if entry.models == nil || ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return entry.models[strings.ToLower(strings.TrimSpace(model))]
|
||||
}
|
||||
|
||||
// store 写入一次刷新的结果;失败时保留旧目录并进入退避。
|
||||
func (c *modelProtocolCatalog) store(key string, models map[string][]string, err error, now time.Time) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
entry := c.entryLocked(key)
|
||||
entry.refreshing = false
|
||||
if entry.done != nil {
|
||||
close(entry.done)
|
||||
entry.done = nil
|
||||
}
|
||||
if err != nil {
|
||||
entry.retryAt = now.Add(modelProtocolCatalogRetryBackoff)
|
||||
return
|
||||
}
|
||||
entry.models = models
|
||||
entry.fetchedAt = now
|
||||
entry.retryAt = time.Time{}
|
||||
}
|
||||
|
||||
// modelEndpointProtocol 把 supported_endpoints 中的端点路径映射为上游协议。
|
||||
func modelEndpointProtocol(endpoint string) string {
|
||||
endpoint = strings.ToLower(strings.TrimRight(strings.TrimSpace(endpoint), "/"))
|
||||
switch {
|
||||
case strings.HasSuffix(endpoint, "/chat/completions"):
|
||||
return APIProtocolChatCompletions
|
||||
case strings.HasSuffix(endpoint, "/responses"):
|
||||
return APIProtocolResponses
|
||||
case strings.HasSuffix(endpoint, "/messages"):
|
||||
return APIProtocolAnthropic
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// parseModelProtocolCatalog 解析 /models 响应;没有任何模型带可识别的 supported_endpoints
|
||||
// 时返回错误(上游不提供该字段,或是中转站的普通 /models)。
|
||||
func parseModelProtocolCatalog(body []byte) (map[string][]string, error) {
|
||||
entries, err := extractUpstreamModelRawEntries(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
models := make(map[string][]string)
|
||||
for _, raw := range entries {
|
||||
id := strings.ToLower(strings.TrimSpace(gjson.GetBytes(raw, "id").String()))
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
var protocols []string
|
||||
for _, endpoint := range gjson.GetBytes(raw, "supported_endpoints").Array() {
|
||||
protocol := modelEndpointProtocol(endpoint.String())
|
||||
if protocol != "" && !slices.Contains(protocols, protocol) {
|
||||
protocols = append(protocols, protocol)
|
||||
}
|
||||
}
|
||||
if len(protocols) > 0 {
|
||||
models[id] = protocols
|
||||
}
|
||||
}
|
||||
if len(models) == 0 {
|
||||
return nil, fmt.Errorf("model list has no supported_endpoints")
|
||||
}
|
||||
return models, nil
|
||||
}
|
||||
|
||||
// modelCatalogProtocols 返回上游模型目录中 model 支持的协议;平台不提供目录、账号固定了
|
||||
// 上游协议或目录尚未就绪时返回 nil。
|
||||
func (s *OpenAIGatewayService) modelCatalogProtocols(ctx context.Context, account *Account, model string) []string {
|
||||
if s == nil || s.httpUpstream == nil || strings.TrimSpace(model) == "" || !account.routesByModel() {
|
||||
return nil
|
||||
}
|
||||
if profile := account.providerProfile(); profile == nil || !profile.ModelCatalog {
|
||||
return nil
|
||||
}
|
||||
if account.GetAPIProtocol() != APIProtocolAdaptive {
|
||||
return nil
|
||||
}
|
||||
base := strings.TrimSpace(account.GetCNProtocolBaseURL(APIProtocolChatCompletions))
|
||||
if base == "" {
|
||||
return nil
|
||||
}
|
||||
url := buildOpenAIModelsURL(base)
|
||||
key := modelProtocolCatalogKey(account, url)
|
||||
headers := modelProtocolCatalogHeaders(account, url)
|
||||
proxyURL := ""
|
||||
if account.ProxyID != nil && account.Proxy != nil {
|
||||
proxyURL = account.Proxy.URL()
|
||||
}
|
||||
accountID, concurrency := account.ID, account.Concurrency
|
||||
return upstreamModelProtocols.lookup(ctx, key, model, time.Now(), func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), modelProtocolCatalogTimeout)
|
||||
defer cancel()
|
||||
models, err := s.fetchModelProtocolCatalog(ctx, url, headers, proxyURL, accountID, concurrency)
|
||||
if err != nil {
|
||||
slog.Warn("model_protocol_catalog_refresh_failed", "account_id", accountID, "url", url, "error", err)
|
||||
} else {
|
||||
slog.Info("model_protocol_catalog_refreshed", "account_id", accountID, "url", url, "models", len(models))
|
||||
}
|
||||
upstreamModelProtocols.store(key, models, err, time.Now())
|
||||
})
|
||||
}
|
||||
|
||||
// modelProtocolCatalogKey 按账号和地址隔离目录及刷新退避,避免一个账号的目录或
|
||||
// 鉴权失败影响同地址的其他账号。
|
||||
func modelProtocolCatalogKey(account *Account, url string) string {
|
||||
return fmt.Sprintf("%s#account=%d", url, account.ID)
|
||||
}
|
||||
|
||||
// modelProtocolCatalogHeaders 构造目录请求头,UA 收敛与账号请求头覆写与转发一致
|
||||
// (见 buildUpstreamRequest)。在请求时构造,后台刷新不再读取账号。
|
||||
func modelProtocolCatalogHeaders(account *Account, url string) http.Header {
|
||||
headers := http.Header{}
|
||||
headers.Set("Accept", "application/json")
|
||||
if apiKey := strings.TrimSpace(account.GetOpenAIProtocolAPIKey()); apiKey != "" {
|
||||
headers.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
applyOpenCodeUpstreamUserAgent(account, url, headers)
|
||||
account.ApplyHeaderOverrides(headers)
|
||||
return headers
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) fetchModelProtocolCatalog(ctx context.Context, url string, headers http.Header, proxyURL string, accountID int64, concurrency int) (map[string][]string, error) {
|
||||
validatedURL, err := s.validateUpstreamBaseURL(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(WithHTTPUpstreamRedirectsDisabled(ctx), http.MethodGet, validatedURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header = headers.Clone()
|
||||
resp, err := s.httpUpstream.Do(req, proxyURL, accountID, maxInt(concurrency, 1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||
return nil, fmt.Errorf("model list returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, modelProtocolCatalogMaxBodyBytes+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(body) > modelProtocolCatalogMaxBodyBytes {
|
||||
return nil, fmt.Errorf("model list exceeds %d bytes", modelProtocolCatalogMaxBodyBytes)
|
||||
}
|
||||
return parseModelProtocolCatalog(body)
|
||||
}
|
||||
|
||||
// resolveUpstreamProtocolFor 是网关入口使用的 resolveUpstreamProtocol:按模型分流且平台
|
||||
// 提供模型目录时,带上目录中该模型支持的协议。
|
||||
func (s *OpenAIGatewayService) resolveUpstreamProtocolFor(ctx context.Context, account *Account, inbound, model string) string {
|
||||
return resolveUpstreamProtocol(account, inbound, model, s.modelCatalogProtocols(ctx, account, model))
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// 取自 https://api.commandcode.ai/provider/v1/models 的片段(2026-09-26)。
|
||||
const commandCodeModelsSample = `{"object":"list","data":[
|
||||
{"id":"claude-sonnet-4-6","supported_endpoints":["/messages"]},
|
||||
{"id":"gpt-5.5","supported_endpoints":["/chat/completions","/responses"]},
|
||||
{"id":"deepseek/deepseek-v4-flash","supported_endpoints":["/chat/completions","/responses"]},
|
||||
{"id":"deepseek/deepseek-v4-flash-fast","supported_endpoints":["/chat/completions"]},
|
||||
{"id":"zai-org/GLM-5.3","supported_endpoints":["/chat/completions","/responses"]},
|
||||
{"id":"typesafe/jev","supported_endpoints":["/systemone"]},
|
||||
{"id":"no-endpoints"}
|
||||
]}`
|
||||
|
||||
func TestParseModelProtocolCatalog(t *testing.T) {
|
||||
models, err := parseModelProtocolCatalog([]byte(commandCodeModelsSample))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, map[string][]string{
|
||||
"claude-sonnet-4-6": {APIProtocolAnthropic},
|
||||
"gpt-5.5": {APIProtocolChatCompletions, APIProtocolResponses},
|
||||
"deepseek/deepseek-v4-flash": {APIProtocolChatCompletions, APIProtocolResponses},
|
||||
"deepseek/deepseek-v4-flash-fast": {APIProtocolChatCompletions},
|
||||
"zai-org/glm-5.3": {APIProtocolChatCompletions, APIProtocolResponses},
|
||||
}, models)
|
||||
|
||||
_, err = parseModelProtocolCatalog([]byte(`{"data":[{"id":"gpt-5"},{"id":"glm-5"}]}`))
|
||||
require.Error(t, err, "a plain /models without supported_endpoints is not a protocol catalog")
|
||||
}
|
||||
|
||||
func TestModelProtocolCatalogLookupRefreshesInBackground(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
var catalog modelProtocolCatalog
|
||||
const key = "https://catalog.example/v1/models"
|
||||
now := time.Now()
|
||||
models, err := parseModelProtocolCatalog([]byte(commandCodeModelsSample))
|
||||
require.NoError(t, err)
|
||||
catalog.store(key, models, nil, now)
|
||||
var refreshes atomic.Int32
|
||||
refresh := func() { refreshes.Add(1) }
|
||||
|
||||
require.Equal(t, []string{APIProtocolChatCompletions, APIProtocolResponses}, catalog.lookup(t.Context(), key, "ZAI-ORG/GLM-5.3", now, refresh))
|
||||
require.Nil(t, catalog.lookup(t.Context(), key, "unknown-model", now, refresh))
|
||||
require.Zero(t, refreshes.Load())
|
||||
|
||||
// A stale catalog is returned immediately while one refresh runs in the background.
|
||||
time.Sleep(modelProtocolCatalogTTL) // synctest advances virtual time.
|
||||
later := time.Now()
|
||||
require.NotNil(t, catalog.lookup(t.Context(), key, "gpt-5.5", later, refresh))
|
||||
require.Equal(t, later, time.Now(), "a stale result must not wait for refresh")
|
||||
synctest.Wait()
|
||||
require.EqualValues(t, 1, refreshes.Load())
|
||||
require.NotNil(t, catalog.lookup(t.Context(), key, "gpt-5.5", later, refresh))
|
||||
require.EqualValues(t, 1, refreshes.Load(), "concurrent stale reads share one refresh")
|
||||
catalog.store(key, nil, errors.New("boom"), later)
|
||||
require.NotNil(t, catalog.lookup(t.Context(), key, "gpt-5.5", later.Add(time.Minute), refresh))
|
||||
require.EqualValues(t, 1, refreshes.Load(), "failure backoff preserves the old catalog")
|
||||
require.NotNil(t, catalog.lookup(t.Context(), key, "gpt-5.5", later.Add(modelProtocolCatalogRetryBackoff), refresh))
|
||||
synctest.Wait()
|
||||
require.EqualValues(t, 2, refreshes.Load())
|
||||
})
|
||||
}
|
||||
|
||||
func TestModelProtocolCatalogFirstLoadSharesWaitDeadline(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
var catalog modelProtocolCatalog
|
||||
const key = "https://catalog.example/v1/models"
|
||||
models := map[string][]string{"gpt-5.5": {APIProtocolResponses}}
|
||||
release := make(chan struct{})
|
||||
var refreshes atomic.Int32
|
||||
refresh := func() {
|
||||
refreshes.Add(1)
|
||||
<-release
|
||||
catalog.store(key, models, nil, time.Now())
|
||||
}
|
||||
type result struct {
|
||||
protocols []string
|
||||
elapsed time.Duration
|
||||
}
|
||||
first, second := make(chan result, 1), make(chan result, 1)
|
||||
lookup := func(done chan<- result) {
|
||||
start := time.Now()
|
||||
protocols := catalog.lookup(t.Context(), key, "gpt-5.5", start, refresh)
|
||||
done <- result{protocols, time.Since(start)}
|
||||
}
|
||||
start := time.Now()
|
||||
go lookup(first)
|
||||
synctest.Wait()
|
||||
time.Sleep(modelProtocolCatalogFirstLoadWait / 2) // Virtual time only.
|
||||
go lookup(second)
|
||||
synctest.Wait()
|
||||
time.Sleep(modelProtocolCatalogFirstLoadWait / 2)
|
||||
synctest.Wait()
|
||||
|
||||
r1, r2 := <-first, <-second
|
||||
require.Nil(t, r1.protocols)
|
||||
require.Nil(t, r2.protocols)
|
||||
require.Equal(t, modelProtocolCatalogFirstLoadWait, r1.elapsed)
|
||||
require.Equal(t, modelProtocolCatalogFirstLoadWait/2, r2.elapsed, "a later caller waits only for the remaining shared window")
|
||||
require.Equal(t, modelProtocolCatalogFirstLoadWait, time.Since(start))
|
||||
require.Nil(t, catalog.lookup(t.Context(), key, "gpt-5.5", time.Now(), refresh))
|
||||
require.Equal(t, modelProtocolCatalogFirstLoadWait, time.Since(start), "later calls fall back immediately while the same refresh continues")
|
||||
require.EqualValues(t, 1, refreshes.Load())
|
||||
|
||||
close(release)
|
||||
synctest.Wait()
|
||||
require.Equal(t, models["gpt-5.5"], catalog.lookup(t.Context(), key, "gpt-5.5", time.Now(), refresh), "a late successful refresh still populates the cache")
|
||||
})
|
||||
}
|
||||
|
||||
func TestModelProtocolCatalogFirstLoadWaitsForRefresh(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
const key = "https://catalog.example/v1/models"
|
||||
models, err := parseModelProtocolCatalog([]byte(commandCodeModelsSample))
|
||||
require.NoError(t, err)
|
||||
var loaded modelProtocolCatalog
|
||||
release := make(chan struct{})
|
||||
result := make(chan []string, 1)
|
||||
go func() {
|
||||
result <- loaded.lookup(t.Context(), key, "gpt-5.5", time.Now(), func() {
|
||||
<-release
|
||||
loaded.store(key, models, nil, time.Now())
|
||||
})
|
||||
}()
|
||||
synctest.Wait()
|
||||
close(release)
|
||||
synctest.Wait()
|
||||
require.Equal(t, []string{APIProtocolChatCompletions, APIProtocolResponses}, <-result)
|
||||
|
||||
var failing modelProtocolCatalog
|
||||
var refreshes atomic.Int32
|
||||
refresh := func() {
|
||||
refreshes.Add(1)
|
||||
failing.store(key, nil, errors.New("boom"), time.Now())
|
||||
}
|
||||
start := time.Now()
|
||||
require.Nil(t, failing.lookup(t.Context(), key, "gpt-5.5", start, refresh))
|
||||
require.Nil(t, failing.lookup(t.Context(), key, "gpt-5.5", start.Add(time.Minute), refresh))
|
||||
require.Equal(t, start, time.Now(), "a failed first load and its backoff must not hold requests")
|
||||
require.EqualValues(t, 1, refreshes.Load())
|
||||
})
|
||||
}
|
||||
|
||||
func TestModelProtocolCatalogFirstLoadWaitRespondsToCancellation(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
var catalog modelProtocolCatalog
|
||||
const key = "https://catalog.example/v1/models"
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
release := make(chan struct{})
|
||||
models := map[string][]string{"gpt-5.5": {APIProtocolResponses}}
|
||||
result := make(chan []string, 1)
|
||||
start := time.Now()
|
||||
go func() {
|
||||
result <- catalog.lookup(ctx, key, "gpt-5.5", start, func() {
|
||||
<-release
|
||||
catalog.store(key, models, nil, time.Now())
|
||||
})
|
||||
}()
|
||||
synctest.Wait()
|
||||
cancel()
|
||||
synctest.Wait()
|
||||
require.Nil(t, <-result)
|
||||
require.Equal(t, start, time.Now(), "cancellation releases the caller without waiting for the cold-start deadline")
|
||||
|
||||
// The caller's cancellation must not cancel the background refresh for future requests.
|
||||
close(release)
|
||||
synctest.Wait()
|
||||
require.Equal(t, models["gpt-5.5"], catalog.lookup(t.Context(), key, "gpt-5.5", time.Now(), nil))
|
||||
})
|
||||
}
|
||||
|
||||
// 官方默认地址和自定义上游均按账号隔离;请求头与转发一致。
|
||||
func TestModelProtocolCatalogKeyAndHeaders(t *testing.T) {
|
||||
official := commandCodeTestAccount(21)
|
||||
base := official.GetCNProtocolBaseURL(APIProtocolChatCompletions)
|
||||
url := buildOpenAIModelsURL(base)
|
||||
require.Equal(t, "https://api.commandcode.ai/provider/v1/models", url)
|
||||
require.Equal(t, url+"#account=21", modelProtocolCatalogKey(official, url))
|
||||
require.Equal(t, url+"#account=22", modelProtocolCatalogKey(commandCodeTestAccount(22), url))
|
||||
|
||||
headers := modelProtocolCatalogHeaders(official, url)
|
||||
require.Equal(t, "Bearer user_test_key", headers.Get("Authorization"))
|
||||
require.Equal(t, CodexCanonicalUserAgent(), headers.Get("User-Agent"), "official host gets the canonical UA like forwarding")
|
||||
|
||||
custom := commandCodeTestAccount(23)
|
||||
custom.Credentials["api_base_urls"] = map[string]any{APIProtocolChatCompletions: "https://relay.example/v1"}
|
||||
custom.Credentials["header_override_enabled"] = true
|
||||
custom.Credentials["header_overrides"] = map[string]any{"X-Tenant": "t-1"}
|
||||
customBase := custom.GetCNProtocolBaseURL(APIProtocolChatCompletions)
|
||||
customURL := buildOpenAIModelsURL(customBase)
|
||||
require.Equal(t, customURL+"#account=23", modelProtocolCatalogKey(custom, customURL))
|
||||
headers = modelProtocolCatalogHeaders(custom, customURL)
|
||||
require.Equal(t, "t-1", getHeaderRaw(headers, "x-tenant"))
|
||||
require.Empty(t, headers.Get("User-Agent"))
|
||||
}
|
||||
|
||||
type modelCatalogAccountUpstream struct {
|
||||
HTTPUpstream
|
||||
mu sync.Mutex
|
||||
requests []*http.Request
|
||||
failureStatus int
|
||||
failureErr error
|
||||
}
|
||||
|
||||
func (u *modelCatalogAccountUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
u.mu.Lock()
|
||||
u.requests = append(u.requests, req)
|
||||
u.mu.Unlock()
|
||||
if req.Header.Get("Authorization") == "Bearer invalid-key" {
|
||||
if u.failureErr != nil {
|
||||
return nil, u.failureErr
|
||||
}
|
||||
return newJSONResponse(u.failureStatus, `{"error":"invalid credentials"}`), nil
|
||||
}
|
||||
endpoint := "/chat/completions"
|
||||
if getHeaderRaw(req.Header, "x-tenant") == "responses-tenant" {
|
||||
endpoint = "/responses"
|
||||
}
|
||||
return newJSONResponse(http.StatusOK, fmt.Sprintf(`{"data":[{"id":"vendor/model","supported_endpoints":[%q]}]}`, endpoint)), nil
|
||||
}
|
||||
|
||||
func TestModelProtocolCatalogOfficialAccountsAreIsolated(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status int
|
||||
err error
|
||||
}{
|
||||
{name: "unauthorized", status: http.StatusUnauthorized},
|
||||
{name: "forbidden", status: http.StatusForbidden},
|
||||
{name: "transport", err: errors.New("upstream connection failed")},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
upstream := &modelCatalogAccountUpstream{failureStatus: tc.status, failureErr: tc.err}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
id := time.Now().UnixNano()
|
||||
bad, chat, responses := commandCodeTestAccount(id), commandCodeTestAccount(id+1), commandCodeTestAccount(id+2)
|
||||
bad.Credentials["api_key"] = "invalid-key"
|
||||
responses.Credentials["header_override_enabled"] = true
|
||||
responses.Credentials["header_overrides"] = map[string]any{"X-Tenant": "responses-tenant"}
|
||||
url := buildOpenAIModelsURL(bad.GetCNProtocolBaseURL(APIProtocolChatCompletions))
|
||||
t.Cleanup(func() {
|
||||
upstreamModelProtocols.mu.Lock()
|
||||
defer upstreamModelProtocols.mu.Unlock()
|
||||
for _, account := range []*Account{bad, chat, responses} {
|
||||
delete(upstreamModelProtocols.entries, modelProtocolCatalogKey(account, url))
|
||||
}
|
||||
})
|
||||
|
||||
require.Nil(t, svc.modelCatalogProtocols(t.Context(), bad, "vendor/model"))
|
||||
require.Equal(t, APIProtocolChatCompletions, svc.resolveUpstreamProtocolFor(t.Context(), chat, APIProtocolResponses, "vendor/model"), "a healthy account fetches its own catalog despite another account's backoff")
|
||||
require.Equal(t, APIProtocolResponses, svc.resolveUpstreamProtocolFor(t.Context(), responses, APIProtocolChatCompletions, "vendor/model"), "successful catalogs stay isolated when headers select different tenants")
|
||||
require.Equal(t, []string{APIProtocolChatCompletions}, svc.modelCatalogProtocols(t.Context(), chat, "vendor/model"))
|
||||
require.Nil(t, svc.modelCatalogProtocols(t.Context(), bad, "vendor/model"))
|
||||
upstream.mu.Lock()
|
||||
defer upstream.mu.Unlock()
|
||||
require.Len(t, upstream.requests, 3, "each healthy account fetches once; the failed account remains in its own backoff")
|
||||
for _, req := range upstream.requests {
|
||||
require.Equal(t, url, req.URL.String(), "all accounts use the same official model-list URL")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandCodeModelProtocolSetUsesCatalog(t *testing.T) {
|
||||
account := commandCodeTestAccount(11)
|
||||
both := []string{APIProtocolChatCompletions, APIProtocolResponses}
|
||||
|
||||
// 目录声明两种协议:入站同协议直通;Anthropic 入站走首选(内置规则没有命中时为 Chat Completions)。
|
||||
require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(account, APIProtocolResponses, "deepseek/deepseek-v4-flash", both))
|
||||
require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolChatCompletions, "deepseek/deepseek-v4-flash", both))
|
||||
require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolAnthropic, "deepseek/deepseek-v4-flash", both))
|
||||
// GPT 的首选沿用内置规则(Responses)。
|
||||
require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(account, APIProtocolAnthropic, "gpt-5.5", both))
|
||||
// 目录只声明 Chat Completions:Responses 入站也转换到 Chat Completions。
|
||||
require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolResponses, "deepseek/deepseek-v4-flash-fast", []string{APIProtocolChatCompletions}))
|
||||
require.Equal(t, APIProtocolAnthropic, resolveUpstreamProtocol(account, APIProtocolResponses, "claude-sonnet-4-6", []string{APIProtocolAnthropic}))
|
||||
|
||||
// 账号规则命中时优先于目录;已配置但未命中时仍使用目录。
|
||||
account.Credentials["protocol_rules"] = []any{map[string]any{"pattern": "deepseek/*", "protocol": APIProtocolChatCompletions}}
|
||||
require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolResponses, "deepseek/deepseek-v4-flash", both))
|
||||
require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(account, APIProtocolResponses, "zai-org/glm-5.3", both))
|
||||
|
||||
// 显式协议优先于一切。
|
||||
account.Credentials["api_protocol"] = APIProtocolChatCompletions
|
||||
require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolResponses, "zai-org/glm-5.3", both))
|
||||
}
|
||||
|
||||
func TestProtocolRulesWithProtocolSets(t *testing.T) {
|
||||
credentials := map[string]any{"protocol_rules": []any{
|
||||
map[string]any{"pattern": " GPT-* ", "protocol": APIProtocolResponses, "protocols": []any{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolChatCompletions}},
|
||||
map[string]any{"pattern": "qwen*", "protocols": []any{APIProtocolAnthropic}},
|
||||
map[string]any{"pattern": "glm-*", "protocol": APIProtocolChatCompletions},
|
||||
}}
|
||||
require.NoError(t, NormalizeProtocolRulesCredentials(credentials))
|
||||
require.Equal(t, []any{
|
||||
map[string]any{"pattern": "gpt-*", "protocol": APIProtocolResponses, "protocols": []any{APIProtocolResponses, APIProtocolChatCompletions}},
|
||||
map[string]any{"pattern": "qwen*", "protocol": APIProtocolAnthropic},
|
||||
map[string]any{"pattern": "glm-*", "protocol": APIProtocolChatCompletions},
|
||||
}, credentials["protocol_rules"])
|
||||
|
||||
bad := map[string]any{"protocol_rules": []any{map[string]any{"pattern": "gpt-*", "protocols": []any{"responses", "bogus"}}}}
|
||||
require.Error(t, NormalizeProtocolRulesCredentials(bad))
|
||||
|
||||
// 单一协议规则(OpenCode)不受影响:与入站无关。
|
||||
openCode := &Account{Platform: PlatformOpenCodeGo, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k"}}
|
||||
for _, inbound := range []string{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolAnthropic} {
|
||||
require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(openCode, inbound, "gpt-5.5", nil), inbound)
|
||||
require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(openCode, inbound, "glm-5.3", nil), inbound)
|
||||
}
|
||||
}
|
||||
|
||||
// 经真实入口验证:目录声明模型支持入站协议时原样直通,不做协议转换。
|
||||
func TestCommandCodeGatewayPassesThroughCatalogProtocols(t *testing.T) {
|
||||
type observation struct {
|
||||
url string
|
||||
body []byte
|
||||
}
|
||||
forward := func(t *testing.T, ingress routingMatrixIngress, model string, catalog map[string][]string) observation {
|
||||
t.Helper()
|
||||
base := fmt.Sprintf("http://cc-%s-%d.example", strings.ReplaceAll(t.Name(), "/", "-"), time.Now().UnixNano())
|
||||
account := commandCodeTestAccount(12)
|
||||
account.Credentials["api_base_urls"] = map[string]any{
|
||||
APIProtocolChatCompletions: base + "/provider/v1",
|
||||
APIProtocolResponses: base + "/provider/v1",
|
||||
APIProtocolAnthropic: base + "/provider",
|
||||
}
|
||||
url := buildOpenAIModelsURL(base + "/provider/v1")
|
||||
key := modelProtocolCatalogKey(account, url)
|
||||
if catalog != nil {
|
||||
upstreamModelProtocols.store(key, catalog, nil, time.Now())
|
||||
} else {
|
||||
// 目录不可用(退避中):不触发刷新,回落内置规则。
|
||||
upstreamModelProtocols.store(key, nil, errors.New("unavailable"), time.Now())
|
||||
}
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
body := routingMatrixCase{ingress: ingress, model: model}.body()
|
||||
_ = ingress.forward(svc, adaptiveProtocolTestContext(ingress.path, body), account, body)
|
||||
require.NotEmpty(t, upstream.requests)
|
||||
return observation{url: upstream.requests[len(upstream.requests)-1].URL.String(), body: upstream.lastBody}
|
||||
}
|
||||
ingresses := map[string]routingMatrixIngress{}
|
||||
for _, ingress := range routingMatrixIngresses() {
|
||||
ingresses[ingress.name] = ingress
|
||||
}
|
||||
catalog := map[string][]string{
|
||||
"deepseek/deepseek-v4-flash": {APIProtocolChatCompletions, APIProtocolResponses},
|
||||
"deepseek/deepseek-v4-flash-fast": {APIProtocolChatCompletions},
|
||||
"gpt-5.5": {APIProtocolChatCompletions, APIProtocolResponses},
|
||||
}
|
||||
|
||||
obs := forward(t, ingresses["responses"], "deepseek/deepseek-v4-flash", catalog)
|
||||
require.True(t, strings.HasSuffix(obs.url, "/provider/v1/responses"), obs.url)
|
||||
require.True(t, gjson.GetBytes(obs.body, "input").Exists(), "Responses body passes through unconverted")
|
||||
|
||||
obs = forward(t, ingresses["responses"], "deepseek/deepseek-v4-flash", nil)
|
||||
require.True(t, strings.HasSuffix(obs.url, "/provider/v1/chat/completions"), obs.url)
|
||||
require.True(t, gjson.GetBytes(obs.body, "messages").Exists())
|
||||
|
||||
obs = forward(t, ingresses["responses"], "deepseek/deepseek-v4-flash-fast", catalog)
|
||||
require.True(t, strings.HasSuffix(obs.url, "/provider/v1/chat/completions"), obs.url)
|
||||
|
||||
obs = forward(t, ingresses["chat"], "gpt-5.5", catalog)
|
||||
require.True(t, strings.HasSuffix(obs.url, "/provider/v1/chat/completions"), obs.url)
|
||||
require.True(t, gjson.GetBytes(obs.body, "messages").Exists(), "Chat body passes through unconverted")
|
||||
}
|
||||
|
||||
// 目录缺失时网关拉取目录,首个请求即按目录分流;自定义上游按账号各自拉取,并带上
|
||||
// 账号的请求头覆写。
|
||||
func TestCommandCodeGatewayFetchesModelCatalog(t *testing.T) {
|
||||
base := fmt.Sprintf("http://cc-fetch-%d.example/provider/v1", time.Now().UnixNano())
|
||||
newAccount := func(id int64) *Account {
|
||||
account := commandCodeTestAccount(id)
|
||||
account.Credentials["api_base_urls"] = map[string]any{
|
||||
APIProtocolChatCompletions: base,
|
||||
APIProtocolResponses: base,
|
||||
APIProtocolAnthropic: strings.TrimSuffix(base, "/v1"),
|
||||
}
|
||||
account.Credentials["header_override_enabled"] = true
|
||||
account.Credentials["header_overrides"] = map[string]any{"X-Tenant": fmt.Sprintf("t-%d", id)}
|
||||
return account
|
||||
}
|
||||
upstream := &commandCodeAlphaUpstream{responses: map[string]commandCodeAlphaResponse{
|
||||
"/provider/v1/models": {status: 200, body: commandCodeModelsSample},
|
||||
}}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
both := []string{APIProtocolChatCompletions, APIProtocolResponses}
|
||||
|
||||
first, second := newAccount(13), newAccount(14)
|
||||
require.Equal(t, both, svc.modelCatalogProtocols(t.Context(), first, "deepseek/deepseek-v4-flash"))
|
||||
require.Equal(t, both, svc.modelCatalogProtocols(t.Context(), first, "deepseek/deepseek-v4-flash"))
|
||||
require.Equal(t, both, svc.modelCatalogProtocols(t.Context(), second, "deepseek/deepseek-v4-flash"))
|
||||
|
||||
upstream.mu.Lock()
|
||||
defer upstream.mu.Unlock()
|
||||
require.Len(t, upstream.requests, 2, "one fetch per account on a custom upstream")
|
||||
for i, account := range []*Account{first, second} {
|
||||
req := upstream.requests[i]
|
||||
require.Equal(t, "/provider/v1/models", req.URL.Path)
|
||||
require.Equal(t, "Bearer user_test_key", req.Header.Get("Authorization"))
|
||||
require.Equal(t, fmt.Sprintf("t-%d", account.ID), getHeaderRaw(req.Header, "x-tenant"))
|
||||
}
|
||||
}
|
||||
@@ -90,6 +90,10 @@ func (a *Account) modelRateLimitKeysForRequest(ctx context.Context, requestedMod
|
||||
if isAnthropicFableModel(modelKey) && modelKey != anthropicFableRateLimitKey {
|
||||
keys = append(keys, anthropicFableRateLimitKey)
|
||||
}
|
||||
case PlatformCline:
|
||||
if walletKey := clineWalletRateLimitKey(modelKey); walletKey != "" {
|
||||
keys = append(keys, walletKey)
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
@@ -189,6 +193,17 @@ func (a *Account) modelRateLimitResetAt(scope string) *time.Time {
|
||||
return &resetAt
|
||||
}
|
||||
|
||||
// modelRateLimitReason 返回指定 scope 冷却记录中的原因;没有记录时为空。
|
||||
func (a *Account) modelRateLimitReason(scope string) string {
|
||||
if a == nil || a.Extra == nil {
|
||||
return ""
|
||||
}
|
||||
rawLimits, _ := a.Extra[modelRateLimitsKey].(map[string]any)
|
||||
rawLimit, _ := rawLimits[scope].(map[string]any)
|
||||
reason, _ := rawLimit["reason"].(string)
|
||||
return reason
|
||||
}
|
||||
|
||||
func setAccountModelRateLimitSnapshot(account *Account, scope string, resetAt time.Time, reason string, now time.Time) {
|
||||
if account == nil || strings.TrimSpace(scope) == "" {
|
||||
return
|
||||
|
||||
@@ -48,9 +48,9 @@ func TestOllamaCloudDefaultProtocolAndBaseURLs(t *testing.T) {
|
||||
require.True(t, account.IsAdaptiveAPIProtocol())
|
||||
|
||||
// C30/Q2-3:anthropic 默认 base 不带 /v1;cc/responses 带 /v1。
|
||||
require.Equal(t, "https://ollama.com", account.defaultCNProtocolBaseURL(APIProtocolAnthropic))
|
||||
require.Equal(t, "https://ollama.com/v1", account.defaultCNProtocolBaseURL(APIProtocolChatCompletions))
|
||||
require.Equal(t, "https://ollama.com/v1", account.defaultCNProtocolBaseURL(APIProtocolResponses))
|
||||
require.Equal(t, "https://ollama.com", account.defaultProviderBaseURL(APIProtocolAnthropic))
|
||||
require.Equal(t, "https://ollama.com/v1", account.defaultProviderBaseURL(APIProtocolChatCompletions))
|
||||
require.Equal(t, "https://ollama.com/v1", account.defaultProviderBaseURL(APIProtocolResponses))
|
||||
|
||||
// 同一结论经 adaptive 解析链(api_base_urls / base_url 均缺失)。
|
||||
require.Equal(t, "https://ollama.com", account.GetCNProtocolBaseURL(APIProtocolAnthropic))
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -31,7 +32,7 @@ func TestOllamaCloudPlatform_SchedulerSnapshotPlatforms(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
platforms := schedulerSnapshotPlatforms()
|
||||
require.Len(t, platforms, 12)
|
||||
require.ElementsMatch(t, domain.ConcretePlatformIDs(), platforms)
|
||||
require.Contains(t, platforms[:], PlatformOllamaCloud)
|
||||
require.Contains(t, platforms[:], PlatformTypeSafe)
|
||||
|
||||
@@ -46,7 +47,7 @@ func TestOllamaCloudPlatform_SchedulerSnapshotPlatforms(t *testing.T) {
|
||||
// 桶数必须与平台数组长度一致:每平台 single+forced,anthropic/gemini 各多一个 mixed。
|
||||
const groupID int64 = 7701
|
||||
require.Equal(t, len(platforms)*2+2, schedulerCanonicalBucketCount())
|
||||
require.Equal(t, 26, schedulerCanonicalBucketCount())
|
||||
require.Equal(t, 30, schedulerCanonicalBucketCount()) // 14 个具体平台
|
||||
|
||||
buckets := schedulerCanonicalBuckets(groupID)
|
||||
require.Len(t, buckets, schedulerCanonicalBucketCount())
|
||||
|
||||
@@ -133,8 +133,8 @@ func (s *AccountTestService) ProbeOpenAIAPIKeyResponsesSupport(ctx context.Conte
|
||||
if account.Type != AccountTypeAPIKey {
|
||||
return
|
||||
}
|
||||
if account.IsCNProvider() || account.Platform == PlatformOllamaCloud {
|
||||
// 国产 OpenAI 兼容上游默认仅支持 /v1/chat/completions。直接落标 false
|
||||
if account.RoutesProtocolByInbound() {
|
||||
// 按入站协议分流的供应商(国产厂商等)默认仅支持 /v1/chat/completions。直接落标 false
|
||||
// 走 Chat Completions 直转,跳过网络探测。
|
||||
// 例外:deepseek / kimi 的固定 responses 和 adaptive 账号使用官方原生
|
||||
// Responses 端点,落标 force_responses;其余协议显式重置为 auto,避免
|
||||
|
||||
@@ -93,6 +93,8 @@ type codexOAuthTransformOptions struct {
|
||||
SkipDefaultInstructions bool
|
||||
PreserveToolCallIDs bool
|
||||
OmitPromotedSystemMessagesFromInput bool
|
||||
// ResponsesLite selects where an injected hosted tool is declared.
|
||||
ResponsesLite bool
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -347,6 +349,12 @@ func applyCodexOAuthTransformWithOptions(reqBody map[string]any, opts codexOAuth
|
||||
result.Modified = true
|
||||
}
|
||||
|
||||
// Runs after input filtering so it sees the final replayed history. The
|
||||
// compact endpoint has its own wire shape and is left untouched.
|
||||
if !opts.IsCompact && ensureOpenAIOAuthWebSearchToolForHistory(reqBody, opts.ResponsesLite) {
|
||||
result.Modified = true
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
@@ -110,88 +110,43 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions(
|
||||
}
|
||||
|
||||
// Cursor compatibility: some clients send a Responses-shaped body to the
|
||||
// /v1/chat/completions URL. Detect it before adaptive routing so adaptive
|
||||
// /v1/chat/completions URL. Detect it before protocol routing so adaptive
|
||||
// accounts never forward the body unchanged to a Chat Completions endpoint.
|
||||
isResponsesShape := !gjson.GetBytes(body, "messages").Exists() && gjson.GetBytes(body, "input").Exists()
|
||||
|
||||
// OpenCode Go:按模型原生协议分流(与 inbound 协议正交)。
|
||||
// 规则未命中一律兜底 Chat Completions,只有显式 Responses 才走下方转换链。
|
||||
if account.IsOpenCodeGo() {
|
||||
mapped := resolveOpenCodeGoMappedModel(account, body, defaultMappedModel)
|
||||
if IsOpenCodeUnsupportedModel(mapped) {
|
||||
return nil, writeOpenCodeUnsupportedModelError(c, false, mapped)
|
||||
}
|
||||
proto := openCodeGoNativeProtocol(account, mapped)
|
||||
if proto != APIProtocolResponses {
|
||||
if isResponsesShape {
|
||||
if proto == APIProtocolAnthropic {
|
||||
return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, "")
|
||||
}
|
||||
var responsesReq apicompat.ResponsesRequest
|
||||
if err := json.Unmarshal(body, &responsesReq); err != nil {
|
||||
return nil, fmt.Errorf("parse responses-shaped chat completions request: %w", err)
|
||||
}
|
||||
chatReq, err := apicompat.ResponsesToChatCompletionsRequestWithOptions(
|
||||
&responsesReq,
|
||||
&apicompat.ResponsesToChatOptions{ReasoningContentByID: s.reasoningContentByID},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("convert responses-shaped chat completions request: %w", err)
|
||||
}
|
||||
chatBody, err := json.Marshal(chatReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal converted chat completions request: %w", err)
|
||||
}
|
||||
return s.forwardAsRawChatCompletions(ctx, c, account, chatBody, defaultMappedModel)
|
||||
}
|
||||
if proto == APIProtocolAnthropic {
|
||||
return s.forwardChatCompletionsViaNativeAnthropic(ctx, c, account, body, defaultMappedModel)
|
||||
}
|
||||
return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel)
|
||||
}
|
||||
inbound := APIProtocolChatCompletions
|
||||
if isResponsesShape {
|
||||
inbound = APIProtocolResponses
|
||||
}
|
||||
// 按模型分流与 adaptive 账号按请求体形状处理 Responses 形状入站;其余账号
|
||||
// 维持原样把请求体交给所选路径。
|
||||
convertResponsesShape := isResponsesShape && (account.routesByModel() || account.IsAdaptiveAPIProtocol())
|
||||
|
||||
// 自适应账号的标准 Chat Completions 入站使用供应商原生 CC 端点。
|
||||
// Responses 形状下,DeepSeek / Kimi 继续走下方原生 Responses 链;GLM
|
||||
// 没有 Responses 端点,先转换成 Chat Completions 再直转。
|
||||
if account.IsAdaptiveAPIProtocol() && !account.IsOpenCodeGo() {
|
||||
if !isResponsesShape {
|
||||
return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel)
|
||||
// 上游协议统一由 resolveUpstreamProtocol 判定(按模型分流时带上游模型目录)。Anthropic 分流必须先于
|
||||
// ShouldUseResponsesAPI:Anthropic 协议账号经 probe 落标
|
||||
// openai_responses_supported=false,否则会命中 CC 直转。
|
||||
routingModel := upstreamRoutingModel(account, body, defaultMappedModel)
|
||||
if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(routingModel) {
|
||||
return nil, writeOpenCodeUnsupportedModelError(c, false, routingModel)
|
||||
}
|
||||
switch s.resolveUpstreamProtocolFor(ctx, account, inbound, routingModel) {
|
||||
case APIProtocolAnthropic:
|
||||
if convertResponsesShape {
|
||||
return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, "")
|
||||
}
|
||||
if !account.SupportsNativeCNResponses() {
|
||||
var responsesReq apicompat.ResponsesRequest
|
||||
if err := json.Unmarshal(body, &responsesReq); err != nil {
|
||||
return nil, fmt.Errorf("parse responses-shaped chat completions request: %w", err)
|
||||
}
|
||||
chatReq, err := apicompat.ResponsesToChatCompletionsRequestWithOptions(
|
||||
&responsesReq,
|
||||
&apicompat.ResponsesToChatOptions{ReasoningContentByID: s.reasoningContentByID},
|
||||
)
|
||||
// CC 入站经 CC→Responses→Anthropic 转换链直通供应商原生 Anthropic 端点。
|
||||
return s.forwardChatCompletionsViaNativeAnthropic(ctx, c, account, body, defaultMappedModel)
|
||||
case APIProtocolChatCompletions:
|
||||
if convertResponsesShape {
|
||||
chatBody, err := s.convertResponsesShapedChatBody(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("convert responses-shaped chat completions request: %w", err)
|
||||
}
|
||||
chatBody, err := json.Marshal(chatReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal converted chat completions request: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
return s.forwardAsRawChatCompletions(ctx, c, account, chatBody, defaultMappedModel)
|
||||
}
|
||||
// DeepSeek / Kimi 原生 Responses 请求继续走下方 Responses→Chat 回程转换。
|
||||
}
|
||||
|
||||
// 入口分流(国产供应商 Anthropic 协议):上游为供应商原生 Anthropic 端点,
|
||||
// CC 入站请求经 CC→Responses→Anthropic 转换链直通该端点。必须先于
|
||||
// ShouldUseResponsesAPI 分流:该类账号经 probe 落标
|
||||
// openai_responses_supported=false,会先命中下方的 CC 直转分支。
|
||||
if account.IsAnthropicProtocol() {
|
||||
return s.forwardChatCompletionsViaNativeAnthropic(ctx, c, account, body, defaultMappedModel)
|
||||
}
|
||||
|
||||
// 固定 chat_completions 的 CN 账号,以及强制或已探测确认不支持 Responses
|
||||
// 的其他 APIKey 账号,均走 CC 直转。
|
||||
if shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
|
||||
return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel)
|
||||
}
|
||||
// 上游为 Responses(含 adaptive 下 Responses 形状入站且供应商有原生
|
||||
// Responses 端点):走下方 Chat Completions ↔ Responses 转换链。
|
||||
SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint)
|
||||
|
||||
startTime := time.Now()
|
||||
@@ -430,7 +385,7 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions(
|
||||
return s.forwardAsChatCompletions(markAgentIdentityTaskRecoveryTried(ctx), c, account, body, promptCacheKey, defaultMappedModel, compatPromptCacheTenantIsolated)
|
||||
}
|
||||
if account.Type == AccountTypeAPIKey &&
|
||||
!account.IsOpenCodeGo() &&
|
||||
!account.routesByModel() &&
|
||||
openai_compat.ResolveResponsesSupport(account.Extra) == openai_compat.ResponsesSupportUnknown &&
|
||||
!isResponsesEndpointSupportedByStatus(resp.StatusCode) {
|
||||
logger.L().Info("openai chat_completions: /responses unsupported, falling back to raw chat completions",
|
||||
|
||||
@@ -150,7 +150,7 @@ func prepareNativeOpenAIInputTokensCountRequest(body []byte, account *Account) (
|
||||
}
|
||||
|
||||
func shouldEstimateOpenAIInputTokensLocally(account *Account) bool {
|
||||
if account == nil || account.IsGrok() || account.IsCNProvider() || account.Type == AccountTypeUpstream {
|
||||
if account == nil || account.IsGrok() || account.RoutesProtocolByInbound() || account.Type == AccountTypeUpstream {
|
||||
return true
|
||||
}
|
||||
if account.Type != AccountTypeAPIKey {
|
||||
@@ -264,8 +264,7 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic(
|
||||
return fmt.Errorf("count_tokens: missing account")
|
||||
}
|
||||
|
||||
// 国产供应商、OpenCode 与 Ollama Cloud(全部协议,含 anthropic):一律本地估算,
|
||||
// 不发上游请求。
|
||||
// 多协议 API Key 供应商(国产厂商与聚合平台,全部协议,含 anthropic):一律本地估算,不发上游请求。
|
||||
// 依据(2026-08 核实):三家的 Anthropic 兼容层均未提供
|
||||
// /v1/messages/count_tokens——DeepSeek 官方 anthropic_api 文档无此端点
|
||||
// (且注明 anthropic-version 头被忽略),聚合网关 OpenModel 明确标注
|
||||
@@ -274,7 +273,7 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic(
|
||||
// 高频调用此端点,本地 tiktoken 估算是与 Grok 一致的既有方案。
|
||||
// Ollama Cloud 同因:其 Anthropic 兼容层同样未提供该端点(上游只有
|
||||
// /v1/responses/input_tokens),转发同样只会得到 404。
|
||||
if account.IsCNProvider() || account.IsOpenCodeGo() || account.IsOllamaCloud() {
|
||||
if account.IsMultiProtocolAPIKey() {
|
||||
estimated, err := estimateAnthropicCountTokensLocally(body)
|
||||
if err != nil {
|
||||
writeAnthropicCountTokensError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body")
|
||||
|
||||
@@ -159,27 +159,6 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
return s.forwardGrokResponses(ctx, c, account, body, originalModel, reqStream, startTime)
|
||||
}
|
||||
|
||||
if account.IsOpenCodeGo() {
|
||||
mapped := resolveOpenCodeGoMappedModel(account, body, "")
|
||||
if IsOpenCodeUnsupportedModel(mapped) {
|
||||
return nil, writeOpenCodeUnsupportedModelError(c, false, mapped)
|
||||
}
|
||||
switch openCodeGoNativeProtocol(account, mapped) {
|
||||
case APIProtocolAnthropic:
|
||||
return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, "")
|
||||
case APIProtocolResponses:
|
||||
break
|
||||
default:
|
||||
return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body)
|
||||
}
|
||||
}
|
||||
|
||||
// CN 供应商 anthropic 协议账号:/v1/responses 入站是交叉协议组合
|
||||
// (Responses 客户端 × Anthropic 上游),转成 Anthropic 请求走原生端点。
|
||||
// 不能落到下面的 raw-CC 分支——其 URL 构造会把 anthropic base 当 CC base 用。
|
||||
if account.IsAnthropicProtocol() {
|
||||
return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, reqModel)
|
||||
}
|
||||
if account.IsOpenAIApiKey() {
|
||||
if normalized, changed, normalizeErr := normalizeOpenAIParallelToolCallsWithoutTools(body, responsesLite); normalizeErr != nil {
|
||||
return nil, normalizeErr
|
||||
@@ -198,7 +177,19 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
originalModel = reqModel
|
||||
}
|
||||
|
||||
if shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
|
||||
// 上游协议统一由 resolveUpstreamProtocol 判定(按模型分流时带上游模型目录)。OpenAI API Key 账号只会落到
|
||||
// Responses / Chat Completions,上面的归一化对两条路径都生效。
|
||||
routingModel := upstreamRoutingModel(account, body, "")
|
||||
if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(routingModel) {
|
||||
return nil, writeOpenCodeUnsupportedModelError(c, false, routingModel)
|
||||
}
|
||||
switch s.resolveUpstreamProtocolFor(ctx, account, APIProtocolResponses, routingModel) {
|
||||
case APIProtocolAnthropic:
|
||||
// Responses 客户端 × Anthropic 上游:转成 Anthropic 请求走原生端点。不能落到
|
||||
// raw-CC 分支——其 URL 构造会把 anthropic base 当 CC base 用。
|
||||
// 账号映射未命中时以去除首尾空白的请求模型兜底,计费名与上游模型名一致。
|
||||
return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, reqModel)
|
||||
case APIProtocolChatCompletions:
|
||||
return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body)
|
||||
}
|
||||
SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint)
|
||||
@@ -517,6 +508,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
SkipDefaultInstructions: true,
|
||||
PreserveToolCallIDs: true,
|
||||
OmitPromotedSystemMessagesFromInput: omitPromotedSystemMessages,
|
||||
ResponsesLite: responsesLite,
|
||||
})
|
||||
ensureCodexOAuthInstructionsField(decoded)
|
||||
markDecodedModified()
|
||||
@@ -525,6 +517,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
IsCodexCLI: isCodexCLI,
|
||||
IsCompact: isCompactRequest,
|
||||
OmitPromotedSystemMessagesFromInput: omitPromotedSystemMessages,
|
||||
ResponsesLite: responsesLite,
|
||||
})
|
||||
}
|
||||
if codexResult.Error != nil {
|
||||
@@ -1360,14 +1353,15 @@ func shouldForwardOpenAIResponsesViaRawChatCompletions(account *Account) bool {
|
||||
if account == nil || account.Type != AccountTypeAPIKey {
|
||||
return false
|
||||
}
|
||||
if account.IsOpenCodeGo() {
|
||||
if account.routesByModel() {
|
||||
// Model protocol_rules are the authority. Probe Extra must not collapse
|
||||
// Grok/GPT/Muse into Chat Completions.
|
||||
return false
|
||||
}
|
||||
if account.IsCNProvider() {
|
||||
// CN 的显式协议配置优先于异步探针 Extra;adaptive 仅 DeepSeek / Kimi
|
||||
// 有原生 Responses,GLM 回退 Chat Completions。
|
||||
if account.RoutesProtocolByInbound() {
|
||||
// 按入站协议分流的供应商(国产厂商等):显式协议配置优先于异步探针
|
||||
// Extra;adaptive 仅在供应商有原生 Responses 端点时直转,否则回退
|
||||
// Chat Completions(如 GLM)。
|
||||
switch account.GetAPIProtocol() {
|
||||
case APIProtocolChatCompletions:
|
||||
return true
|
||||
|
||||
@@ -53,32 +53,21 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// OpenCode Go:按模型原生协议分流。规则未命中兜底 Chat Completions。
|
||||
if account.IsOpenCodeGo() {
|
||||
mapped := resolveOpenCodeGoMappedModel(account, body, defaultMappedModel)
|
||||
if IsOpenCodeUnsupportedModel(mapped) {
|
||||
return nil, writeOpenCodeUnsupportedModelError(c, true, mapped)
|
||||
}
|
||||
switch openCodeGoNativeProtocol(account, mapped) {
|
||||
case APIProtocolAnthropic:
|
||||
return s.forwardAnthropicViaNativeAnthropicEndpoint(ctx, c, account, body, defaultMappedModel)
|
||||
case APIProtocolResponses:
|
||||
break
|
||||
default:
|
||||
return s.forwardAnthropicViaRawChatCompletions(ctx, c, account, body, defaultMappedModel)
|
||||
}
|
||||
} else if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() {
|
||||
// 入口分流(国产供应商 Anthropic 协议):上游为供应商原生 Anthropic 端点时,
|
||||
// /v1/messages 请求零转换直通(仅模型名映射 + 少量 body 清洗),完整保留
|
||||
// thinking / tool_use / cache 语义,适配 Claude Code 等原生客户端。
|
||||
// 必须先于 ShouldUseResponsesAPI 分流:Anthropic 协议账号经 probe 落标
|
||||
// openai_responses_supported=false,会先命中下方的 CC 直转分支。
|
||||
return s.forwardAnthropicViaNativeAnthropicEndpoint(ctx, c, account, body, defaultMappedModel)
|
||||
// 上游协议统一由 resolveUpstreamProtocol 判定(按模型分流时带上游模型目录)。Anthropic 分流必须先于
|
||||
// ShouldUseResponsesAPI:Anthropic 协议账号经 probe 落标
|
||||
// openai_responses_supported=false,否则会命中 CC 直转。
|
||||
routingModel := upstreamRoutingModel(account, body, defaultMappedModel)
|
||||
if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(routingModel) {
|
||||
return nil, writeOpenCodeUnsupportedModelError(c, true, routingModel)
|
||||
}
|
||||
|
||||
// 固定 chat_completions 的 CN 账号,以及不支持 Responses 的其他 APIKey
|
||||
// 账号,均将 Messages 转为 CC;固定 responses 的 CN 账号不受探针旧值覆盖。
|
||||
if shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
|
||||
switch s.resolveUpstreamProtocolFor(ctx, account, APIProtocolAnthropic, routingModel) {
|
||||
case APIProtocolAnthropic:
|
||||
// 上游为供应商原生 Anthropic 端点:/v1/messages 零转换直通(仅模型名映射 +
|
||||
// 少量 body 清洗),完整保留 thinking / tool_use / cache 语义。
|
||||
return s.forwardAnthropicViaNativeAnthropicEndpoint(ctx, c, account, body, defaultMappedModel)
|
||||
case APIProtocolChatCompletions:
|
||||
// 固定 chat_completions 的多协议账号、规则命中 CC 的按模型分流账号,以及
|
||||
// 不支持 Responses 的其他 APIKey 账号,均将 Messages 转为 CC。
|
||||
return s.forwardAnthropicViaRawChatCompletions(ctx, c, account, body, defaultMappedModel)
|
||||
}
|
||||
SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint)
|
||||
|
||||
@@ -139,13 +139,22 @@ func (s *OpenAIGatewayService) nativeAnthropicTargetURL(account *Account) (strin
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid base_url: %w", err)
|
||||
}
|
||||
// 版本感知拼接:base 已带 /v1 时不再追加,避免拼出 /v1/v1/messages
|
||||
//(OpenCode Go 的 Chat Completions base 带 /v1,Ollama Cloud 的 anthropic
|
||||
// 默认 base 不带)。
|
||||
return buildOpenAIEndpointURL(validatedURL, "/v1/messages"), nil
|
||||
return nativeAnthropicMessagesURL(account, validatedURL), nil
|
||||
}
|
||||
|
||||
func resolveOpenCodeGoMappedModel(account *Account, body []byte, defaultMappedModel string) string {
|
||||
// nativeAnthropicMessagesURL 由已校验的 Anthropic 协议基址拼出 messages 端点,转发与
|
||||
// 连接测试共用。按模型分流的聚合平台(OpenCode、Command Code 等)的基址可能沿用带 /v1
|
||||
// 的 Chat Completions 基址,用版本感知拼接避免 /v1/v1/messages;其余供应商朴素拼接。
|
||||
func nativeAnthropicMessagesURL(account *Account, validatedBaseURL string) string {
|
||||
// 版本感知拼接:base 已带 /v1 时不再追加,避免拼出 /v1/v1/messages(按模型分流平台的
|
||||
// Chat Completions base 带 /v1;Ollama Cloud 的 anthropic 默认 base 不带,自定义可能带)。
|
||||
if account.routesByModel() || account.IsOllamaCloud() {
|
||||
return buildOpenAIEndpointURL(validatedBaseURL, "/v1/messages")
|
||||
}
|
||||
return strings.TrimRight(validatedBaseURL, "/") + "/v1/messages"
|
||||
}
|
||||
|
||||
func resolveMappedUpstreamModel(account *Account, body []byte, defaultMappedModel string) string {
|
||||
original := strings.TrimSpace(gjson.GetBytes(body, "model").String())
|
||||
billing := resolveOpenAIForwardModel(account, original, defaultMappedModel)
|
||||
return normalizeOpenAIModelForUpstream(account, billing)
|
||||
|
||||
@@ -213,7 +213,10 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough(
|
||||
}
|
||||
if account != nil && account.IsOpenAI() {
|
||||
responsesLite := isOpenAIResponsesLiteHeader(c.GetHeader(responsesLiteHeader)) || isOpenAIResponsesLiteWebSocketPayload(body)
|
||||
normalizedBody, normalized, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, account, responsesLite)
|
||||
normalizedBody, normalized, normalizeErr := normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{
|
||||
ResponsesLite: responsesLite,
|
||||
Compact: isOpenAIResponsesCompactPath(c),
|
||||
})
|
||||
if normalizeErr != nil {
|
||||
return nil, fmt.Errorf("normalize passthrough Responses compatibility: %w", normalizeErr)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestOpenAIGatewayServiceRecordUsage_AggregatorClaudeUsesDefaultPricing(t *testing.T) {
|
||||
for _, platform := range []string{PlatformCommandCode, PlatformCline} {
|
||||
for _, model := range []string{"claude-sonnet-4-6", "anthropic/claude-sonnet-4-6"} {
|
||||
t.Run(platform+"/"+model, func(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
userRepo := &openAIRecordUsageUserRepoStub{}
|
||||
svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil)
|
||||
svc.resolver = NewModelPricingResolver(nil, svc.billingService)
|
||||
group := &Group{ID: 1, Platform: platform, RateMultiplier: 1.1}
|
||||
usage := OpenAIUsage{InputTokens: 1000, OutputTokens: 200}
|
||||
expected := expectedOpenAICost(t, svc, model, usage, group.RateMultiplier)
|
||||
require.Greater(t, expected.ActualCost, 0.0)
|
||||
|
||||
err := svc.RecordUsage(context.Background(), providerClaudeRecordUsageInput(platform, model, group, usage))
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, usageRepo.calls)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Equal(t, usage.InputTokens, usageRepo.lastLog.InputTokens)
|
||||
require.Equal(t, usage.OutputTokens, usageRepo.lastLog.OutputTokens)
|
||||
require.InDelta(t, expected.TotalCost, usageRepo.lastLog.TotalCost, 1e-12)
|
||||
require.InDelta(t, expected.ActualCost, usageRepo.lastLog.ActualCost, 1e-12)
|
||||
require.Equal(t, 1, userRepo.deductCalls)
|
||||
require.InDelta(t, expected.ActualCost, userRepo.lastAmount, 1e-12)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayServiceRecordUsage_CNAndOpenCodeClaudeRequireExplicitPricing(t *testing.T) {
|
||||
for _, platform := range []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} {
|
||||
t.Run(platform, func(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
userRepo := &openAIRecordUsageUserRepoStub{}
|
||||
svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil)
|
||||
svc.resolver = NewModelPricingResolver(nil, svc.billingService)
|
||||
group := &Group{ID: 1, Platform: platform, RateMultiplier: 1.1}
|
||||
usage := OpenAIUsage{InputTokens: 1000, OutputTokens: 200}
|
||||
|
||||
err := svc.RecordUsage(context.Background(), providerClaudeRecordUsageInput(platform, "claude-sonnet-4-6", group, usage))
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, usageRepo.calls)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Equal(t, usage.InputTokens, usageRepo.lastLog.InputTokens)
|
||||
require.Equal(t, usage.OutputTokens, usageRepo.lastLog.OutputTokens)
|
||||
require.Zero(t, usageRepo.lastLog.TotalCost)
|
||||
require.Zero(t, usageRepo.lastLog.ActualCost)
|
||||
require.Zero(t, userRepo.deductCalls)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayServiceRecordUsage_CNAndOpenCodeClaudeHonorExplicitPricing(t *testing.T) {
|
||||
const model = "claude-sonnet-4-6"
|
||||
for _, platform := range []string{PlatformKimi, PlatformOpenCodeGo} {
|
||||
for _, source := range []string{PricingSourceGroup, PricingSourceChannel} {
|
||||
t.Run(platform+"/"+source, func(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
userRepo := &openAIRecordUsageUserRepoStub{}
|
||||
svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil)
|
||||
group := &Group{ID: 1, Platform: platform, RateMultiplier: 1.25}
|
||||
inputPrice, outputPrice := 1e-6, 2e-6
|
||||
pricing := ChannelModelPricing{
|
||||
Models: []string{model}, BillingMode: BillingModeToken,
|
||||
InputPrice: &inputPrice, OutputPrice: &outputPrice,
|
||||
}
|
||||
if source == PricingSourceGroup {
|
||||
group.ModelPricing = []ChannelModelPricing{pricing}
|
||||
} else {
|
||||
cache := newEmptyChannelCache()
|
||||
cache.pricingByGroupModel[channelModelKey{groupID: group.ID, platform: platform, model: model}] = &pricing
|
||||
cache.channelByGroupID[group.ID] = &Channel{ID: 1, Status: StatusActive}
|
||||
cache.groupPlatform[group.ID] = platform
|
||||
cache.loadedAt = time.Now()
|
||||
svc.channelService = &ChannelService{}
|
||||
svc.channelService.cache.Store(cache)
|
||||
}
|
||||
svc.resolver = NewModelPricingResolver(svc.channelService, svc.billingService)
|
||||
usage := OpenAIUsage{InputTokens: 1000, OutputTokens: 200}
|
||||
expectedTotal := float64(usage.InputTokens)*inputPrice + float64(usage.OutputTokens)*outputPrice
|
||||
expectedActual := expectedTotal * group.RateMultiplier
|
||||
|
||||
err := svc.RecordUsage(context.Background(), providerClaudeRecordUsageInput(platform, model, group, usage))
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.InDelta(t, expectedTotal, usageRepo.lastLog.TotalCost, 1e-12)
|
||||
require.InDelta(t, expectedActual, usageRepo.lastLog.ActualCost, 1e-12)
|
||||
require.Equal(t, 1, userRepo.deductCalls)
|
||||
require.InDelta(t, expectedActual, userRepo.lastAmount, 1e-12)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func providerClaudeRecordUsageInput(platform, model string, group *Group, usage OpenAIUsage) *OpenAIRecordUsageInput {
|
||||
return &OpenAIRecordUsageInput{
|
||||
Result: &OpenAIForwardResult{
|
||||
RequestID: "provider_claude_" + platform,
|
||||
Model: model, BillingModel: model, UpstreamModel: model,
|
||||
Usage: usage, Duration: time.Second,
|
||||
},
|
||||
APIKey: &APIKey{ID: 10, GroupID: &group.ID, Group: group},
|
||||
User: &User{ID: 20},
|
||||
Account: &Account{ID: 30, Platform: platform, Type: AccountTypeAPIKey},
|
||||
}
|
||||
}
|
||||
@@ -53,11 +53,11 @@ func buildOpenAIResponsesURL(base string) string {
|
||||
}
|
||||
|
||||
// buildOpenAIResponsesURLForPlatform 组装 Responses 端点(平台感知)。
|
||||
// DeepSeek 官方 Responses 端点为 /responses(无 /v1 前缀,适配 Codex);
|
||||
// 其余平台维持 /v1/responses。
|
||||
// 供应商 profile 声明了 ResponsesPath 时按其拼接(如 DeepSeek 为无 /v1 前缀的
|
||||
// /responses);其余平台维持 /v1/responses。
|
||||
func buildOpenAIResponsesURLForPlatform(platform string, base string) string {
|
||||
if platform == PlatformDeepseek {
|
||||
return buildOpenAIEndpointURL(base, "/responses")
|
||||
if profile := LookupProviderProfile(platform); profile != nil && profile.ResponsesPath != "" {
|
||||
return buildOpenAIEndpointURL(base, profile.ResponsesPath)
|
||||
}
|
||||
return buildOpenAIResponsesURL(base)
|
||||
}
|
||||
@@ -1475,6 +1475,18 @@ func normalizeOpenAIResponseFormatSchemasBody(body []byte) ([]byte, bool, error)
|
||||
}
|
||||
|
||||
func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Account, responsesLite bool) ([]byte, bool, error) {
|
||||
return normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{ResponsesLite: responsesLite})
|
||||
}
|
||||
|
||||
type openAIResponsesCompatibilityOptions struct {
|
||||
ResponsesLite bool
|
||||
// Compact marks the /responses/compact wire shape, which is left as-is
|
||||
// by request-shape compatibility rewrites such as web_search history.
|
||||
Compact bool
|
||||
}
|
||||
|
||||
func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account *Account, opts openAIResponsesCompatibilityOptions) ([]byte, bool, error) {
|
||||
responsesLite := opts.ResponsesLite
|
||||
if account == nil || !account.IsOpenAI() {
|
||||
return body, false, nil
|
||||
}
|
||||
@@ -1539,6 +1551,14 @@ func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Ac
|
||||
normalized = next
|
||||
changed = true
|
||||
}
|
||||
if !opts.Compact {
|
||||
webSearchBody, webSearchChanged, err := ensureOpenAIOAuthWebSearchToolForHistoryBody(normalized, responsesLite)
|
||||
if err != nil {
|
||||
return body, false, fmt.Errorf("normalize websocket body: %w", err)
|
||||
}
|
||||
normalized = webSearchBody
|
||||
changed = changed || webSearchChanged
|
||||
}
|
||||
}
|
||||
needsOrphanCleanup := account != nil && account.IsOpenAIOAuthLike() &&
|
||||
gjson.GetBytes(normalized, "input").IsArray()
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/openai"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -285,20 +286,18 @@ func (s *OpenAIGatewayService) SelectAccountForTokenCount(
|
||||
)
|
||||
}
|
||||
|
||||
// NormalizeOpenAICompatiblePlatform 保留 grok 与国产 OpenAI 兼容供应商(kimi/zhipu/
|
||||
// deepseek)的原值,其他值一律归一为 openai。调度器据此对账号与请求做精确平台匹配:
|
||||
// NormalizeOpenAICompatiblePlatform 保留走 OpenAI 网关的平台(openai、grok 与多协议
|
||||
// API Key 供应商,见平台清单)的原值,其他值一律归一为 openai。调度器据此对账号与请求做精确平台匹配:
|
||||
// kimi 分组请求只命中 kimi 账号,语义与 openai/grok 一致。
|
||||
// Ollama Cloud 同样必须保留原值:归一为 openai 会让 ollama_cloud 分组去查
|
||||
// openai 候选桶,表现为静默空池。
|
||||
// (upstream 曾将本函数改为未导出 normalizeOpenAICompatiblePlatform,本分支的
|
||||
// handler 调度入口仍需导出,保持导出名。)
|
||||
func NormalizeOpenAICompatiblePlatform(platform string) string {
|
||||
switch platform {
|
||||
case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud:
|
||||
if domain.UsesOpenAIGateway(platform) {
|
||||
return platform
|
||||
default:
|
||||
return PlatformOpenAI
|
||||
}
|
||||
return PlatformOpenAI
|
||||
}
|
||||
|
||||
// ---- composite account_pool 契约接入点(增量2A) ----
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// The ChatGPT internal Codex endpoint rejects a request whose input replays a
|
||||
// hosted web_search_call item unless the request also declares the web_search
|
||||
// tool; the stream then fails with "response protection is unavailable".
|
||||
// Codex's local context compaction sends the full history with tools:[], so
|
||||
// every compaction after a web search fails (#7927).
|
||||
//
|
||||
// Declare a cached-only web_search tool for such requests. Responses Lite
|
||||
// rejects hosted tools at the top level, so Lite requests carry it in an
|
||||
// input additional_tools item instead. When the caller declared no tools at
|
||||
// all, also pin tool_choice to "none" so the injected tool cannot be invoked
|
||||
// and the request keeps its no-tools semantics.
|
||||
|
||||
const (
|
||||
openAIWebSearchCallItemType = "web_search_call"
|
||||
openAIAdditionalToolsItemType = "additional_tools"
|
||||
openAICompactionTriggerItemType = "compaction_trigger"
|
||||
openAIAdditionalToolsDefaultRole = "developer"
|
||||
)
|
||||
|
||||
var openAIWebSearchHistoryTool = map[string]any{
|
||||
"type": "web_search",
|
||||
"external_web_access": false,
|
||||
}
|
||||
|
||||
func isOpenAIWebSearchToolType(toolType string) bool {
|
||||
return strings.HasPrefix(strings.TrimSpace(toolType), "web_search")
|
||||
}
|
||||
|
||||
func openAIToolsContainWebSearch(rawTools any) bool {
|
||||
tools, ok := rawTools.([]any)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for _, rawTool := range tools {
|
||||
tool, ok := rawTool.(map[string]any)
|
||||
if ok && isOpenAIWebSearchToolType(firstNonEmptyString(tool["type"])) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// shouldPinOpenAIWebSearchHistoryToolChoice reports whether tool_choice may be
|
||||
// forced to "none": only when the caller offered no tools, so the choice
|
||||
// cannot meaningfully be anything else.
|
||||
func shouldPinOpenAIWebSearchHistoryToolChoice(choice any) bool {
|
||||
switch typed := choice.(type) {
|
||||
case nil:
|
||||
return true
|
||||
case string:
|
||||
normalized := strings.ToLower(strings.TrimSpace(typed))
|
||||
return normalized == "" || normalized == "auto" || normalized == "none"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// openAIAdditionalToolsInsertIndex keeps a trailing compaction trigger last,
|
||||
// as required by the remote compaction v2 wire format.
|
||||
func openAIAdditionalToolsInsertIndex(itemTypes []string) int {
|
||||
if n := len(itemTypes); n > 0 && itemTypes[n-1] == openAICompactionTriggerItemType {
|
||||
return n - 1
|
||||
}
|
||||
return len(itemTypes)
|
||||
}
|
||||
|
||||
// ensureOpenAIOAuthWebSearchToolForHistory is the map variant used by the
|
||||
// Codex OAuth transform.
|
||||
func ensureOpenAIOAuthWebSearchToolForHistory(reqBody map[string]any, responsesLite bool) bool {
|
||||
if reqBody == nil {
|
||||
return false
|
||||
}
|
||||
input, ok := reqBody["input"].([]any)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
hasWebSearchCall := false
|
||||
callerDeclaredTools := false
|
||||
additionalToolsIndex := -1
|
||||
itemTypes := make([]string, len(input))
|
||||
for i, rawItem := range input {
|
||||
item, ok := rawItem.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
itemTypes[i] = strings.TrimSpace(firstNonEmptyString(item["type"]))
|
||||
switch itemTypes[i] {
|
||||
case openAIWebSearchCallItemType:
|
||||
hasWebSearchCall = true
|
||||
case openAIAdditionalToolsItemType:
|
||||
if openAIToolsContainWebSearch(item["tools"]) {
|
||||
return false
|
||||
}
|
||||
if tools, _ := item["tools"].([]any); len(tools) > 0 {
|
||||
callerDeclaredTools = true
|
||||
}
|
||||
if additionalToolsIndex < 0 {
|
||||
additionalToolsIndex = i
|
||||
}
|
||||
}
|
||||
}
|
||||
if !hasWebSearchCall || openAIToolsContainWebSearch(reqBody["tools"]) {
|
||||
return false
|
||||
}
|
||||
tools, _ := reqBody["tools"].([]any)
|
||||
callerDeclaredTools = callerDeclaredTools || len(tools) > 0
|
||||
|
||||
switch {
|
||||
case !responsesLite:
|
||||
reqBody["tools"] = append(tools, cloneOpenAIWebSearchHistoryTool())
|
||||
case additionalToolsIndex >= 0:
|
||||
// additionalToolsIndex is only recorded for map items.
|
||||
item, _ := input[additionalToolsIndex].(map[string]any)
|
||||
existing, _ := item["tools"].([]any)
|
||||
item["tools"] = append(existing, cloneOpenAIWebSearchHistoryTool())
|
||||
default:
|
||||
at := openAIAdditionalToolsInsertIndex(itemTypes)
|
||||
additional := map[string]any{
|
||||
"type": openAIAdditionalToolsItemType,
|
||||
"role": openAIAdditionalToolsDefaultRole,
|
||||
"tools": []any{cloneOpenAIWebSearchHistoryTool()},
|
||||
}
|
||||
next := make([]any, 0, len(input)+1)
|
||||
next = append(next, input[:at]...)
|
||||
next = append(next, additional)
|
||||
next = append(next, input[at:]...)
|
||||
reqBody["input"] = next
|
||||
}
|
||||
if !callerDeclaredTools {
|
||||
if choice, exists := reqBody["tool_choice"]; !exists || shouldPinOpenAIWebSearchHistoryToolChoice(choice) {
|
||||
reqBody["tool_choice"] = "none"
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ensureOpenAIOAuthWebSearchToolForHistoryBody is the raw-body variant used by
|
||||
// the passthrough and WebSocket paths; it avoids decoding the whole body.
|
||||
func ensureOpenAIOAuthWebSearchToolForHistoryBody(body []byte, responsesLite bool) ([]byte, bool, error) {
|
||||
if len(body) == 0 || !bytes.Contains(body, []byte(openAIWebSearchCallItemType)) {
|
||||
return body, false, nil
|
||||
}
|
||||
input := gjson.GetBytes(body, "input")
|
||||
if !input.IsArray() {
|
||||
return body, false, nil
|
||||
}
|
||||
items := input.Array()
|
||||
hasWebSearchCall := false
|
||||
callerDeclaredTools := false
|
||||
additionalToolsIndex := -1
|
||||
itemTypes := make([]string, len(items))
|
||||
for i, item := range items {
|
||||
itemTypes[i] = strings.TrimSpace(item.Get("type").String())
|
||||
switch itemTypes[i] {
|
||||
case openAIWebSearchCallItemType:
|
||||
hasWebSearchCall = true
|
||||
case openAIAdditionalToolsItemType:
|
||||
itemTools := item.Get("tools")
|
||||
if gjsonToolsContainWebSearch(itemTools) {
|
||||
return body, false, nil
|
||||
}
|
||||
if itemTools.IsArray() && len(itemTools.Array()) > 0 {
|
||||
callerDeclaredTools = true
|
||||
}
|
||||
if additionalToolsIndex < 0 {
|
||||
additionalToolsIndex = i
|
||||
}
|
||||
}
|
||||
}
|
||||
if !hasWebSearchCall {
|
||||
return body, false, nil
|
||||
}
|
||||
tools := gjson.GetBytes(body, "tools")
|
||||
if gjsonToolsContainWebSearch(tools) {
|
||||
return body, false, nil
|
||||
}
|
||||
topLevelTools := tools.IsArray() && len(tools.Array()) > 0
|
||||
callerDeclaredTools = callerDeclaredTools || topLevelTools
|
||||
|
||||
var (
|
||||
next []byte
|
||||
err error
|
||||
)
|
||||
switch {
|
||||
case !responsesLite && topLevelTools:
|
||||
next, err = sjson.SetBytes(body, "tools.-1", cloneOpenAIWebSearchHistoryTool())
|
||||
case !responsesLite:
|
||||
next, err = sjson.SetBytes(body, "tools", []any{cloneOpenAIWebSearchHistoryTool()})
|
||||
case additionalToolsIndex >= 0 && items[additionalToolsIndex].Get("tools").IsArray():
|
||||
next, err = sjson.SetBytes(body, fmt.Sprintf("input.%d.tools.-1", additionalToolsIndex), cloneOpenAIWebSearchHistoryTool())
|
||||
case additionalToolsIndex >= 0:
|
||||
next, err = sjson.SetBytes(body, fmt.Sprintf("input.%d.tools", additionalToolsIndex), []any{cloneOpenAIWebSearchHistoryTool()})
|
||||
default:
|
||||
next, err = insertOpenAIAdditionalToolsItemRaw(body, items, openAIAdditionalToolsInsertIndex(itemTypes))
|
||||
}
|
||||
if err != nil {
|
||||
return body, false, fmt.Errorf("declare web_search tool for web_search_call history: %w", err)
|
||||
}
|
||||
if !callerDeclaredTools {
|
||||
choice := gjson.GetBytes(next, "tool_choice")
|
||||
if !choice.Exists() || choice.Type == gjson.Null || (choice.Type == gjson.String && shouldPinOpenAIWebSearchHistoryToolChoice(choice.String())) {
|
||||
next, err = sjson.SetBytes(next, "tool_choice", "none")
|
||||
if err != nil {
|
||||
return body, false, fmt.Errorf("pin tool_choice for web_search_call history: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return next, true, nil
|
||||
}
|
||||
|
||||
func insertOpenAIAdditionalToolsItemRaw(body []byte, items []gjson.Result, at int) ([]byte, error) {
|
||||
additional, err := marshalOpenAIUpstreamJSON(map[string]any{
|
||||
"type": openAIAdditionalToolsItemType,
|
||||
"role": openAIAdditionalToolsDefaultRole,
|
||||
"tools": []any{cloneOpenAIWebSearchHistoryTool()},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rawItems := make([][]byte, 0, len(items)+1)
|
||||
for i, item := range items {
|
||||
if i == at {
|
||||
rawItems = append(rawItems, additional)
|
||||
}
|
||||
rawItems = append(rawItems, []byte(item.Raw))
|
||||
}
|
||||
if at >= len(items) {
|
||||
rawItems = append(rawItems, additional)
|
||||
}
|
||||
raw := append([]byte{'['}, bytes.Join(rawItems, []byte{','})...)
|
||||
raw = append(raw, ']')
|
||||
return sjson.SetRawBytes(body, "input", raw)
|
||||
}
|
||||
|
||||
func gjsonToolsContainWebSearch(tools gjson.Result) bool {
|
||||
if !tools.IsArray() {
|
||||
return false
|
||||
}
|
||||
for _, tool := range tools.Array() {
|
||||
if isOpenAIWebSearchToolType(tool.Get("type").String()) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func cloneOpenAIWebSearchHistoryTool() map[string]any {
|
||||
tool := make(map[string]any, len(openAIWebSearchHistoryTool))
|
||||
for key, value := range openAIWebSearchHistoryTool {
|
||||
tool[key] = value
|
||||
}
|
||||
return tool
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// TestForward_OAuthWebSearchHistoryDeclaresTool drives the Codex compaction
|
||||
// shape (web_search_call history, tools:[]) through Forward and asserts the
|
||||
// body reaching chatgpt.com declares web_search (#7927): top-level for the
|
||||
// standard wire, input additional_tools for Responses Lite.
|
||||
func TestForward_OAuthWebSearchHistoryDeclaresTool(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
passthrough bool
|
||||
lite bool
|
||||
}{
|
||||
{"transform", false, false},
|
||||
{"passthrough", true, false},
|
||||
{"transform lite", false, true},
|
||||
{"passthrough lite", true, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
s := newAstraOAuthSetup(t, tc.passthrough)
|
||||
if tc.lite {
|
||||
s.c.Request.Header.Set(responsesLiteHeader, "true")
|
||||
}
|
||||
inner := `{"id":"resp_test","model":"gpt-5.5","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}`
|
||||
s.upstream.resp = &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(codexCompletedSSE(inner))),
|
||||
}
|
||||
body, err := sjson.SetRawBytes([]byte(openAIWebSearchHistoryCompactionBody), "input.-1", []byte(`{"type":"compaction_trigger"}`))
|
||||
require.NoError(t, err)
|
||||
|
||||
result, err := s.svc.Forward(context.Background(), s.c, s.account, body)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotNil(t, s.upstream.lastReq)
|
||||
require.Equal(t, astraProCodexResponsesURL, s.upstream.lastReq.URL.String())
|
||||
|
||||
forwarded := s.upstream.lastBody
|
||||
require.Equal(t, "web_search_call", gjson.GetBytes(forwarded, "input.1.type").String())
|
||||
require.Equal(t, "none", gjson.GetBytes(forwarded, "tool_choice").String())
|
||||
items := gjson.GetBytes(forwarded, "input").Array()
|
||||
require.Equal(t, "compaction_trigger", items[len(items)-1].Get("type").String())
|
||||
if !tc.lite {
|
||||
tools := gjson.GetBytes(forwarded, "tools").Array()
|
||||
require.Len(t, tools, 1)
|
||||
require.Equal(t, "web_search", tools[0].Get("type").String())
|
||||
return
|
||||
}
|
||||
require.False(t, gjsonToolsContainWebSearch(gjson.GetBytes(forwarded, "tools")))
|
||||
additional := items[len(items)-2]
|
||||
require.Equal(t, "additional_tools", additional.Get("type").String())
|
||||
require.Equal(t, "web_search", additional.Get("tools.0.type").String())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// Codex local compaction replays hosted web_search_call history with tools:[];
|
||||
// ChatGPT then fails with "response protection is unavailable" (#7927).
|
||||
const openAIWebSearchHistoryCompactionBody = `{"model":"gpt-5.5","instructions":"x","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"look it up"}]},{"type":"web_search_call","id":"ws_123","status":"completed","action":{"type":"search","query":"kwin inputmethod"}},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"found"}]},{"type":"message","role":"user","content":[{"type":"input_text","text":"summarize"}]}],"tools":[],"tool_choice":"auto","parallel_tool_calls":false,"stream":true,"store":false}`
|
||||
|
||||
func TestOAuthWebSearchHistoryToolAcrossPaths(t *testing.T) {
|
||||
oauth := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
|
||||
transform := func(compact bool) func([]byte) ([]byte, bool, error) {
|
||||
return func(b []byte) ([]byte, bool, error) {
|
||||
var req map[string]any
|
||||
if err := json.Unmarshal(b, &req); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
result := applyCodexOAuthTransform(req, true, compact)
|
||||
out, err := json.Marshal(req)
|
||||
return out, result.Modified, err
|
||||
}
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
normalize func([]byte) ([]byte, bool, error)
|
||||
inject bool
|
||||
}{
|
||||
{"transformed OAuth", transform(false), true},
|
||||
{"transformed OAuth compact", transform(true), false},
|
||||
{"OAuth websocket", func(b []byte) ([]byte, bool, error) {
|
||||
return normalizeOpenAIResponsesWebSocketCompatibilityBody(b, oauth, false)
|
||||
}, true},
|
||||
{"OAuth passthrough compact", func(b []byte) ([]byte, bool, error) {
|
||||
return normalizeOpenAIResponsesCompatibilityBodyWithOptions(b, oauth, openAIResponsesCompatibilityOptions{Compact: true})
|
||||
}, false},
|
||||
{"API key websocket", func(b []byte) ([]byte, bool, error) {
|
||||
return normalizeOpenAIResponsesWebSocketCompatibilityBody(b, &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, false)
|
||||
}, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
out, _, err := tt.normalize([]byte(openAIWebSearchHistoryCompactionBody))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "web_search_call", gjson.GetBytes(out, "input.1.type").String())
|
||||
if !tt.inject {
|
||||
require.False(t, gjsonToolsContainWebSearch(gjson.GetBytes(out, "tools")))
|
||||
return
|
||||
}
|
||||
tools := gjson.GetBytes(out, "tools").Array()
|
||||
require.Len(t, tools, 1)
|
||||
require.Equal(t, "web_search", tools[0].Get("type").String())
|
||||
require.False(t, tools[0].Get("external_web_access").Bool())
|
||||
require.True(t, tools[0].Get("external_web_access").Exists())
|
||||
require.Equal(t, "none", gjson.GetBytes(out, "tool_choice").String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureOpenAIOAuthWebSearchToolForHistory(t *testing.T) {
|
||||
const (
|
||||
user = `{"type":"message","role":"user","content":[{"type":"input_text","text":"q"}]}`
|
||||
search = `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q"}}`
|
||||
trigger = `{"type":"compaction_trigger"}`
|
||||
history = `[` + user + `,` + search + `]`
|
||||
)
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
lite bool
|
||||
changed bool
|
||||
toolsPath string
|
||||
toolCount int
|
||||
toolChoice string
|
||||
itemTypes []string
|
||||
}{
|
||||
{"tools absent", `{"input":` + history + `}`, false, true, "tools", 1, "none", nil},
|
||||
{"tools null", `{"input":` + history + `,"tools":null,"tool_choice":null}`, false, true, "tools", 1, "none", nil},
|
||||
{"explicit none kept", `{"input":` + history + `,"tools":[],"tool_choice":"none"}`, false, true, "tools", 1, "none", nil},
|
||||
{"required not rewritten", `{"input":` + history + `,"tools":[],"tool_choice":"required"}`, false, true, "tools", 1, "required", nil},
|
||||
{"caller tools keep choice", `{"input":` + history + `,"tools":[{"type":"function","name":"echo"}],"tool_choice":"auto"}`, false, true, "tools", 2, "auto", nil},
|
||||
{"web_search already declared", `{"input":` + history + `,"tools":[{"type":"web_search"}]}`, false, false, "", 0, "", nil},
|
||||
{"web_search_preview declared", `{"input":` + history + `,"tools":[{"type":"web_search_preview"}]}`, false, false, "", 0, "", nil},
|
||||
{"declared via additional_tools", `{"input":[{"type":"additional_tools","tools":[{"type":"web_search"}]},` + search + `]}`, false, false, "", 0, "", nil},
|
||||
{"no web_search_call item", `{"input":[{"type":"message","role":"user","content":"web_search_call"}],"tools":[]}`, false, false, "", 0, "", nil},
|
||||
{"string input", `{"input":"web_search_call"}`, false, false, "", 0, "", nil},
|
||||
{"lite inserts before compaction trigger", `{"input":[` + user + `,` + search + `,` + trigger + `]}`, true, true, "input.2.tools", 1, "none",
|
||||
[]string{"message", "web_search_call", "additional_tools", "compaction_trigger"}},
|
||||
{"lite appends without trigger", `{"input":` + history + `,"tool_choice":"auto"}`, true, true, "input.2.tools", 1, "none",
|
||||
[]string{"message", "web_search_call", "additional_tools"}},
|
||||
{"lite extends caller additional_tools", `{"input":[{"type":"additional_tools","role":"developer","tools":[{"type":"function","name":"echo"}]},` + search + `,` + trigger + `],"tool_choice":"auto"}`, true, true, "input.0.tools", 2, "auto",
|
||||
[]string{"additional_tools", "web_search_call", "compaction_trigger"}},
|
||||
{"lite fills empty additional_tools", `{"input":[{"type":"additional_tools","role":"developer"},` + search + `]}`, true, true, "input.0.tools", 1, "none",
|
||||
[]string{"additional_tools", "web_search_call"}},
|
||||
{"lite keeps top-level tools untouched", `{"input":` + history + `,"tools":[{"type":"function","name":"echo"}]}`, true, true, "input.2.tools", 1, "",
|
||||
[]string{"message", "web_search_call", "additional_tools"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
out, changed, err := ensureOpenAIOAuthWebSearchToolForHistoryBody([]byte(tt.body), tt.lite)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.changed, changed)
|
||||
var req map[string]any
|
||||
require.NoError(t, json.Unmarshal([]byte(tt.body), &req))
|
||||
require.Equal(t, tt.changed, ensureOpenAIOAuthWebSearchToolForHistory(req, tt.lite))
|
||||
if !tt.changed {
|
||||
require.JSONEq(t, tt.body, string(out))
|
||||
return
|
||||
}
|
||||
require.True(t, gjson.ValidBytes(out))
|
||||
tools := gjson.GetBytes(out, tt.toolsPath).Array()
|
||||
require.Len(t, tools, tt.toolCount)
|
||||
require.Equal(t, "web_search", tools[len(tools)-1].Get("type").String())
|
||||
require.Equal(t, tt.toolChoice, gjson.GetBytes(out, "tool_choice").String())
|
||||
if tt.lite {
|
||||
require.False(t, gjsonToolsContainWebSearch(gjson.GetBytes(out, "tools")), "Lite rejects top-level hosted tools")
|
||||
var types []string
|
||||
for _, item := range gjson.GetBytes(out, "input").Array() {
|
||||
types = append(types, item.Get("type").String())
|
||||
}
|
||||
require.Equal(t, tt.itemTypes, types)
|
||||
}
|
||||
|
||||
// The map variant used by the Codex transform must agree.
|
||||
mapOut, err := json.Marshal(req)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, string(out), string(mapOut))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureOpenAIOAuthWebSearchToolForHistoryDoesNotShareToolMap(t *testing.T) {
|
||||
first := map[string]any{"input": []any{map[string]any{"type": "web_search_call"}}}
|
||||
second := map[string]any{"input": []any{map[string]any{"type": "web_search_call"}}}
|
||||
require.True(t, ensureOpenAIOAuthWebSearchToolForHistory(first, false))
|
||||
require.True(t, ensureOpenAIOAuthWebSearchToolForHistory(second, false))
|
||||
firstTools, ok := first["tools"].([]any)
|
||||
require.True(t, ok)
|
||||
firstTool, ok := firstTools[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
firstTool["external_web_access"] = true
|
||||
secondTools, ok := second["tools"].([]any)
|
||||
require.True(t, ok)
|
||||
secondTool, ok := secondTools[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, false, secondTool["external_web_access"])
|
||||
require.Equal(t, false, openAIWebSearchHistoryTool["external_web_access"])
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
@@ -19,9 +20,9 @@ const (
|
||||
// the UI does not pick a model. glm-5.3 is a Chat Completions catalog ID.
|
||||
DefaultOpenCodeGoTestModel = "glm-5.3"
|
||||
|
||||
openCodeGoProtocolRulesKey = "protocol_rules"
|
||||
maxOpenCodeGoProtocolRules = 64
|
||||
maxOpenCodeGoProtocolPatternLength = 128
|
||||
protocolRulesCredentialKey = "protocol_rules"
|
||||
maxProtocolRules = 64
|
||||
maxProtocolRulePatternLength = 128
|
||||
)
|
||||
|
||||
// DefaultOpenCodeGoModelIDs 是官方文档当前公开的模型 ID 目录,
|
||||
@@ -101,16 +102,31 @@ func writeOpenCodeUnsupportedModelError(c *gin.Context, isAnthropic bool, model
|
||||
return fmt.Errorf("opencode unsupported model: %s", model)
|
||||
}
|
||||
|
||||
// OpenCodeGoProtocolRule is one model-pattern → native protocol mapping.
|
||||
// ProtocolRule is one model-pattern → native protocol mapping.
|
||||
// Pattern is an exact ID or a suffix glob (foo* / *). First match wins.
|
||||
type OpenCodeGoProtocolRule struct {
|
||||
type ProtocolRule struct {
|
||||
Pattern string `json:"pattern"`
|
||||
Protocol string `json:"protocol"`
|
||||
// Protocols 是命中模型支持的全部原生协议,首项即 Protocol(首选);为空表示只支持
|
||||
// Protocol。入站协议在其中时同协议直通,否则走首选协议(见 resolveModelRoutedProtocolFor)。
|
||||
Protocols []string `json:"protocols,omitempty"`
|
||||
}
|
||||
|
||||
// normalizeProtocolSet 返回以 preferred 开头、去重且只含原生协议的协议集合。
|
||||
func normalizeProtocolSet(preferred string, protocols []string) []string {
|
||||
set := []string{preferred}
|
||||
for _, protocol := range protocols {
|
||||
if !isNativeUpstreamProtocol(protocol) || slices.Contains(set, protocol) {
|
||||
continue
|
||||
}
|
||||
set = append(set, protocol)
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
// DefaultOpenCodeGoProtocolRules is the built-in adaptive routing table for Go.
|
||||
func DefaultOpenCodeGoProtocolRules() []OpenCodeGoProtocolRule {
|
||||
return []OpenCodeGoProtocolRule{
|
||||
func DefaultOpenCodeGoProtocolRules() []ProtocolRule {
|
||||
return []ProtocolRule{
|
||||
{Pattern: "grok-*", Protocol: APIProtocolResponses},
|
||||
{Pattern: "gpt-*", Protocol: APIProtocolResponses},
|
||||
{Pattern: "muse-spark-*", Protocol: APIProtocolResponses},
|
||||
@@ -122,8 +138,8 @@ func DefaultOpenCodeGoProtocolRules() []OpenCodeGoProtocolRule {
|
||||
// DefaultOpenCodeZenProtocolRules 对齐 https://opencode.ai/docs/zen/ 端点表:
|
||||
// GPT/Grok/Muse Spark → Responses,Claude/Qwen(除 qwen3.8-max) → Anthropic,
|
||||
// qwen3.8-max 及其余模型 → Chat Completions。
|
||||
func DefaultOpenCodeZenProtocolRules() []OpenCodeGoProtocolRule {
|
||||
return []OpenCodeGoProtocolRule{
|
||||
func DefaultOpenCodeZenProtocolRules() []ProtocolRule {
|
||||
return []ProtocolRule{
|
||||
{Pattern: "grok-*", Protocol: APIProtocolResponses},
|
||||
{Pattern: "gpt-*", Protocol: APIProtocolResponses},
|
||||
{Pattern: "muse-spark-*", Protocol: APIProtocolResponses},
|
||||
@@ -133,14 +149,7 @@ func DefaultOpenCodeZenProtocolRules() []OpenCodeGoProtocolRule {
|
||||
}
|
||||
}
|
||||
|
||||
func defaultOpenCodeProtocolRules(mode string) []OpenCodeGoProtocolRule {
|
||||
if mode == AccountModeZen {
|
||||
return DefaultOpenCodeZenProtocolRules()
|
||||
}
|
||||
return DefaultOpenCodeGoProtocolRules()
|
||||
}
|
||||
|
||||
func isNativeOpenCodeGoProtocol(protocol string) bool {
|
||||
func isNativeUpstreamProtocol(protocol string) bool {
|
||||
switch protocol {
|
||||
case APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses:
|
||||
return true
|
||||
@@ -149,7 +158,7 @@ func isNativeOpenCodeGoProtocol(protocol string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
func openCodeGoPatternMatches(pattern, model string) bool {
|
||||
func protocolRulePatternMatches(pattern, model string) bool {
|
||||
pattern = strings.ToLower(strings.TrimSpace(pattern))
|
||||
model = normalizeOpenCodeGoModelID(model)
|
||||
if pattern == "" || model == "" {
|
||||
@@ -164,49 +173,51 @@ func openCodeGoPatternMatches(pattern, model string) bool {
|
||||
return model == pattern
|
||||
}
|
||||
|
||||
func matchOpenCodeGoProtocolRules(model string, rules []OpenCodeGoProtocolRule) string {
|
||||
for _, rule := range rules {
|
||||
if !isNativeOpenCodeGoProtocol(rule.Protocol) {
|
||||
continue
|
||||
}
|
||||
if openCodeGoPatternMatches(rule.Pattern, model) {
|
||||
return rule.Protocol
|
||||
}
|
||||
// matchProtocolRules 返回首条命中规则的首选协议;未命中时为 Chat Completions。
|
||||
func matchProtocolRules(model string, rules []ProtocolRule) string {
|
||||
if set, ok := matchProtocolRuleSet(model, rules); ok {
|
||||
return set[0]
|
||||
}
|
||||
return APIProtocolChatCompletions
|
||||
}
|
||||
|
||||
// OpenCodeGoModelProtocol 返回内置默认表下模型对应的原生上游协议。
|
||||
// 未命中时为 Chat Completions。账号自定义 protocol_rules 见
|
||||
// ResolveOpenCodeGoUpstreamProtocol。
|
||||
func OpenCodeGoModelProtocol(model string) string {
|
||||
return matchOpenCodeGoProtocolRules(model, DefaultOpenCodeGoProtocolRules())
|
||||
// matchProtocolRuleSet 返回首条命中规则支持的协议集合(首项为首选);未命中时 ok=false。
|
||||
func matchProtocolRuleSet(model string, rules []ProtocolRule) ([]string, bool) {
|
||||
for _, rule := range rules {
|
||||
if !isNativeUpstreamProtocol(rule.Protocol) {
|
||||
continue
|
||||
}
|
||||
if protocolRulePatternMatches(rule.Pattern, model) {
|
||||
return normalizeProtocolSet(rule.Protocol, rule.Protocols), true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (a *Account) openCodeGoProtocolRules() ([]OpenCodeGoProtocolRule, bool) {
|
||||
func (a *Account) configuredProtocolRules() ([]ProtocolRule, bool) {
|
||||
if a == nil || a.Credentials == nil {
|
||||
return nil, false
|
||||
}
|
||||
raw, ok := a.Credentials[openCodeGoProtocolRulesKey]
|
||||
raw, ok := a.Credentials[protocolRulesCredentialKey]
|
||||
if !ok || raw == nil {
|
||||
return nil, false
|
||||
}
|
||||
rules, err := parseOpenCodeGoProtocolRules(raw)
|
||||
rules, err := parseProtocolRules(raw)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return rules, true
|
||||
}
|
||||
|
||||
func parseOpenCodeGoProtocolRules(raw any) ([]OpenCodeGoProtocolRule, error) {
|
||||
items, err := openCodeGoProtocolRuleItems(raw)
|
||||
func parseProtocolRules(raw any) ([]ProtocolRule, error) {
|
||||
items, err := protocolRuleItems(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(items) > maxOpenCodeGoProtocolRules {
|
||||
return nil, fmt.Errorf("protocol_rules supports at most %d entries", maxOpenCodeGoProtocolRules)
|
||||
if len(items) > maxProtocolRules {
|
||||
return nil, fmt.Errorf("protocol_rules supports at most %d entries", maxProtocolRules)
|
||||
}
|
||||
rules := make([]OpenCodeGoProtocolRule, 0, len(items))
|
||||
rules := make([]ProtocolRule, 0, len(items))
|
||||
for i, item := range items {
|
||||
entry, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
@@ -214,20 +225,59 @@ func parseOpenCodeGoProtocolRules(raw any) ([]OpenCodeGoProtocolRule, error) {
|
||||
}
|
||||
pattern, _ := entry["pattern"].(string)
|
||||
protocol, _ := entry["protocol"].(string)
|
||||
pattern, err := normalizeOpenCodeGoProtocolPattern(pattern)
|
||||
pattern, err := normalizeProtocolRulePattern(pattern)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("protocol_rules[%d]: %w", i, err)
|
||||
}
|
||||
protocols, err := protocolRuleProtocols(entry["protocols"])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("protocol_rules[%d]: %w", i, err)
|
||||
}
|
||||
protocol = strings.TrimSpace(protocol)
|
||||
if !isNativeOpenCodeGoProtocol(protocol) {
|
||||
if protocol == "" && len(protocols) > 0 {
|
||||
protocol = protocols[0]
|
||||
}
|
||||
if !isNativeUpstreamProtocol(protocol) {
|
||||
return nil, fmt.Errorf("protocol_rules[%d]: protocol must be chat_completions, anthropic, or responses", i)
|
||||
}
|
||||
rules = append(rules, OpenCodeGoProtocolRule{Pattern: pattern, Protocol: protocol})
|
||||
rule := ProtocolRule{Pattern: pattern, Protocol: protocol}
|
||||
if set := normalizeProtocolSet(protocol, protocols); len(set) > 1 {
|
||||
rule.Protocols = set
|
||||
}
|
||||
rules = append(rules, rule)
|
||||
}
|
||||
return rules, nil
|
||||
}
|
||||
|
||||
func openCodeGoProtocolRuleItems(raw any) ([]any, error) {
|
||||
// protocolRuleProtocols 解析规则的 protocols 列表(可缺省);其中每一项都须为原生协议。
|
||||
func protocolRuleProtocols(raw any) ([]string, error) {
|
||||
if raw == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var items []any
|
||||
switch values := raw.(type) {
|
||||
case []any:
|
||||
items = values
|
||||
case []string:
|
||||
for _, value := range values {
|
||||
items = append(items, value)
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("protocols must be an array")
|
||||
}
|
||||
out := make([]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
protocol, _ := item.(string)
|
||||
protocol = strings.TrimSpace(protocol)
|
||||
if !isNativeUpstreamProtocol(protocol) {
|
||||
return nil, fmt.Errorf("protocols must only contain chat_completions, anthropic, or responses")
|
||||
}
|
||||
out = append(out, protocol)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func protocolRuleItems(raw any) ([]any, error) {
|
||||
switch items := raw.(type) {
|
||||
case []any:
|
||||
return items, nil
|
||||
@@ -242,12 +292,12 @@ func openCodeGoProtocolRuleItems(raw any) ([]any, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeOpenCodeGoProtocolPattern(pattern string) (string, error) {
|
||||
func normalizeProtocolRulePattern(pattern string) (string, error) {
|
||||
pattern = strings.ToLower(strings.TrimSpace(pattern))
|
||||
if pattern == "" {
|
||||
return "", fmt.Errorf("pattern is required")
|
||||
}
|
||||
if len(pattern) > maxOpenCodeGoProtocolPatternLength {
|
||||
if len(pattern) > maxProtocolRulePatternLength {
|
||||
return "", fmt.Errorf("pattern is too long")
|
||||
}
|
||||
if strings.ContainsAny(pattern, " \t") {
|
||||
@@ -260,28 +310,36 @@ func normalizeOpenCodeGoProtocolPattern(pattern string) (string, error) {
|
||||
return pattern, nil
|
||||
}
|
||||
|
||||
// NormalizeOpenCodeGoProtocolRulesCredentials 校验并原地规范化 credentials.protocol_rules。
|
||||
// NormalizeProtocolRulesCredentials 校验并原地规范化 credentials.protocol_rules。
|
||||
// 未携带该字段时为 no-op,使旧账号继续使用内置默认表。
|
||||
func NormalizeOpenCodeGoProtocolRulesCredentials(credentials map[string]any) error {
|
||||
func NormalizeProtocolRulesCredentials(credentials map[string]any) error {
|
||||
if credentials == nil {
|
||||
return nil
|
||||
}
|
||||
raw, ok := credentials[openCodeGoProtocolRulesKey]
|
||||
raw, ok := credentials[protocolRulesCredentialKey]
|
||||
if !ok || raw == nil {
|
||||
return nil
|
||||
}
|
||||
rules, err := parseOpenCodeGoProtocolRules(raw)
|
||||
rules, err := parseProtocolRules(raw)
|
||||
if err != nil {
|
||||
return infraerrors.New(http.StatusBadRequest, "INVALID_OPENCODE_GO_PROTOCOL_RULES", err.Error())
|
||||
}
|
||||
encoded := make([]any, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
encoded = append(encoded, map[string]any{
|
||||
item := map[string]any{
|
||||
"pattern": rule.Pattern,
|
||||
"protocol": rule.Protocol,
|
||||
})
|
||||
}
|
||||
if len(rule.Protocols) > 1 {
|
||||
protocols := make([]any, 0, len(rule.Protocols))
|
||||
for _, protocol := range rule.Protocols {
|
||||
protocols = append(protocols, protocol)
|
||||
}
|
||||
item["protocols"] = protocols
|
||||
}
|
||||
encoded = append(encoded, item)
|
||||
}
|
||||
credentials[openCodeGoProtocolRulesKey] = encoded
|
||||
credentials[protocolRulesCredentialKey] = encoded
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -308,56 +366,10 @@ func (a *Account) IsOpenCodeGoPlan() bool {
|
||||
return a.GetOpenCodeAccountMode() == AccountModeGo
|
||||
}
|
||||
|
||||
func (a *Account) openCodeDefaultChatBaseURL() string {
|
||||
if a.IsOpenCodeZen() {
|
||||
return DefaultOpenCodeZenBaseURL
|
||||
}
|
||||
return DefaultOpenCodeGoBaseURL
|
||||
}
|
||||
|
||||
func (a *Account) openCodeDefaultAnthropicBaseURL() string {
|
||||
if a.IsOpenCodeZen() {
|
||||
return DefaultOpenCodeZenAnthropicBaseURL
|
||||
}
|
||||
return DefaultOpenCodeGoAnthropicBaseURL
|
||||
}
|
||||
|
||||
func (a *Account) IsMultiProtocolAPIKey() bool {
|
||||
return a != nil && IsMultiProtocolAPIKeyProvider(a.Platform)
|
||||
}
|
||||
|
||||
// openCodeGoNativeProtocol 返回 OpenCode Go 实际上游协议。
|
||||
// 规则未命中、空值或未知协议一律兜底 Chat Completions,避免落入 Responses 转换链。
|
||||
func openCodeGoNativeProtocol(account *Account, model string) string {
|
||||
if account == nil {
|
||||
return APIProtocolChatCompletions
|
||||
}
|
||||
switch proto := account.ResolveOpenCodeGoUpstreamProtocol(model); proto {
|
||||
case APIProtocolAnthropic, APIProtocolResponses:
|
||||
return proto
|
||||
default:
|
||||
return APIProtocolChatCompletions
|
||||
}
|
||||
}
|
||||
|
||||
// ResolveOpenCodeGoUpstreamProtocol 按账号协议配置与模型规则决定上游协议。
|
||||
// 显式 pinned 协议优先;adaptive(默认)先走 credentials.protocol_rules,
|
||||
// 未配置时回落内置默认表;已配置但未命中则走 Chat Completions。
|
||||
func (a *Account) ResolveOpenCodeGoUpstreamProtocol(model string) string {
|
||||
if a == nil || !a.IsOpenCodeGo() {
|
||||
return ""
|
||||
}
|
||||
switch a.GetAPIProtocol() {
|
||||
case APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses:
|
||||
return a.GetAPIProtocol()
|
||||
default:
|
||||
if rules, present := a.openCodeGoProtocolRules(); present {
|
||||
return matchOpenCodeGoProtocolRules(model, rules)
|
||||
}
|
||||
return matchOpenCodeGoProtocolRules(model, defaultOpenCodeProtocolRules(a.GetOpenCodeAccountMode()))
|
||||
}
|
||||
}
|
||||
|
||||
// openCodeGoQuotaURL 根据 base_url 解析 OpenCode Go 额度端点。
|
||||
// /zen/go/v1(Chat 协议默认,DefaultOpenCodeGoBaseURL)与 /zen/go
|
||||
// (Anthropic 协议默认,DefaultOpenCodeGoAnthropicBaseURL)两种 base 统一
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestOpenCodeGoModelProtocol(t *testing.T) {
|
||||
func TestOpenCodeGoDefaultProtocolRules(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
model string
|
||||
@@ -28,120 +28,119 @@ func TestOpenCodeGoModelProtocol(t *testing.T) {
|
||||
{"unknown-model", APIProtocolChatCompletions},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
require.Equal(t, tc.want, OpenCodeGoModelProtocol(tc.model), "model=%s", tc.model)
|
||||
require.Equal(t, tc.want, matchProtocolRules(tc.model, DefaultOpenCodeGoProtocolRules()), "model=%s", tc.model)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveOpenCodeGoUpstreamProtocol(t *testing.T) {
|
||||
func TestOpenCodeGoModelRoutedProtocol(t *testing.T) {
|
||||
t.Parallel()
|
||||
adaptive := &Account{Platform: PlatformOpenCodeGo, Credentials: map[string]any{"api_protocol": APIProtocolAdaptive}}
|
||||
require.Equal(t, APIProtocolAnthropic, adaptive.ResolveOpenCodeGoUpstreamProtocol("minimax-m3"))
|
||||
require.Equal(t, APIProtocolResponses, adaptive.ResolveOpenCodeGoUpstreamProtocol("grok-4.6"))
|
||||
require.Equal(t, APIProtocolChatCompletions, adaptive.ResolveOpenCodeGoUpstreamProtocol("glm-5.3"))
|
||||
require.Equal(t, APIProtocolAnthropic, adaptive.resolveModelRoutedProtocol("minimax-m3"))
|
||||
require.Equal(t, APIProtocolResponses, adaptive.resolveModelRoutedProtocol("grok-4.6"))
|
||||
require.Equal(t, APIProtocolChatCompletions, adaptive.resolveModelRoutedProtocol("glm-5.3"))
|
||||
|
||||
pinned := &Account{Platform: PlatformOpenCodeGo, Credentials: map[string]any{"api_protocol": APIProtocolChatCompletions}}
|
||||
require.Equal(t, APIProtocolChatCompletions, pinned.ResolveOpenCodeGoUpstreamProtocol("minimax-m3"))
|
||||
require.Equal(t, APIProtocolChatCompletions, pinned.resolveModelRoutedProtocol("minimax-m3"))
|
||||
|
||||
empty := &Account{Platform: PlatformOpenCodeGo}
|
||||
require.Equal(t, APIProtocolResponses, empty.ResolveOpenCodeGoUpstreamProtocol("gpt-5.6-luna"))
|
||||
require.Equal(t, APIProtocolResponses, empty.resolveModelRoutedProtocol("gpt-5.6-luna"))
|
||||
require.Equal(t, AccountModeGo, empty.GetOpenCodeAccountMode())
|
||||
require.True(t, empty.IsOpenCodeGoPlan())
|
||||
|
||||
zen := &Account{Platform: PlatformOpenCodeGo, Credentials: map[string]any{"account_mode": AccountModeZen, "api_protocol": APIProtocolAdaptive}}
|
||||
require.Equal(t, APIProtocolChatCompletions, zen.ResolveOpenCodeGoUpstreamProtocol("minimax-m3"))
|
||||
require.Equal(t, APIProtocolAnthropic, zen.ResolveOpenCodeGoUpstreamProtocol("claude-opus-4-6"))
|
||||
require.Equal(t, APIProtocolChatCompletions, zen.ResolveOpenCodeGoUpstreamProtocol("qwen3.8-max"))
|
||||
require.Equal(t, APIProtocolAnthropic, zen.ResolveOpenCodeGoUpstreamProtocol("qwen3.8-flash"))
|
||||
require.Equal(t, APIProtocolAnthropic, zen.ResolveOpenCodeGoUpstreamProtocol("qwen3.7-max"))
|
||||
require.Equal(t, APIProtocolChatCompletions, zen.resolveModelRoutedProtocol("minimax-m3"))
|
||||
require.Equal(t, APIProtocolAnthropic, zen.resolveModelRoutedProtocol("claude-opus-4-6"))
|
||||
require.Equal(t, APIProtocolChatCompletions, zen.resolveModelRoutedProtocol("qwen3.8-max"))
|
||||
require.Equal(t, APIProtocolAnthropic, zen.resolveModelRoutedProtocol("qwen3.8-flash"))
|
||||
require.Equal(t, APIProtocolAnthropic, zen.resolveModelRoutedProtocol("qwen3.7-max"))
|
||||
require.Equal(t, DefaultOpenCodeZenBaseURL, zen.GetOpenAIBaseURL())
|
||||
|
||||
goAccount := &Account{Platform: PlatformOpenCodeGo, Credentials: map[string]any{"account_mode": AccountModeGo, "api_protocol": APIProtocolAdaptive}}
|
||||
require.Equal(t, APIProtocolAnthropic, goAccount.ResolveOpenCodeGoUpstreamProtocol("qwen3.8-max"))
|
||||
require.Equal(t, APIProtocolAnthropic, goAccount.resolveModelRoutedProtocol("qwen3.8-max"))
|
||||
|
||||
require.Equal(t, "", (&Account{Platform: PlatformKimi}).ResolveOpenCodeGoUpstreamProtocol("glm-5.3"))
|
||||
require.False(t, (&Account{Platform: PlatformKimi}).routesByModel())
|
||||
}
|
||||
|
||||
func TestResolveOpenCodeGoUpstreamProtocolUsesAccountRules(t *testing.T) {
|
||||
func TestOpenCodeGoModelRoutedProtocolUsesAccountRules(t *testing.T) {
|
||||
t.Parallel()
|
||||
account := &Account{
|
||||
Platform: PlatformOpenCodeGo,
|
||||
Credentials: map[string]any{
|
||||
"api_protocol": APIProtocolAdaptive,
|
||||
openCodeGoProtocolRulesKey: []any{
|
||||
protocolRulesCredentialKey: []any{
|
||||
map[string]any{"pattern": "grok-*", "protocol": APIProtocolChatCompletions},
|
||||
map[string]any{"pattern": "deepseek-v4-flash", "protocol": APIProtocolResponses},
|
||||
map[string]any{"pattern": "qwen*", "protocol": APIProtocolAnthropic},
|
||||
},
|
||||
},
|
||||
}
|
||||
require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("grok-4.6"))
|
||||
require.Equal(t, APIProtocolResponses, account.ResolveOpenCodeGoUpstreamProtocol("deepseek-v4-flash"))
|
||||
require.Equal(t, APIProtocolAnthropic, account.ResolveOpenCodeGoUpstreamProtocol("qwen3.8-max"))
|
||||
require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("glm-5.3"))
|
||||
require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("minimax-m3"))
|
||||
require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("grok-4.6"))
|
||||
require.Equal(t, APIProtocolResponses, account.resolveModelRoutedProtocol("deepseek-v4-flash"))
|
||||
require.Equal(t, APIProtocolAnthropic, account.resolveModelRoutedProtocol("qwen3.8-max"))
|
||||
require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("glm-5.3"))
|
||||
require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("minimax-m3"))
|
||||
}
|
||||
|
||||
func TestResolveOpenCodeGoUpstreamProtocolEmptyRulesAreAllChatCompletions(t *testing.T) {
|
||||
func TestOpenCodeGoModelRoutedProtocolEmptyRulesAreAllChatCompletions(t *testing.T) {
|
||||
t.Parallel()
|
||||
account := &Account{
|
||||
Platform: PlatformOpenCodeGo,
|
||||
Credentials: map[string]any{
|
||||
openCodeGoProtocolRulesKey: []any{},
|
||||
protocolRulesCredentialKey: []any{},
|
||||
},
|
||||
}
|
||||
require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("grok-4.6"))
|
||||
require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("minimax-m3"))
|
||||
require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("grok-4.6"))
|
||||
require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("minimax-m3"))
|
||||
}
|
||||
|
||||
func TestResolveOpenCodeGoUpstreamProtocolFirstMatchWins(t *testing.T) {
|
||||
func TestOpenCodeGoModelRoutedProtocolFirstMatchWins(t *testing.T) {
|
||||
t.Parallel()
|
||||
account := &Account{
|
||||
Platform: PlatformOpenCodeGo,
|
||||
Credentials: map[string]any{
|
||||
openCodeGoProtocolRulesKey: []any{
|
||||
protocolRulesCredentialKey: []any{
|
||||
map[string]any{"pattern": "gpt-5.6-luna", "protocol": APIProtocolChatCompletions},
|
||||
map[string]any{"pattern": "gpt-*", "protocol": APIProtocolResponses},
|
||||
},
|
||||
},
|
||||
}
|
||||
require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("gpt-5.6-luna"))
|
||||
require.Equal(t, APIProtocolResponses, account.ResolveOpenCodeGoUpstreamProtocol("gpt-5.4"))
|
||||
require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("gpt-5.6-luna"))
|
||||
require.Equal(t, APIProtocolResponses, account.resolveModelRoutedProtocol("gpt-5.4"))
|
||||
}
|
||||
|
||||
func TestOpenCodeGoNativeProtocolUnmatchedFallsBackToChatCompletions(t *testing.T) {
|
||||
func TestOpenCodeGoUnmatchedFallsBackToChatCompletions(t *testing.T) {
|
||||
t.Parallel()
|
||||
withRules := &Account{
|
||||
Platform: PlatformOpenCodeGo,
|
||||
Credentials: map[string]any{
|
||||
"api_protocol": APIProtocolAdaptive,
|
||||
openCodeGoProtocolRulesKey: []any{
|
||||
protocolRulesCredentialKey: []any{
|
||||
map[string]any{"pattern": "grok-*", "protocol": APIProtocolResponses},
|
||||
map[string]any{"pattern": "gpt-*", "protocol": APIProtocolResponses},
|
||||
map[string]any{"pattern": "qwen*", "protocol": APIProtocolAnthropic},
|
||||
},
|
||||
},
|
||||
}
|
||||
require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(withRules, "deepseek-v4-flash"))
|
||||
require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(withRules, "glm-5.3"))
|
||||
require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(withRules, "omen-alpha"))
|
||||
require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(withRules, "kimi-k3"))
|
||||
require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(withRules, "unknown-model"))
|
||||
require.Equal(t, APIProtocolResponses, openCodeGoNativeProtocol(withRules, "grok-4.6"))
|
||||
require.Equal(t, APIProtocolAnthropic, openCodeGoNativeProtocol(withRules, "qwen3.8-flash"))
|
||||
require.Equal(t, APIProtocolChatCompletions, withRules.resolveModelRoutedProtocol("deepseek-v4-flash"))
|
||||
require.Equal(t, APIProtocolChatCompletions, withRules.resolveModelRoutedProtocol("glm-5.3"))
|
||||
require.Equal(t, APIProtocolChatCompletions, withRules.resolveModelRoutedProtocol("omen-alpha"))
|
||||
require.Equal(t, APIProtocolChatCompletions, withRules.resolveModelRoutedProtocol("kimi-k3"))
|
||||
require.Equal(t, APIProtocolChatCompletions, withRules.resolveModelRoutedProtocol("unknown-model"))
|
||||
require.Equal(t, APIProtocolResponses, withRules.resolveModelRoutedProtocol("grok-4.6"))
|
||||
require.Equal(t, APIProtocolAnthropic, withRules.resolveModelRoutedProtocol("qwen3.8-flash"))
|
||||
|
||||
defaults := &Account{Platform: PlatformOpenCodeGo}
|
||||
require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(defaults, "deepseek-v4-flash"))
|
||||
require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(nil, "grok-4.6"))
|
||||
require.Equal(t, APIProtocolChatCompletions, defaults.resolveModelRoutedProtocol("deepseek-v4-flash"))
|
||||
}
|
||||
|
||||
func TestParseOpenCodeGoProtocolRulesAcceptsTypedMaps(t *testing.T) {
|
||||
t.Parallel()
|
||||
rules, err := parseOpenCodeGoProtocolRules([]map[string]any{
|
||||
rules, err := parseProtocolRules([]map[string]any{
|
||||
{"pattern": "grok-*", "protocol": APIProtocolResponses},
|
||||
{"pattern": "qwen*", "protocol": APIProtocolAnthropic},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []OpenCodeGoProtocolRule{
|
||||
require.Equal(t, []ProtocolRule{
|
||||
{Pattern: "grok-*", Protocol: APIProtocolResponses},
|
||||
{Pattern: "qwen*", Protocol: APIProtocolAnthropic},
|
||||
}, rules)
|
||||
@@ -160,9 +159,9 @@ func TestShouldForwardOpenAIResponsesViaRawChatCompletions_OpenCodeGoIgnoresProb
|
||||
},
|
||||
}
|
||||
require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account))
|
||||
require.Equal(t, APIProtocolResponses, account.ResolveOpenCodeGoUpstreamProtocol("grok-4.6"))
|
||||
require.Equal(t, APIProtocolResponses, account.ResolveOpenCodeGoUpstreamProtocol("gpt-5.6-luna"))
|
||||
require.Equal(t, APIProtocolAnthropic, account.ResolveOpenCodeGoUpstreamProtocol("qwen3.8-flash"))
|
||||
require.Equal(t, APIProtocolResponses, account.resolveModelRoutedProtocol("grok-4.6"))
|
||||
require.Equal(t, APIProtocolResponses, account.resolveModelRoutedProtocol("gpt-5.6-luna"))
|
||||
require.Equal(t, APIProtocolAnthropic, account.resolveModelRoutedProtocol("qwen3.8-flash"))
|
||||
}
|
||||
|
||||
func TestStampOpenAIResponsesUpstreamEndpoint(t *testing.T) {
|
||||
@@ -178,31 +177,31 @@ func TestStampOpenAIResponsesUpstreamEndpoint(t *testing.T) {
|
||||
|
||||
func TestNormalizeOpenCodeGoProtocolRulesCredentials(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.NoError(t, NormalizeOpenCodeGoProtocolRulesCredentials(nil))
|
||||
require.NoError(t, NormalizeOpenCodeGoProtocolRulesCredentials(map[string]any{}))
|
||||
require.NoError(t, NormalizeProtocolRulesCredentials(nil))
|
||||
require.NoError(t, NormalizeProtocolRulesCredentials(map[string]any{}))
|
||||
|
||||
creds := map[string]any{
|
||||
openCodeGoProtocolRulesKey: []any{
|
||||
protocolRulesCredentialKey: []any{
|
||||
map[string]any{"pattern": " Grok-* ", "protocol": APIProtocolResponses},
|
||||
},
|
||||
}
|
||||
require.NoError(t, NormalizeOpenCodeGoProtocolRulesCredentials(creds))
|
||||
rules, ok := creds[openCodeGoProtocolRulesKey].([]any)
|
||||
require.NoError(t, NormalizeProtocolRulesCredentials(creds))
|
||||
rules, ok := creds[protocolRulesCredentialKey].([]any)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, rules)
|
||||
entry, ok := rules[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "grok-*", entry["pattern"])
|
||||
|
||||
err := NormalizeOpenCodeGoProtocolRulesCredentials(map[string]any{
|
||||
openCodeGoProtocolRulesKey: []any{
|
||||
err := NormalizeProtocolRulesCredentials(map[string]any{
|
||||
protocolRulesCredentialKey: []any{
|
||||
map[string]any{"pattern": "*grok", "protocol": APIProtocolResponses},
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
|
||||
err = NormalizeOpenCodeGoProtocolRulesCredentials(map[string]any{
|
||||
openCodeGoProtocolRulesKey: []any{
|
||||
err = NormalizeProtocolRulesCredentials(map[string]any{
|
||||
protocolRulesCredentialKey: []any{
|
||||
map[string]any{"pattern": "grok-*", "protocol": "adaptive"},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestOpenCodeUnsupportedModelsRejectMappedAliasesBeforeProtocolSelection(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, ingress := range routingMatrixIngresses() {
|
||||
for _, protocol := range []string{APIProtocolAdaptive, APIProtocolResponses, APIProtocolChatCompletions, APIProtocolAnthropic} {
|
||||
for _, mode := range []string{AccountModeGo, AccountModeZen} {
|
||||
t.Run(ingress.name+"/"+protocol+"/"+mode, func(t *testing.T) {
|
||||
account := &Account{ID: 105, Platform: PlatformOpenCodeGo, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "test-key", "api_protocol": protocol, "account_mode": mode,
|
||||
"model_mapping": map[string]any{"public-model": "gemini-3.8-flash"},
|
||||
"protocol_rules": []any{map[string]any{"pattern": "*", "protocol": APIProtocolChatCompletions}},
|
||||
}}
|
||||
body := (routingMatrixCase{ingress: ingress, model: "public-model"}).body()
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, ingress.path, bytes.NewReader(body))
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("unexpected upstream request")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
|
||||
err := ingress.forward(svc, c, account, body)
|
||||
|
||||
require.ErrorContains(t, err, "opencode unsupported model: gemini-3.8-flash")
|
||||
require.Equal(t, http.StatusBadRequest, recorder.Code)
|
||||
require.Empty(t, upstream.requests)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandCodeGeminiModelReachesUpstream(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, ingress := range routingMatrixIngresses() {
|
||||
t.Run(ingress.name, func(t *testing.T) {
|
||||
account := commandCodeTestAccount(106)
|
||||
account.Credentials["api_protocol"] = APIProtocolChatCompletions
|
||||
body := (routingMatrixCase{ingress: ingress, model: "gemini-3.8-flash"}).body()
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, ingress.path, bytes.NewReader(body))
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
|
||||
err := ingress.forward(svc, c, account, body)
|
||||
|
||||
require.Error(t, err)
|
||||
require.NotContains(t, err.Error(), "opencode unsupported model")
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "https://api.commandcode.ai/provider/v1/chat/completions", upstream.requests[0].URL.String())
|
||||
})
|
||||
}
|
||||
account := commandCodeTestAccount(107)
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
|
||||
c, _ := newTestContext()
|
||||
require.NoError(t, svc.testModelRoutedAccountConnection(c, account, "gemini-3.8-flash", "hi"))
|
||||
require.Len(t, upstream.requests, 1)
|
||||
}
|
||||
|
||||
func TestOpenCodeConnectionTestRejectsMappedUnsupportedModel(t *testing.T) {
|
||||
account := &Account{Platform: PlatformOpenCodeGo, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_protocol": APIProtocolChatCompletions,
|
||||
"model_mapping": map[string]any{"public-model": "jev-1.13"},
|
||||
}}
|
||||
c, _ := newTestContext()
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/test", nil).WithContext(context.Background())
|
||||
err := (&AccountTestService{}).testModelRoutedAccountConnection(c, account, "public-model", "hi")
|
||||
require.ErrorContains(t, err, "not supported on OpenCode standard gateway")
|
||||
require.ErrorContains(t, err, "jev-1.13")
|
||||
}
|
||||
@@ -128,11 +128,11 @@ func TestAccountTestService_OpenCodeUnsupportedModelReturnsError(t *testing.T) {
|
||||
}
|
||||
|
||||
svc := &AccountTestService{}
|
||||
err := svc.testOpenCodeGoAccountConnection(c, account, "gemini-3.8-flash", "hi")
|
||||
err := svc.testModelRoutedAccountConnection(c, account, "gemini-3.8-flash", "hi")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "not supported on OpenCode standard gateway")
|
||||
|
||||
err = svc.testOpenCodeGoAccountConnection(c, account, "jev-1.13", "hi")
|
||||
err = svc.testModelRoutedAccountConnection(c, account, "jev-1.13", "hi")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "not supported on OpenCode standard gateway")
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"sort"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
)
|
||||
|
||||
// PlatformCatalog 是前端使用的平台清单:domain 平台清单加上多协议供应商的
|
||||
// profile(接入模式、各协议默认基址、内置分流规则)。它被写成前端内置清单
|
||||
// frontend/src/constants/platformCatalog.builtin.json(见
|
||||
// TestFrontendBuiltinPlatformCatalogInSync),前端据此生成平台选项、展示名与
|
||||
// 多协议账号表单,新登记的平台只需重新生成该文件,无需修改前端代码。
|
||||
type PlatformCatalog struct {
|
||||
Platforms []PlatformCatalogEntry `json:"platforms"`
|
||||
// CompositePrecedence 是组合分组逐平台回退的顺序(先命中者生效)。
|
||||
CompositePrecedence []string `json:"composite_precedence"`
|
||||
}
|
||||
|
||||
// PlatformCatalogEntry 描述一个具体平台;MultiProtocol 仅多协议 API Key 供应商有值。
|
||||
type PlatformCatalogEntry struct {
|
||||
domain.PlatformSpec
|
||||
MultiProtocol *ProviderProfileInfo `json:"multi_protocol,omitempty"`
|
||||
}
|
||||
|
||||
// ProviderProfileInfo 是 ProviderProfile 的对外形状。
|
||||
type ProviderProfileInfo struct {
|
||||
DefaultMode string `json:"default_mode"`
|
||||
Routing ProviderRouting `json:"routing"`
|
||||
ResponsesPath string `json:"responses_path,omitempty"`
|
||||
// ModelCatalog 表示模型支持的协议由上游 /models 自动获取(账号规则仍优先)。
|
||||
ModelCatalog bool `json:"model_catalog,omitempty"`
|
||||
// Modes 以默认模式开头,其余按模式名排序。
|
||||
Modes []ProviderModeInfo `json:"modes"`
|
||||
}
|
||||
|
||||
// ProviderModeInfo 是某接入模式的默认端点;BaseURLs 缺少某协议即该模式不提供该原生端点。
|
||||
type ProviderModeInfo struct {
|
||||
Mode string `json:"mode"`
|
||||
BaseURLs map[string]string `json:"base_urls"`
|
||||
ProtocolRules []ProtocolRule `json:"protocol_rules,omitempty"`
|
||||
}
|
||||
|
||||
// BuildPlatformCatalog 按展示顺序返回全部具体平台(不含 composite)。
|
||||
func BuildPlatformCatalog() PlatformCatalog {
|
||||
specs := domain.Platforms()
|
||||
catalog := PlatformCatalog{
|
||||
Platforms: make([]PlatformCatalogEntry, 0, len(specs)),
|
||||
CompositePrecedence: domain.CompositePrecedencePlatformIDs(),
|
||||
}
|
||||
for _, spec := range specs {
|
||||
catalog.Platforms = append(catalog.Platforms, PlatformCatalogEntry{
|
||||
PlatformSpec: spec,
|
||||
MultiProtocol: providerProfileInfo(LookupProviderProfile(spec.ID)),
|
||||
})
|
||||
}
|
||||
return catalog
|
||||
}
|
||||
|
||||
func providerProfileInfo(profile *ProviderProfile) *ProviderProfileInfo {
|
||||
if profile == nil {
|
||||
return nil
|
||||
}
|
||||
routing := profile.Routing
|
||||
if routing == "" {
|
||||
routing = ProviderRoutingByInbound
|
||||
}
|
||||
modes := make([]string, 0, len(profile.Modes))
|
||||
for mode := range profile.Modes {
|
||||
if mode != profile.DefaultMode {
|
||||
modes = append(modes, mode)
|
||||
}
|
||||
}
|
||||
sort.Strings(modes)
|
||||
if _, ok := profile.Modes[profile.DefaultMode]; ok {
|
||||
modes = append([]string{profile.DefaultMode}, modes...)
|
||||
}
|
||||
info := &ProviderProfileInfo{
|
||||
DefaultMode: profile.DefaultMode,
|
||||
Routing: routing,
|
||||
ResponsesPath: profile.ResponsesPath,
|
||||
ModelCatalog: profile.ModelCatalog,
|
||||
Modes: make([]ProviderModeInfo, 0, len(modes)),
|
||||
}
|
||||
for _, mode := range modes {
|
||||
endpoints := profile.Modes[mode]
|
||||
baseURLs := make(map[string]string, len(endpoints.BaseURLs))
|
||||
for protocol, baseURL := range endpoints.BaseURLs {
|
||||
baseURLs[protocol] = baseURL
|
||||
}
|
||||
info.Modes = append(info.Modes, ProviderModeInfo{
|
||||
Mode: mode,
|
||||
BaseURLs: baseURLs,
|
||||
ProtocolRules: cloneProtocolRules(endpoints.ProtocolRules),
|
||||
})
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
func cloneProtocolRules(rules []ProtocolRule) []ProtocolRule {
|
||||
if rules == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]ProtocolRule, len(rules))
|
||||
for i, rule := range rules {
|
||||
out[i] = rule
|
||||
out[i].Protocols = append([]string(nil), rule.Protocols...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuildPlatformCatalogMirrorsPlatformListAndProfiles(t *testing.T) {
|
||||
catalog := BuildPlatformCatalog()
|
||||
require.Equal(t, domain.CompositePrecedencePlatformIDs(), catalog.CompositePrecedence)
|
||||
require.Len(t, catalog.Platforms, len(domain.ConcretePlatformIDs()))
|
||||
|
||||
for i, entry := range catalog.Platforms {
|
||||
require.Equal(t, domain.ConcretePlatformIDs()[i], entry.ID)
|
||||
profile := LookupProviderProfile(entry.ID)
|
||||
if profile == nil {
|
||||
require.Nil(t, entry.MultiProtocol, entry.ID)
|
||||
continue
|
||||
}
|
||||
require.NotNil(t, entry.MultiProtocol, entry.ID)
|
||||
require.Equal(t, profile.DefaultMode, entry.MultiProtocol.DefaultMode, entry.ID)
|
||||
require.Equal(t, profile.DefaultMode, entry.MultiProtocol.Modes[0].Mode, entry.ID)
|
||||
require.Equal(t, profile.ResponsesPath, entry.MultiProtocol.ResponsesPath, entry.ID)
|
||||
require.Len(t, entry.MultiProtocol.Modes, len(profile.Modes), entry.ID)
|
||||
for _, mode := range entry.MultiProtocol.Modes {
|
||||
endpoints := profile.Modes[mode.Mode]
|
||||
require.Equal(t, endpoints.BaseURLs, mode.BaseURLs, "%s/%s", entry.ID, mode.Mode)
|
||||
require.Equal(t, len(endpoints.ProtocolRules), len(mode.ProtocolRules), "%s/%s", entry.ID, mode.Mode)
|
||||
for j, rule := range endpoints.ProtocolRules {
|
||||
require.Equal(t, rule, mode.ProtocolRules[j])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPlatformCatalogJSONShape(t *testing.T) {
|
||||
raw, err := json.Marshal(BuildPlatformCatalog())
|
||||
require.NoError(t, err)
|
||||
|
||||
type modeJSON struct {
|
||||
Mode string `json:"mode"`
|
||||
BaseURLs map[string]string `json:"base_urls"`
|
||||
ProtocolRules []ProtocolRule `json:"protocol_rules"`
|
||||
}
|
||||
type platformJSON struct {
|
||||
ID string `json:"id"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Gateway string `json:"gateway"`
|
||||
CNProvider *bool `json:"cn_provider"`
|
||||
MultiProtocol *struct {
|
||||
DefaultMode string `json:"default_mode"`
|
||||
Routing string `json:"routing"`
|
||||
ResponsesPath string `json:"responses_path"`
|
||||
Modes []modeJSON `json:"modes"`
|
||||
} `json:"multi_protocol"`
|
||||
}
|
||||
var decoded struct {
|
||||
Platforms []platformJSON `json:"platforms"`
|
||||
CompositePrecedence []string `json:"composite_precedence"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(raw, &decoded))
|
||||
require.Equal(t, domain.CompositePrecedencePlatformIDs(), decoded.CompositePrecedence)
|
||||
byID := map[string]platformJSON{}
|
||||
for _, p := range decoded.Platforms {
|
||||
byID[p.ID] = p
|
||||
}
|
||||
|
||||
anthropic := byID[PlatformAnthropic]
|
||||
require.Equal(t, "Anthropic", anthropic.DisplayName)
|
||||
require.Equal(t, "anthropic", anthropic.Gateway)
|
||||
require.NotNil(t, anthropic.CNProvider)
|
||||
require.False(t, *anthropic.CNProvider)
|
||||
require.Nil(t, anthropic.MultiProtocol)
|
||||
require.NotContains(t, string(raw), `"multi_protocol":null`)
|
||||
|
||||
deepseek := byID[PlatformDeepseek].MultiProtocol
|
||||
require.NotNil(t, deepseek)
|
||||
require.Equal(t, "by_inbound", deepseek.Routing)
|
||||
require.Equal(t, "/responses", deepseek.ResponsesPath)
|
||||
|
||||
openCode := byID[PlatformOpenCodeGo].MultiProtocol
|
||||
require.NotNil(t, openCode)
|
||||
require.Equal(t, "by_model", openCode.Routing)
|
||||
require.Equal(t, AccountModeGo, openCode.DefaultMode)
|
||||
require.Len(t, openCode.Modes, 2)
|
||||
require.Equal(t, AccountModeGo, openCode.Modes[0].Mode)
|
||||
require.Equal(t, DefaultOpenCodeGoBaseURL, openCode.Modes[0].BaseURLs[APIProtocolChatCompletions])
|
||||
require.Equal(t, DefaultOpenCodeGoProtocolRules(), openCode.Modes[0].ProtocolRules)
|
||||
require.Equal(t, AccountModeZen, openCode.Modes[1].Mode)
|
||||
}
|
||||
|
||||
// 下发的是副本:调用方修改结果不影响内置 profile。
|
||||
func TestBuildPlatformCatalogReturnsCopies(t *testing.T) {
|
||||
catalog := BuildPlatformCatalog()
|
||||
for _, entry := range catalog.Platforms {
|
||||
if entry.MultiProtocol == nil {
|
||||
continue
|
||||
}
|
||||
for _, mode := range entry.MultiProtocol.Modes {
|
||||
for protocol := range mode.BaseURLs {
|
||||
mode.BaseURLs[protocol] = "mutated"
|
||||
}
|
||||
for i := range mode.ProtocolRules {
|
||||
mode.ProtocolRules[i].Protocol = "mutated"
|
||||
}
|
||||
}
|
||||
}
|
||||
require.Equal(t, DefaultOpenCodeGoBaseURL, LookupProviderProfile(PlatformOpenCodeGo).DefaultBaseURL(AccountModeGo, APIProtocolChatCompletions))
|
||||
require.NotEqual(t, "mutated", LookupProviderProfile(PlatformOpenCodeGo).Modes[AccountModeGo].ProtocolRules[0].Protocol)
|
||||
}
|
||||
|
||||
// 前端内置的平台清单(接口加载前与加载失败时使用)必须与后端一致。
|
||||
// 更新平台清单或 profile 后运行:
|
||||
//
|
||||
// UPDATE_PLATFORM_CATALOG=1 go test -tags unit ./internal/service/ -run TestFrontendBuiltinPlatformCatalogInSync
|
||||
func TestFrontendBuiltinPlatformCatalogInSync(t *testing.T) {
|
||||
const path = "../../../frontend/src/constants/platformCatalog.builtin.json"
|
||||
want, err := json.MarshalIndent(BuildPlatformCatalog(), "", " ")
|
||||
require.NoError(t, err)
|
||||
want = append(want, '\n')
|
||||
|
||||
if os.Getenv("UPDATE_PLATFORM_CATALOG") == "1" {
|
||||
require.NoError(t, os.WriteFile(path, want, 0o644))
|
||||
return
|
||||
}
|
||||
got, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
t.Skip("frontend sources not available")
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, string(want), string(got),
|
||||
"frontend/src/constants/platformCatalog.builtin.json 与后端平台清单不一致,按测试注释重新生成")
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 以下为重构前各处手写的平台列表 / switch,作为平台清单派生结果的等价基准;
|
||||
// 重构后新登记的平台(Command Code、Cline)按同类平台(OpenCode)的位置补入。
|
||||
var (
|
||||
legacyAllPlatforms = []string{
|
||||
PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
|
||||
PlatformCommandCode,
|
||||
PlatformCline,
|
||||
}
|
||||
legacySchedulerSnapshotPlatforms = []string{
|
||||
PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
|
||||
PlatformCommandCode,
|
||||
PlatformCline,
|
||||
}
|
||||
legacyCompositeMatchingPlatforms = legacySchedulerSnapshotPlatforms
|
||||
legacyMultiProtocolProviders = []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline}
|
||||
platformProbeValues = append(append([]string{}, legacyAllPlatforms...), PlatformComposite, "", "moonshot", "Kimi", "openai ", "glm", "bogus")
|
||||
platformProbeAccountTypes = []string{AccountTypeAPIKey, AccountTypeOAuth, AccountTypeSetupToken, AccountTypeUpstream, ""}
|
||||
)
|
||||
|
||||
func legacyIsCNProvider(platform string) bool {
|
||||
switch platform {
|
||||
case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func legacyIsOpenAICompatible(platform string) bool {
|
||||
return platform == PlatformOpenAI || platform == PlatformGrok || legacyIsCNProvider(platform) || platform == PlatformOpenCodeGo || platform == PlatformCommandCode || platform == PlatformCline
|
||||
}
|
||||
|
||||
func legacyNormalizeOpenAICompatiblePlatform(platform string) string {
|
||||
switch platform {
|
||||
case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline:
|
||||
return platform
|
||||
}
|
||||
return PlatformOpenAI
|
||||
}
|
||||
|
||||
func legacyIsUpstreamBillingProbeIdentity(platform, accountType string) bool {
|
||||
if accountType != AccountTypeAPIKey {
|
||||
return false
|
||||
}
|
||||
switch platform {
|
||||
case PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo,
|
||||
PlatformTypeSafe, PlatformCommandCode, PlatformCline:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func legacyIsHeaderOverrideEligible(platform, accountType string) bool {
|
||||
switch platform {
|
||||
case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline:
|
||||
return accountType == AccountTypeAPIKey
|
||||
case PlatformGrok:
|
||||
return accountType == AccountTypeAPIKey || accountType == AccountTypeOAuth
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func legacyIsConcreteRequestPlatform(platform string) bool {
|
||||
for _, p := range legacyAllPlatforms {
|
||||
if p == platform {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestPlatformListDerivedListsMatchLegacy(t *testing.T) {
|
||||
require.Equal(t, legacyAllPlatforms, AllowedQuotaPlatforms)
|
||||
require.Equal(t, legacySchedulerSnapshotPlatforms, schedulerSnapshotPlatforms())
|
||||
require.Equal(t, legacyCompositeMatchingPlatforms, matchingPlatforms(PlatformComposite))
|
||||
require.Equal(t, []string{PlatformKimi}, matchingPlatforms(PlatformKimi))
|
||||
|
||||
var multiProtocol []string
|
||||
for _, platform := range legacyAllPlatforms {
|
||||
if IsMultiProtocolAPIKeyProvider(platform) {
|
||||
multiProtocol = append(multiProtocol, platform)
|
||||
}
|
||||
}
|
||||
require.Equal(t, legacyMultiProtocolProviders, multiProtocol)
|
||||
}
|
||||
|
||||
func TestPlatformListDerivedPredicatesMatchLegacy(t *testing.T) {
|
||||
for _, platform := range platformProbeValues {
|
||||
require.Equal(t, legacyIsCNProvider(platform), IsCNProvider(platform), platform)
|
||||
require.Equal(t, legacyIsConcreteRequestPlatform(platform), isConcreteRequestPlatform(platform), platform)
|
||||
require.Equal(t, legacyNormalizeOpenAICompatiblePlatform(platform), NormalizeOpenAICompatiblePlatform(platform), platform)
|
||||
require.Equal(t, legacyIsOpenAICompatible(platform), (&Account{Platform: platform}).IsOpenAICompatible(), platform)
|
||||
for _, accountType := range platformProbeAccountTypes {
|
||||
require.Equal(t, legacyIsUpstreamBillingProbeIdentity(platform, accountType),
|
||||
IsUpstreamBillingProbeIdentity(platform, accountType), "%s/%s", platform, accountType)
|
||||
require.Equal(t, legacyIsHeaderOverrideEligible(platform, accountType),
|
||||
(&Account{Platform: platform, Type: accountType}).IsHeaderOverrideEligible(), "%s/%s", platform, accountType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 多协议 API Key 供应商经 OpenAI 网关转发(NormalizeOpenAICompatiblePlatform、
|
||||
// countTokens 路由等依赖此约束),ProviderProfile 登记的平台必须在平台清单中声明 openai 网关。
|
||||
func TestProviderProfilesUseOpenAIGateway(t *testing.T) {
|
||||
for platform := range providerProfiles {
|
||||
spec, ok := domain.LookupPlatform(platform)
|
||||
require.True(t, ok, platform)
|
||||
require.Equal(t, domain.PlatformGatewayOpenAI, spec.Gateway, platform)
|
||||
}
|
||||
}
|
||||
|
||||
// 转发、探测与计费中"多协议供应商"类判断改为查 profile:现有平台上与改动前的
|
||||
// 国产厂商 / 国产厂商 ∪ OpenCode 判断逐一相同。
|
||||
func TestProviderProfileAccountPredicatesMatchLegacy(t *testing.T) {
|
||||
for _, platform := range platformProbeValues {
|
||||
account := &Account{Platform: platform, Type: AccountTypeAPIKey}
|
||||
// Cline 只有 Chat Completions 一个端点,按入站协议分流(其余入站转换)。
|
||||
require.Equal(t, legacyIsCNProvider(platform) || platform == PlatformCline, account.RoutesProtocolByInbound(), platform)
|
||||
require.Equal(t, legacyIsCNProvider(platform) || platform == PlatformOpenCodeGo || platform == PlatformCommandCode || platform == PlatformCline, account.IsMultiProtocolAPIKey(), platform)
|
||||
}
|
||||
var nilAccount *Account
|
||||
require.False(t, nilAccount.RoutesProtocolByInbound())
|
||||
}
|
||||
|
||||
// 仅在 providerProfiles 中登记的新供应商按分流方式自动获得对应行为:按入站协议
|
||||
// 分流的与国产厂商一致,按模型分流的与 OpenCode 一致。
|
||||
func TestNewlyRegisteredProviderInheritsRoutingBehaviour(t *testing.T) {
|
||||
const byInbound, byModel = "test_inbound_provider", "test_model_provider"
|
||||
providerProfiles[byInbound] = &ProviderProfile{
|
||||
Platform: byInbound, DefaultMode: AccountModePayG, Routing: ProviderRoutingByInbound,
|
||||
Modes: map[string]ProviderEndpoints{AccountModePayG: {BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: "https://inbound.example.com/v1",
|
||||
APIProtocolAnthropic: "https://inbound.example.com/anthropic",
|
||||
}}},
|
||||
}
|
||||
providerProfiles[byModel] = &ProviderProfile{
|
||||
Platform: byModel, DefaultMode: AccountModePayG, Routing: ProviderRoutingByModel,
|
||||
Modes: map[string]ProviderEndpoints{AccountModePayG: {BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: "https://model.example.com/v1",
|
||||
}}},
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
delete(providerProfiles, byInbound)
|
||||
delete(providerProfiles, byModel)
|
||||
})
|
||||
|
||||
inbound := &Account{Platform: byInbound, Type: AccountTypeAPIKey, Credentials: map[string]any{
|
||||
"api_key": "sk-test", "api_protocol": APIProtocolAdaptive,
|
||||
"base_url": "https://inbound.example.com/v1",
|
||||
}}
|
||||
require.True(t, inbound.IsMultiProtocolAPIKey())
|
||||
require.True(t, inbound.RoutesProtocolByInbound())
|
||||
// 无原生 Responses 端点的 adaptive 账号回退 Chat Completions(与 GLM 相同)。
|
||||
require.True(t, shouldForwardOpenAIResponsesViaRawChatCompletions(inbound))
|
||||
require.True(t, shouldEstimateOpenAIInputTokensLocally(inbound))
|
||||
require.Equal(t, "https://inbound.example.com/v1", upstreamModelRegistryBaseURL(inbound))
|
||||
|
||||
model := &Account{Platform: byModel, Type: AccountTypeAPIKey, Credentials: map[string]any{
|
||||
"api_key": "sk-test", "api_protocol": APIProtocolAdaptive,
|
||||
"base_url": "https://model.example.com/v1",
|
||||
}}
|
||||
require.True(t, model.IsMultiProtocolAPIKey())
|
||||
require.False(t, model.RoutesProtocolByInbound())
|
||||
// 按模型分流:protocol_rules 决定协议,不按 Responses 能力标记回退(与 OpenCode 相同)。
|
||||
require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(model))
|
||||
require.Equal(t, "https://model.example.com/v1", upstreamModelRegistryBaseURL(model))
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package service
|
||||
|
||||
import "strings"
|
||||
|
||||
// ProviderEndpoints 是多协议 API Key 供应商在某个接入模式下的官方默认端点与
|
||||
// 内置分流规则。账号凭证里的 base_url / api_base_urls / protocol_rules 仍优先于这里。
|
||||
type ProviderEndpoints struct {
|
||||
// BaseURLs 以上游协议(chat_completions / responses / anthropic)为键,
|
||||
// 值为该协议的官方默认基址。缺少某协议的条目即表示该模式不提供该原生端点。
|
||||
// Anthropic 基址的上游路径为 {base}/v1/messages。
|
||||
BaseURLs map[string]string
|
||||
// ProtocolRules 是按模型分流的内置默认表(首条命中生效);为空表示该模式
|
||||
// 不按模型分流,由账号 api_protocol 决定上游协议。
|
||||
ProtocolRules []ProtocolRule
|
||||
}
|
||||
|
||||
// ProviderRouting 决定多协议供应商账号如何选择上游协议。
|
||||
type ProviderRouting string
|
||||
|
||||
const (
|
||||
// ProviderRoutingByInbound 适用于单一厂商:模型在各原生端点都可用,adaptive 账号
|
||||
// 按入站协议选同协议端点,供应商不提供该协议时回落 Chat Completions。
|
||||
ProviderRoutingByInbound ProviderRouting = "by_inbound"
|
||||
// ProviderRoutingByModel 适用于多模型聚合平台:每个模型只在某一协议端点提供,
|
||||
// 按 protocol_rules 以模型名选协议,与入站协议无关。
|
||||
ProviderRoutingByModel ProviderRouting = "by_model"
|
||||
)
|
||||
|
||||
// ProviderProfile 描述一个多协议 API Key 供应商(国产厂商或多模型聚合平台)的
|
||||
// 静态数据:各接入模式的默认端点、内置分流规则与端点路径约定。
|
||||
// 额度解析、会话头等行为差异不在这里,仍由各自的代码路径处理。
|
||||
type ProviderProfile struct {
|
||||
Platform string
|
||||
// DefaultMode 在 credentials.account_mode 缺失或不在 Modes 中时使用。
|
||||
DefaultMode string
|
||||
Modes map[string]ProviderEndpoints
|
||||
// Routing 为空时按 ProviderRoutingByInbound 处理。
|
||||
Routing ProviderRouting
|
||||
// ResponsesPath 覆盖 Responses 端点路径(按 buildOpenAIEndpointURL 的版本感知
|
||||
// 规则拼接),空值为 /v1/responses。对自定义 base_url 的账号同样生效。
|
||||
ResponsesPath string
|
||||
// DefaultTestModel 是管理端连接测试未指定模型时使用的模型;空值时按各协议的
|
||||
// 通用默认模型。
|
||||
DefaultTestModel string
|
||||
// ModelCatalog 表示上游 {Chat Completions 基址}/models 为每个模型给出
|
||||
// supported_endpoints;按模型分流时据此判断模型支持哪些协议(见 model_protocol_catalog.go)。
|
||||
ModelCatalog bool
|
||||
// DefaultAPIProtocol 是账号未显式配置 api_protocol 时的上游协议;空值时按模型分流
|
||||
// 的供应商为 adaptive,其余为 chat_completions。
|
||||
DefaultAPIProtocol string
|
||||
}
|
||||
|
||||
// providerDefaultTestModel 返回账号连接测试未指定模型时的默认模型;非多协议供应商或
|
||||
// 未设置时为空。
|
||||
func (a *Account) providerDefaultTestModel() string {
|
||||
profile := a.providerProfile()
|
||||
if profile == nil {
|
||||
return ""
|
||||
}
|
||||
// Cline 订阅了 ClinePass 的账号用订阅模型测试,不消耗积分;ClinePass 钱包冷却中
|
||||
// (窗口用满等)时改用按量模型,否则测试必然失败,而积分模型照常可用。
|
||||
if a.IsCline() && a.clinePassSubscribed() && !a.isRateLimitActiveForKey(clinePassRateLimitKey) {
|
||||
return DefaultClinePassTestModel
|
||||
}
|
||||
return profile.DefaultTestModel
|
||||
}
|
||||
|
||||
// Endpoints 返回指定接入模式的端点;未知模式回落 DefaultMode。
|
||||
func (p *ProviderProfile) Endpoints(mode string) ProviderEndpoints {
|
||||
if p == nil {
|
||||
return ProviderEndpoints{}
|
||||
}
|
||||
if endpoints, ok := p.Modes[strings.TrimSpace(mode)]; ok {
|
||||
return endpoints
|
||||
}
|
||||
return p.Modes[p.DefaultMode]
|
||||
}
|
||||
|
||||
// DefaultBaseURL 返回指定接入模式与上游协议的官方默认基址;该模式不提供此协议时为空串。
|
||||
func (p *ProviderProfile) DefaultBaseURL(mode, protocol string) string {
|
||||
return p.Endpoints(mode).BaseURLs[protocol]
|
||||
}
|
||||
|
||||
// SupportsProtocol 报告指定接入模式是否提供该协议的原生端点。
|
||||
func (p *ProviderProfile) SupportsProtocol(mode, protocol string) bool {
|
||||
return p.DefaultBaseURL(mode, protocol) != ""
|
||||
}
|
||||
|
||||
// providerProfiles 是多协议 API Key 供应商的单一数据来源。新增同类供应商时在此
|
||||
// 登记一条即可获得默认端点、原生 Responses 能力判定(有 responses 条目即支持)、
|
||||
// 上游协议分流方式、Responses 路径约定与 IsMultiProtocolAPIKeyProvider 归属。
|
||||
// 默认端点需与前端 credentialsBuilder.ts 的预设保持一致。
|
||||
var providerProfiles = map[string]*ProviderProfile{
|
||||
PlatformKimi: {
|
||||
Platform: PlatformKimi,
|
||||
DefaultMode: AccountModePayG,
|
||||
Routing: ProviderRoutingByInbound,
|
||||
Modes: map[string]ProviderEndpoints{
|
||||
AccountModePayG: {
|
||||
BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: DefaultKimiPayGBaseURL,
|
||||
APIProtocolResponses: DefaultKimiPayGBaseURL,
|
||||
APIProtocolAnthropic: DefaultKimiPayGAnthropicBaseURL,
|
||||
},
|
||||
},
|
||||
AccountModeCoding: {
|
||||
BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: DefaultKimiCodingBaseURL,
|
||||
APIProtocolResponses: DefaultKimiCodingBaseURL,
|
||||
APIProtocolAnthropic: DefaultKimiCodingAnthropicBaseURL,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
PlatformZhipu: {
|
||||
Platform: PlatformZhipu,
|
||||
DefaultMode: AccountModePayG,
|
||||
Routing: ProviderRoutingByInbound,
|
||||
// 智谱没有原生 Responses 端点,故不登记 responses 条目。
|
||||
Modes: map[string]ProviderEndpoints{
|
||||
AccountModePayG: {
|
||||
BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: DefaultZhipuPayGBaseURL,
|
||||
APIProtocolAnthropic: DefaultZhipuAnthropicBaseURL,
|
||||
},
|
||||
},
|
||||
AccountModeCoding: {
|
||||
BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: DefaultZhipuCodingBaseURL,
|
||||
APIProtocolAnthropic: DefaultZhipuAnthropicBaseURL,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
PlatformDeepseek: {
|
||||
Platform: PlatformDeepseek,
|
||||
DefaultMode: AccountModePayG,
|
||||
Routing: ProviderRoutingByInbound,
|
||||
// DeepSeek 官方 Responses 端点为 /responses(无 /v1 前缀,适配 Codex)。
|
||||
ResponsesPath: "/responses",
|
||||
Modes: map[string]ProviderEndpoints{
|
||||
AccountModePayG: {
|
||||
BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: DefaultDeepseekBaseURL,
|
||||
APIProtocolResponses: DefaultDeepseekBaseURL,
|
||||
APIProtocolAnthropic: DefaultDeepseekAnthropicBaseURL,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
PlatformMiniMax: {
|
||||
Platform: PlatformMiniMax,
|
||||
DefaultMode: AccountModePayG,
|
||||
Routing: ProviderRoutingByInbound,
|
||||
Modes: map[string]ProviderEndpoints{
|
||||
// 按量付费与 Coding/Token Plan 共用推理域名,靠 API Key 区分套餐。
|
||||
AccountModePayG: {
|
||||
BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: DefaultMiniMaxBaseURL,
|
||||
APIProtocolResponses: DefaultMiniMaxBaseURL,
|
||||
APIProtocolAnthropic: DefaultMiniMaxAnthropicBaseURL,
|
||||
},
|
||||
},
|
||||
AccountModeCoding: {
|
||||
BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: DefaultMiniMaxBaseURL,
|
||||
APIProtocolResponses: DefaultMiniMaxBaseURL,
|
||||
APIProtocolAnthropic: DefaultMiniMaxAnthropicBaseURL,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
PlatformOpenCodeGo: {
|
||||
Platform: PlatformOpenCodeGo,
|
||||
DefaultMode: AccountModeGo,
|
||||
Routing: ProviderRoutingByModel,
|
||||
DefaultTestModel: DefaultOpenCodeGoTestModel,
|
||||
Modes: map[string]ProviderEndpoints{
|
||||
AccountModeGo: {
|
||||
BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: DefaultOpenCodeGoBaseURL,
|
||||
APIProtocolResponses: DefaultOpenCodeGoBaseURL,
|
||||
APIProtocolAnthropic: DefaultOpenCodeGoAnthropicBaseURL,
|
||||
},
|
||||
ProtocolRules: DefaultOpenCodeGoProtocolRules(),
|
||||
},
|
||||
AccountModeZen: {
|
||||
BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: DefaultOpenCodeZenBaseURL,
|
||||
APIProtocolResponses: DefaultOpenCodeZenBaseURL,
|
||||
APIProtocolAnthropic: DefaultOpenCodeZenAnthropicBaseURL,
|
||||
},
|
||||
ProtocolRules: DefaultOpenCodeZenProtocolRules(),
|
||||
},
|
||||
},
|
||||
},
|
||||
PlatformCommandCode: {
|
||||
Platform: PlatformCommandCode,
|
||||
DefaultMode: AccountModePayG,
|
||||
Routing: ProviderRoutingByModel,
|
||||
DefaultTestModel: DefaultCommandCodeTestModel,
|
||||
ModelCatalog: true,
|
||||
// 订阅套餐与 Provider 按量计费共用同一个 API Key 与端点,只有一个接入模式。
|
||||
Modes: map[string]ProviderEndpoints{
|
||||
AccountModePayG: {
|
||||
BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: DefaultCommandCodeBaseURL,
|
||||
APIProtocolResponses: DefaultCommandCodeBaseURL,
|
||||
APIProtocolAnthropic: DefaultCommandCodeAnthropicBaseURL,
|
||||
},
|
||||
ProtocolRules: DefaultCommandCodeProtocolRules(),
|
||||
},
|
||||
},
|
||||
},
|
||||
PlatformOllamaCloud: {
|
||||
Platform: PlatformOllamaCloud,
|
||||
DefaultMode: AccountModeOllamaLegacy,
|
||||
Routing: ProviderRoutingByInbound,
|
||||
// 三种协议都有原生端点,未显式配置时按入站协议直通。
|
||||
DefaultAPIProtocol: APIProtocolAdaptive,
|
||||
// legacy(5h / 7d 滚动窗口)与 credits(月度美元信用池)共用同一 API Key 与端点,
|
||||
// 区别只在额度语义(见 GetOllamaCloudAccountMode)。
|
||||
Modes: map[string]ProviderEndpoints{
|
||||
AccountModeOllamaLegacy: ollamaCloudEndpoints,
|
||||
AccountModeOllamaCredits: ollamaCloudEndpoints,
|
||||
},
|
||||
},
|
||||
PlatformCline: {
|
||||
Platform: PlatformCline,
|
||||
DefaultMode: AccountModePayG,
|
||||
DefaultTestModel: DefaultClineTestModel,
|
||||
// 按量积分与 ClinePass 订阅共用同一个 API Key 与端点,由模型名决定扣哪一边
|
||||
// (cline-pass/* 走订阅),只有一个接入模式;两边的超限分别冷却(见 cline.go)。
|
||||
Modes: map[string]ProviderEndpoints{
|
||||
AccountModePayG: {
|
||||
BaseURLs: map[string]string{APIProtocolChatCompletions: DefaultClineBaseURL},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// ollamaCloudEndpoints 是 Ollama Cloud 各额度模式共用的官方端点(Responses 为 non-stateful)。
|
||||
var ollamaCloudEndpoints = ProviderEndpoints{
|
||||
BaseURLs: map[string]string{
|
||||
APIProtocolChatCompletions: DefaultOllamaCloudBaseURL,
|
||||
APIProtocolResponses: DefaultOllamaCloudBaseURL,
|
||||
APIProtocolAnthropic: DefaultOllamaCloudAnthropicBaseURL,
|
||||
},
|
||||
}
|
||||
|
||||
// LookupProviderProfile 返回 platform 对应的多协议供应商 profile;非此类平台返回 nil。
|
||||
func LookupProviderProfile(platform string) *ProviderProfile {
|
||||
return providerProfiles[platform]
|
||||
}
|
||||
|
||||
func (a *Account) providerProfile() *ProviderProfile {
|
||||
if a == nil {
|
||||
return nil
|
||||
}
|
||||
return LookupProviderProfile(a.Platform)
|
||||
}
|
||||
|
||||
// defaultProviderBaseURL 按账号 account_mode 返回多协议供应商指定协议的官方默认基址;
|
||||
// 非多协议供应商或协议未知时为空串。
|
||||
func (a *Account) defaultProviderBaseURL(protocol string) string {
|
||||
profile := a.providerProfile()
|
||||
if profile == nil {
|
||||
return ""
|
||||
}
|
||||
return profile.DefaultBaseURL(a.GetCredential("account_mode"), protocol)
|
||||
}
|
||||
|
||||
// providerSupportsProtocol 报告账号所在供应商在其 account_mode 下是否提供该协议的原生端点。
|
||||
func (a *Account) providerSupportsProtocol(protocol string) bool {
|
||||
profile := a.providerProfile()
|
||||
return profile != nil && profile.SupportsProtocol(a.GetCredential("account_mode"), protocol)
|
||||
}
|
||||
|
||||
// routesByModel 报告账号所在供应商是否按模型名分流上游协议(多模型聚合平台)。
|
||||
func (a *Account) routesByModel() bool {
|
||||
profile := a.providerProfile()
|
||||
return profile != nil && profile.Routing == ProviderRoutingByModel
|
||||
}
|
||||
|
||||
// RoutesProtocolByInbound 报告账号是否为按入站协议分流的多协议 API Key 供应商
|
||||
// (单一厂商型,目前即国产厂商)。这类账号共享"显式协议优先、adaptive 选同协议
|
||||
// 原生端点"的转发、Responses 能力标记与本地 token 估算逻辑;按模型分流的聚合
|
||||
// 平台由 protocol_rules 决定协议,走 routesByModel 分支。
|
||||
func (a *Account) RoutesProtocolByInbound() bool {
|
||||
profile := a.providerProfile()
|
||||
return profile != nil && profile.Routing != ProviderRoutingByModel
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// legacyProviderDefaultBaseURL 复述 provider profile 引入前 account.go 中逐平台
|
||||
// switch 的默认端点逻辑,作为等价性基准。
|
||||
func legacyProviderDefaultBaseURL(platform, mode, protocol string) string {
|
||||
coding := mode == AccountModeCoding
|
||||
zen := mode == AccountModeZen
|
||||
switch protocol {
|
||||
case APIProtocolAnthropic:
|
||||
switch platform {
|
||||
case PlatformKimi:
|
||||
if coding {
|
||||
return DefaultKimiCodingAnthropicBaseURL
|
||||
}
|
||||
return DefaultKimiPayGAnthropicBaseURL
|
||||
case PlatformZhipu:
|
||||
return DefaultZhipuAnthropicBaseURL
|
||||
case PlatformDeepseek:
|
||||
return DefaultDeepseekAnthropicBaseURL
|
||||
case PlatformMiniMax:
|
||||
return DefaultMiniMaxAnthropicBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
if zen {
|
||||
return DefaultOpenCodeZenAnthropicBaseURL
|
||||
}
|
||||
return DefaultOpenCodeGoAnthropicBaseURL
|
||||
}
|
||||
case APIProtocolChatCompletions, APIProtocolResponses:
|
||||
if platform == PlatformZhipu && protocol == APIProtocolResponses {
|
||||
// 唯一的函数级差异:旧 switch 对智谱 Responses 也返回 CC 基址,profile
|
||||
// 以"缺条目即不支持"建模后返回空串。所有运行时调用方都先经
|
||||
// UsesNativeCNResponses / SupportsNativeCNResponses 守卫,智谱不会走到这里。
|
||||
return ""
|
||||
}
|
||||
switch platform {
|
||||
case PlatformKimi:
|
||||
if coding {
|
||||
return DefaultKimiCodingBaseURL
|
||||
}
|
||||
return DefaultKimiPayGBaseURL
|
||||
case PlatformZhipu:
|
||||
if coding {
|
||||
return DefaultZhipuCodingBaseURL
|
||||
}
|
||||
return DefaultZhipuPayGBaseURL
|
||||
case PlatformDeepseek:
|
||||
return DefaultDeepseekBaseURL
|
||||
case PlatformMiniMax:
|
||||
return DefaultMiniMaxBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
if zen {
|
||||
return DefaultOpenCodeZenBaseURL
|
||||
}
|
||||
return DefaultOpenCodeGoBaseURL
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestProviderProfile_DefaultBaseURLsMatchLegacySwitches(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
platforms := []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo}
|
||||
modes := []string{"", AccountModePayG, AccountModeCoding, AccountModeZen, AccountModeGo, " coding ", "unknown"}
|
||||
|
||||
for _, platform := range platforms {
|
||||
for _, mode := range modes {
|
||||
legacyMode := mode
|
||||
if legacyMode == " coding " {
|
||||
legacyMode = AccountModeCoding
|
||||
}
|
||||
newAccount := func(protocol string) *Account {
|
||||
return &Account{
|
||||
Platform: platform,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"account_mode": mode,
|
||||
"api_protocol": protocol,
|
||||
},
|
||||
}
|
||||
}
|
||||
name := platform + "/" + mode
|
||||
|
||||
chat := newAccount(APIProtocolChatCompletions)
|
||||
require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, APIProtocolChatCompletions), chat.GetOpenAIBaseURL(), name)
|
||||
|
||||
anthropic := newAccount(APIProtocolAnthropic)
|
||||
require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, APIProtocolAnthropic), anthropic.GetAnthropicProtocolBaseURL(), name)
|
||||
require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, APIProtocolChatCompletions), anthropic.GetOpenAIFormatBaseURL(), name)
|
||||
|
||||
adaptive := newAccount(APIProtocolAdaptive)
|
||||
for _, protocol := range []string{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolAnthropic, "unknown"} {
|
||||
require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, protocol), adaptive.GetCNProtocolBaseURL(protocol), name+"/"+protocol)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderProfile_ProfilesMatchMultiProtocolPlatforms(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, platform := range []string{
|
||||
PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformComposite, "",
|
||||
} {
|
||||
want := IsCNProvider(platform) || platform == PlatformOpenCodeGo
|
||||
require.Equal(t, want, IsMultiProtocolAPIKeyProvider(platform), platform)
|
||||
require.Equal(t, want, LookupProviderProfile(platform) != nil, platform)
|
||||
}
|
||||
|
||||
for platform, profile := range providerProfiles {
|
||||
require.Equal(t, platform, profile.Platform)
|
||||
_, ok := profile.Modes[profile.DefaultMode]
|
||||
require.True(t, ok, "%s default mode %q must be registered", platform, profile.DefaultMode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderProfile_NativeResponsesMatchesLegacy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
legacy := map[string]bool{
|
||||
PlatformDeepseek: true,
|
||||
PlatformKimi: true,
|
||||
PlatformMiniMax: true,
|
||||
PlatformOpenCodeGo: true,
|
||||
}
|
||||
modes := []string{"", AccountModePayG, AccountModeCoding, AccountModeZen, AccountModeGo, "unknown"}
|
||||
for _, platform := range []string{PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} {
|
||||
for _, mode := range modes {
|
||||
account := &Account{Platform: platform, Type: AccountTypeAPIKey, Credentials: map[string]any{"account_mode": mode}}
|
||||
require.Equal(t, legacy[platform], account.SupportsNativeCNResponses(), platform+"/"+mode)
|
||||
}
|
||||
}
|
||||
require.False(t, (*Account)(nil).SupportsNativeCNResponses())
|
||||
}
|
||||
|
||||
func TestProviderProfile_BaseURLKeysAreNativeProtocols(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for platform, profile := range providerProfiles {
|
||||
for mode, endpoints := range profile.Modes {
|
||||
require.NotEmpty(t, endpoints.BaseURLs[APIProtocolChatCompletions], "%s/%s must have a chat_completions base", platform, mode)
|
||||
for protocol, baseURL := range endpoints.BaseURLs {
|
||||
require.True(t, isNativeUpstreamProtocol(protocol), "%s/%s has unknown protocol key %q", platform, mode, protocol)
|
||||
require.NotEmpty(t, baseURL, "%s/%s/%s", platform, mode, protocol)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderProfile_ResponsesPathMatchesLegacy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
legacy := func(platform, base string) string {
|
||||
if platform == PlatformDeepseek {
|
||||
return buildOpenAIEndpointURL(base, "/responses")
|
||||
}
|
||||
return buildOpenAIResponsesURL(base)
|
||||
}
|
||||
bases := []string{
|
||||
"https://api.deepseek.com", "https://relay.example.com", "https://relay.example.com/v1",
|
||||
"https://opencode.ai/zen/go/v1", "https://open.bigmodel.cn/api/paas/v4", "https://api.moonshot.cn/v1",
|
||||
}
|
||||
for _, platform := range []string{PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} {
|
||||
for _, base := range bases {
|
||||
require.Equal(t, legacy(platform, base), buildOpenAIResponsesURLForPlatform(platform, base), platform+" "+base)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderProfile_OpenCodeProtocolRulesByMode(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
openCode := LookupProviderProfile(PlatformOpenCodeGo)
|
||||
require.Equal(t, DefaultOpenCodeGoProtocolRules(), openCode.Endpoints(AccountModeGo).ProtocolRules)
|
||||
require.Equal(t, DefaultOpenCodeGoProtocolRules(), openCode.Endpoints("").ProtocolRules)
|
||||
require.Equal(t, DefaultOpenCodeZenProtocolRules(), openCode.Endpoints(AccountModeZen).ProtocolRules)
|
||||
require.Empty(t, LookupProviderProfile(PlatformKimi).Endpoints(AccountModeCoding).ProtocolRules)
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// Cline 上游错误的响应式处理。依据官方错误说明(https://docs.cline.bot/api/errors)与
|
||||
// Cline 客户端的错误分类(cline/cline:sdk/packages/llms/src/providers/errors.ts、
|
||||
// apps/vscode/src/services/error/ClineError.ts):
|
||||
//
|
||||
// - 402 insufficient_credits:积分不足;
|
||||
// - 429 SPEND_LIMIT_EXCEEDED:组织为成员设的花费上限;
|
||||
// - INFERENCE_CAP_ERROR:推理额度上限(客户端归为 QuotaExceeded,文案由服务端给出);
|
||||
// - "You have reached your … ClinePass limit … Please try again later.":ClinePass
|
||||
// 5 小时 / 7 天 / 30 天滚动用量上限,文案不带重置时间;
|
||||
// - "the user is not subscribed to required model plan" 与 "organization accounts
|
||||
// cannot use individual model inference subscriptions":没有可用的 ClinePass 订阅;
|
||||
// - "Free limit reached on model … try again in …":免费模型的每日额度,只限该模型。
|
||||
//
|
||||
// 只读取结构化 error.code 与错误消息;ClinePass / 免费模型限额兼容官方固定文案。
|
||||
// metadata 等字段可能回显请求内容,不能据此冷却钱包;未识别的错误交回默认逻辑。
|
||||
//
|
||||
// 作用范围:积分与 ClinePass 是同一个 Key 下互不影响的两个钱包,一边超限只冷却该边的
|
||||
// 全部模型(模型级冷却键,见 clineWalletRateLimitKey),不停整个账号;钱包按请求模型
|
||||
// 判定——cline-pass/* 请求只会被订阅额度拒绝,其余付费模型只会被积分拒绝。
|
||||
|
||||
type clineErrorKind int
|
||||
|
||||
const (
|
||||
clineErrorNone clineErrorKind = iota
|
||||
// clineCreditsExhausted 积分不足:冷却积分钱包,用量探测发现余额恢复后解除。
|
||||
clineCreditsExhausted
|
||||
// clineSpendLimit 组织花费上限:冷却后由下一次请求重新确认。
|
||||
clineSpendLimit
|
||||
// clineInferenceCap 推理额度上限:归属由请求模型所在的钱包决定。
|
||||
clineInferenceCap
|
||||
// clinePassLimit ClinePass 用量上限:冷却到对应窗口的重置时间。
|
||||
clinePassLimit
|
||||
// clinePassUnavailable 没有可用的 ClinePass 订阅(未订阅或组织账户)。
|
||||
clinePassUnavailable
|
||||
// clineFreeModelLimit 免费模型的每日额度:只限当前模型。
|
||||
clineFreeModelLimit
|
||||
)
|
||||
|
||||
const (
|
||||
clinePassLimitReason = "cline_pass_limit"
|
||||
clinePassUnavailableReason = "cline_pass_unavailable"
|
||||
clineSpendLimitReason = "cline_spend_limit"
|
||||
clineInferenceCapReason = "cline_inference_cap"
|
||||
clineFreeModelLimitReason = "cline_free_model_limit"
|
||||
clineCreditsReason = "cline_credits_exhausted"
|
||||
|
||||
// clineLimitRecheck 是无法得知重置时间时的冷却:到期后由下一次请求重新确认
|
||||
// (管理员可能调高上限、订阅可能续费、滚动窗口逐步释放)。
|
||||
clineLimitRecheck = time.Hour
|
||||
// ClinePass 7 天 / 30 天窗口没有用量快照时的冷却:窗口滚动释放,时间点无从得知,
|
||||
// 冷却较长但远短于窗口,由下一次请求或用量探测重新确认。
|
||||
clinePassWeeklyRecheck = 6 * time.Hour
|
||||
clinePassMonthlyRecheck = 24 * time.Hour
|
||||
// clinePassMaxCooldown 限制按快照重置时间冷却的上限(最长的 30 天窗口)。
|
||||
clinePassMaxCooldown = 31 * 24 * time.Hour
|
||||
// clineFreeModelMaxCooldown 是从免费模型文案解析出的重置时长上限(每日额度)。
|
||||
clineFreeModelMaxCooldown = 25 * time.Hour
|
||||
)
|
||||
|
||||
var (
|
||||
// clinePassLimitPattern 与 Cline 客户端的判定一致:"you have reached your" 开头、
|
||||
// "please try again later." 结尾,中间含 "clinepass limit"。
|
||||
clinePassLimitPattern = regexp.MustCompile(`(?is)you have reached your(.*?)clinepass limit.*?please try again later\.`)
|
||||
clineTryAgainPattern = regexp.MustCompile(`(?i)\btry\s+again\s+in\s+`)
|
||||
)
|
||||
|
||||
// parseClineError 返回错误分类与命中的限额消息,后者用于解析窗口和重试时间。
|
||||
func parseClineError(body []byte) (clineErrorKind, string) {
|
||||
if !gjson.ValidBytes(body) {
|
||||
return clineErrorNone, ""
|
||||
}
|
||||
err := gjson.GetBytes(body, "error")
|
||||
if !err.IsObject() {
|
||||
return clineErrorNone, ""
|
||||
}
|
||||
if code := err.Get("code"); code.Type == gjson.String {
|
||||
if kind := classifyClineErrorCode(code.String()); kind != clineErrorNone {
|
||||
return kind, ""
|
||||
}
|
||||
}
|
||||
// 官方客户端也识别 details.code 中的组织花费上限。
|
||||
if code := err.Get("details.code"); code.Type == gjson.String && classifyClineErrorCode(code.String()) == clineSpendLimit {
|
||||
return clineSpendLimit, ""
|
||||
}
|
||||
for _, path := range []string{"message", "details.message"} {
|
||||
message := err.Get(path)
|
||||
if message.Type != gjson.String {
|
||||
continue
|
||||
}
|
||||
if kind := classifyClineLimitMessage(message.String()); kind != clineErrorNone {
|
||||
return kind, message.String()
|
||||
}
|
||||
}
|
||||
return clineErrorNone, ""
|
||||
}
|
||||
|
||||
func classifyClineErrorCode(code string) clineErrorKind {
|
||||
switch strings.ToLower(strings.TrimSpace(code)) {
|
||||
case "insufficient_credits":
|
||||
return clineCreditsExhausted
|
||||
case "spend_limit_exceeded":
|
||||
return clineSpendLimit
|
||||
case "inference_cap_error":
|
||||
return clineInferenceCap
|
||||
default:
|
||||
return clineErrorNone
|
||||
}
|
||||
}
|
||||
|
||||
func classifyClineLimitMessage(message string) clineErrorKind {
|
||||
text := strings.ToLower(message)
|
||||
switch {
|
||||
case strings.Contains(text, "organization accounts cannot use individual model inference subscriptions"),
|
||||
strings.Contains(text, "the user is not subscribed to required model plan"):
|
||||
return clinePassUnavailable
|
||||
case strings.Contains(text, "free limit reached on model"):
|
||||
return clineFreeModelLimit
|
||||
case clinePassLimitPattern.MatchString(message):
|
||||
return clinePassLimit
|
||||
default:
|
||||
return clineErrorNone
|
||||
}
|
||||
}
|
||||
|
||||
// clineErrorWallet 返回错误本身指明的钱包冷却键,用于请求模型未知的情况。
|
||||
func clineErrorWallet(kind clineErrorKind) string {
|
||||
switch kind {
|
||||
case clinePassLimit, clinePassUnavailable, clineInferenceCap:
|
||||
return clinePassRateLimitKey
|
||||
case clineCreditsExhausted, clineSpendLimit:
|
||||
return clineCreditsRateLimitKey
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// clinePassWindow 返回 ClinePass 超限文案所指的窗口(5h / weekly / monthly)。
|
||||
func clinePassWindow(body []byte) string {
|
||||
match := clinePassLimitPattern.FindSubmatch(body)
|
||||
if match == nil {
|
||||
return "5h"
|
||||
}
|
||||
window := strings.ToLower(string(match[1]))
|
||||
switch {
|
||||
case strings.Contains(window, "month"):
|
||||
return "monthly"
|
||||
case strings.Contains(window, "week"):
|
||||
return "weekly"
|
||||
default:
|
||||
return "5h"
|
||||
}
|
||||
}
|
||||
|
||||
// clinePassLimitCooldown 冷却到用量快照中该窗口的重置时间;没有可用快照时按窗口估计。
|
||||
func clinePassLimitCooldown(account *Account, window string, now time.Time) time.Duration {
|
||||
if account != nil && account.Extra != nil {
|
||||
resetKey := map[string]string{
|
||||
"5h": cnExtraSuffix5hReset,
|
||||
"weekly": cnExtraSuffixWeeklyReset,
|
||||
"monthly": cnExtraSuffixMonthlyReset,
|
||||
}[window]
|
||||
if resetAt := parseSchedulingResetAt(account.Extra[cnExtraKey(PlatformCline, resetKey)]); resetAt != nil {
|
||||
if wait := resetAt.Sub(now); wait > 0 && wait <= clinePassMaxCooldown {
|
||||
return wait
|
||||
}
|
||||
}
|
||||
}
|
||||
switch window {
|
||||
case "monthly":
|
||||
return clinePassMonthlyRecheck
|
||||
case "weekly":
|
||||
return clinePassWeeklyRecheck
|
||||
default:
|
||||
return clineLimitRecheck
|
||||
}
|
||||
}
|
||||
|
||||
// clineFreeModelResetAfter 解析 "try again in 3h 20m";无法解析或超出上限时返回 0。
|
||||
func clineFreeModelResetAfter(body []byte) time.Duration {
|
||||
text := string(body)
|
||||
loc := clineTryAgainPattern.FindStringIndex(text)
|
||||
if loc == nil {
|
||||
return 0
|
||||
}
|
||||
after := parseOpenCodeGoUsageLimitResetDuration("resets in " + text[loc[1]:])
|
||||
if after <= 0 || after > clineFreeModelMaxCooldown {
|
||||
return 0
|
||||
}
|
||||
return after
|
||||
}
|
||||
|
||||
// handleClineError 处理已识别的 Cline 上游错误:冷却对应钱包(或免费模型本身),不停
|
||||
// 整个账号。handled=false 时由调用方继续走默认逻辑。
|
||||
func (s *RateLimitService) handleClineError(
|
||||
ctx context.Context,
|
||||
account *Account,
|
||||
statusCode int,
|
||||
responseBody []byte,
|
||||
upstreamMsg string,
|
||||
) bool {
|
||||
kind, limitMessage := parseClineError(responseBody)
|
||||
if kind == clineErrorNone && statusCode == http.StatusPaymentRequired {
|
||||
// 402 只会来自积分不足(ClinePass 超限走 429 等其他状态码)。
|
||||
kind = clineCreditsExhausted
|
||||
}
|
||||
if kind == clineErrorNone {
|
||||
return false
|
||||
}
|
||||
now := time.Now()
|
||||
modelKey := modelRateLimitKeyForUpstreamModelNotFound(ctx, account, tempUnschedulableModel(ctx, nil))
|
||||
|
||||
scope := modelKey
|
||||
if kind != clineFreeModelLimit {
|
||||
if scope = clineWalletRateLimitKey(modelKey); scope == "" {
|
||||
scope = clineErrorWallet(kind)
|
||||
}
|
||||
}
|
||||
if scope == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
var cooldown time.Duration
|
||||
var reason string
|
||||
switch kind {
|
||||
case clineCreditsExhausted:
|
||||
cooldown, reason = s.cnBalanceCooldownDuration(), clineCreditsReason
|
||||
case clineSpendLimit:
|
||||
cooldown, reason = clineLimitRecheck, clineSpendLimitReason
|
||||
case clineInferenceCap:
|
||||
cooldown, reason = clineLimitRecheck, clineInferenceCapReason
|
||||
if scope == clinePassRateLimitKey {
|
||||
cooldown = clinePassLimitCooldown(account, "5h", now)
|
||||
}
|
||||
case clinePassLimit:
|
||||
cooldown, reason = clinePassLimitCooldown(account, clinePassWindow([]byte(limitMessage)), now), clinePassLimitReason
|
||||
case clinePassUnavailable:
|
||||
cooldown, reason = clineLimitRecheck, clinePassUnavailableReason
|
||||
case clineFreeModelLimit:
|
||||
cooldown, reason = clineFreeModelResetAfter([]byte(limitMessage)), clineFreeModelLimitReason
|
||||
if cooldown <= 0 {
|
||||
cooldown = clineLimitRecheck
|
||||
}
|
||||
}
|
||||
until := now.Add(cooldown)
|
||||
if msg := strings.TrimSpace(upstreamMsg); msg != "" {
|
||||
reason += ": " + msg
|
||||
}
|
||||
|
||||
setAccountModelRateLimitSnapshot(account, scope, until, reason, now)
|
||||
if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, scope, until, reason); err != nil {
|
||||
slog.Warn("cline_limit_set_failed", "account_id", account.ID, "scope", scope, "error", err)
|
||||
return false
|
||||
}
|
||||
slog.Info("cline_limit", "account_id", account.ID, "scope", scope, "model", modelKey,
|
||||
"status_code", statusCode, "until", until.UTC())
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestClassifyClineErrorRequiresStructuredFields(t *testing.T) {
|
||||
for name, body := range map[string]string{
|
||||
"code in model message": `{"error":{"code":"invalid_request_error","message":"Model INFERENCE_CAP_ERROR not found"}}`,
|
||||
"code suffix": `{"error":{"code":"model-SPEND_LIMIT_EXCEEDED","message":"Invalid model"}}`,
|
||||
"credits message without code": `{"error":{"message":"Insufficient credits"}}`,
|
||||
"spend message without code": `{"error":{"message":"SPEND_LIMIT_EXCEEDED"}}`,
|
||||
"metadata code": `{"error":{"code":429,"message":"Rate limit exceeded","metadata":{"code":"SPEND_LIMIT_EXCEEDED"}}}`,
|
||||
"metadata pass message": `{"error":{"message":"Invalid model","metadata":{"message":"You have reached your monthly ClinePass limit. Please try again later."}}}`,
|
||||
"metadata free message": `{"error":{"message":"Invalid model","metadata":{"message":"Free limit reached on model x. Try again in 3h 20m"}}}`,
|
||||
"root request code": `{"error":{"message":"Invalid model"},"request":{"model":"insufficient_credits"}}`,
|
||||
"root message": `{"message":"You have reached your monthly ClinePass limit. Please try again later."}`,
|
||||
"error string": `{"error":"SPEND_LIMIT_EXCEEDED"}`,
|
||||
"plain code": `Model SPEND_LIMIT_EXCEEDED not found`,
|
||||
"plain pass message": `You have reached your weekly ClinePass limit. Please try again later.`,
|
||||
"malformed json": `{"error":{"code":"insufficient_credits"}`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
kind, _ := parseClineError([]byte(body))
|
||||
require.Equal(t, clineErrorNone, kind)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleUpstreamError_Cline400DoesNotCoolWallet(t *testing.T) {
|
||||
for name, body := range map[string]string{
|
||||
"credits model echo": `{"error":{"code":"invalid_request_error","message":"Model insufficient_credits not found"}}`,
|
||||
"spend model echo": `{"error":{"message":"Model SPEND_LIMIT_EXCEEDED not found"}}`,
|
||||
"pass model echo": `{"error":{"message":"Model cline-pass/INFERENCE_CAP_ERROR not found"}}`,
|
||||
"metadata echo": `{"error":{"code":400,"message":"Invalid model","metadata":{"model":"SPEND_LIMIT_EXCEEDED"}}}`,
|
||||
"plain echo": `Model SPEND_LIMIT_EXCEEDED not found`,
|
||||
"business code": clineInferenceCapBody,
|
||||
"pass message": clinePassMonthlyBody,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
account := clineTestAccount(400)
|
||||
repo := &commandCodeRateLimitRepo{}
|
||||
shouldDisable := NewRateLimitService(repo, nil, &config.Config{}, nil, nil).HandleUpstreamError(
|
||||
context.Background(), account, http.StatusBadRequest, http.Header{}, []byte(body), "cline-pass/INFERENCE_CAP_ERROR")
|
||||
|
||||
require.False(t, shouldDisable)
|
||||
require.Empty(t, repo.modelLimits)
|
||||
require.Zero(t, repo.setErrorCalls)
|
||||
require.Zero(t, repo.tempCalls)
|
||||
require.False(t, account.isModelRateLimitedWithContext(context.Background(), "cline-pass/glm-5.3"))
|
||||
require.False(t, account.isModelRateLimitedWithContext(context.Background(), "anthropic/claude-sonnet-4-6"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleUpstreamError_Cline429EchoedKeywordsDoNotCoolWallet(t *testing.T) {
|
||||
for name, body := range map[string]string{
|
||||
"message without code": `{"error":{"message":"Model INFERENCE_CAP_ERROR not found"}}`,
|
||||
"metadata model": `{"error":{"code":429,"message":"Rate limit exceeded","metadata":{"model":"SPEND_LIMIT_EXCEEDED"}}}`,
|
||||
"request model": `{"error":{"code":429,"message":"Rate limit exceeded"},"request":{"model":"insufficient_credits"}}`,
|
||||
"plain text": `Model SPEND_LIMIT_EXCEEDED not found`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
repo := &commandCodeRateLimitRepo{}
|
||||
NewRateLimitService(repo, nil, &config.Config{}, nil, nil).HandleUpstreamError(context.Background(),
|
||||
clineTestAccount(429), http.StatusTooManyRequests, http.Header{}, []byte(body), "deepseek/deepseek-v4-flash")
|
||||
require.Empty(t, repo.modelLimits)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleUpstreamError_ClineStructuredErrorsPreserveCooldown(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, model, body, scope, reason string
|
||||
status int
|
||||
wait time.Duration
|
||||
}{
|
||||
{
|
||||
name: "credits code before echoed metadata", model: "deepseek/deepseek-v4-flash",
|
||||
body: `{"error":{"code":"insufficient_credits","message":"Insufficient credits","metadata":{"model":"SPEND_LIMIT_EXCEEDED"}}}`,
|
||||
scope: clineCreditsRateLimitKey, reason: clineCreditsReason, status: http.StatusPaymentRequired, wait: cnBalanceCheckCooldown(nil),
|
||||
},
|
||||
{
|
||||
name: "spend code before pass wording", model: "deepseek/deepseek-v4-flash",
|
||||
body: `{"error":{"code":"SPEND_LIMIT_EXCEEDED","message":"You have reached your monthly ClinePass limit. Please try again later."}}`,
|
||||
scope: clineCreditsRateLimitKey, reason: clineSpendLimitReason, status: http.StatusTooManyRequests, wait: clineLimitRecheck,
|
||||
},
|
||||
{
|
||||
name: "details spend code", model: "deepseek/deepseek-v4-flash",
|
||||
body: `{"error":{"code":429,"message":"Rate limit exceeded","details":{"code":"SPEND_LIMIT_EXCEEDED"}}}`,
|
||||
scope: clineCreditsRateLimitKey, reason: clineSpendLimitReason, status: http.StatusTooManyRequests, wait: clineLimitRecheck,
|
||||
},
|
||||
{
|
||||
name: "inference code", model: "cline-pass/glm-5.3", body: clineInferenceCapBody,
|
||||
scope: clinePassRateLimitKey, reason: clineInferenceCapReason, status: http.StatusTooManyRequests, wait: clineLimitRecheck,
|
||||
},
|
||||
{
|
||||
name: "pass message ignores metadata window", model: "cline-pass/glm-5.3",
|
||||
body: `{"error":{"code":429,"metadata":{"message":"You have reached your monthly ClinePass limit. Please try again later."},"message":"You have reached your 5-hour ClinePass limit. Please try again later."}}`,
|
||||
scope: clinePassRateLimitKey, reason: clinePassLimitReason, status: http.StatusTooManyRequests, wait: clineLimitRecheck,
|
||||
},
|
||||
{
|
||||
name: "details pass message", model: "cline-pass/glm-5.3",
|
||||
body: `{"error":{"code":429,"message":"Rate limit exceeded","details":{"message":"You have reached your monthly ClinePass limit. Please try again later."}}}`,
|
||||
scope: clinePassRateLimitKey, reason: clinePassLimitReason, status: http.StatusTooManyRequests, wait: clinePassMonthlyRecheck,
|
||||
},
|
||||
{
|
||||
name: "details entitlement message", model: "cline-pass/glm-5.3",
|
||||
body: `{"error":{"code":403,"message":"Forbidden","details":{"message":"The user is not subscribed to required model plan"}}}`,
|
||||
scope: clinePassRateLimitKey, reason: clinePassUnavailableReason, status: http.StatusForbidden, wait: clineLimitRecheck,
|
||||
},
|
||||
{
|
||||
name: "free message ignores metadata retry", model: "cline-free/kimi-k3",
|
||||
body: `{"error":{"code":429,"metadata":{"message":"Try again in 20h"},"message":"Free limit reached on model cline-free/kimi-k3. Try again in 5m"}}`,
|
||||
scope: "cline-free/kimi-k3", reason: clineFreeModelLimitReason, status: http.StatusTooManyRequests, wait: 5 * time.Minute,
|
||||
},
|
||||
{
|
||||
name: "details free message", model: "cline-free/kimi-k3",
|
||||
body: `{"error":{"code":429,"message":"Rate limit exceeded","details":{"message":"Free limit reached on model cline-free/kimi-k3. Try again in 3h 20m"}}}`,
|
||||
scope: "cline-free/kimi-k3", reason: clineFreeModelLimitReason, status: http.StatusTooManyRequests, wait: 3*time.Hour + 20*time.Minute,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
repo := &commandCodeRateLimitRepo{}
|
||||
account := clineTestAccount(430)
|
||||
shouldDisable := NewRateLimitService(repo, nil, &config.Config{}, nil, nil).HandleUpstreamError(
|
||||
context.Background(), account, tc.status, http.Header{}, []byte(tc.body), tc.model)
|
||||
|
||||
require.False(t, shouldDisable)
|
||||
require.Len(t, repo.modelLimits, 1)
|
||||
require.WithinDuration(t, time.Now().Add(tc.wait), repo.modelLimits[tc.scope], time.Second)
|
||||
require.True(t, strings.HasPrefix(repo.reasons[tc.scope], tc.reason), repo.reasons[tc.scope])
|
||||
require.Zero(t, repo.setErrorCalls)
|
||||
require.Zero(t, repo.tempCalls)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
@@ -153,9 +154,17 @@ func (s *RateLimitService) handleCNProviderInsufficientBalance(
|
||||
// 默认 20 分钟)。周期任务会在余额恢复后提前清除,故此处只需保证冷却覆盖到下一次
|
||||
// 周期检测即可。
|
||||
func (s *RateLimitService) cnBalanceCooldownDuration() time.Duration {
|
||||
if s == nil {
|
||||
return cnBalanceCheckCooldown(nil)
|
||||
}
|
||||
return cnBalanceCheckCooldown(s.cfg)
|
||||
}
|
||||
|
||||
// cnBalanceCheckCooldown 返回余额类冷却时长(= 2× 余额检测周期,默认周期 10 分钟)。
|
||||
func cnBalanceCheckCooldown(cfg *config.Config) time.Duration {
|
||||
minutes := 10
|
||||
if s != nil && s.cfg != nil {
|
||||
if cfgMin := s.cfg.Gateway.CNProviders.BalanceCheckIntervalMinutes; cfgMin > 0 {
|
||||
if cfg != nil {
|
||||
if cfgMin := cfg.Gateway.CNProviders.BalanceCheckIntervalMinutes; cfgMin > 0 {
|
||||
minutes = cfgMin
|
||||
}
|
||||
}
|
||||
@@ -175,12 +184,20 @@ func cnProviderQuotaSnapshotReset(account *Account, now time.Time) *time.Time {
|
||||
if account == nil || len(account.Extra) == 0 {
|
||||
return nil
|
||||
}
|
||||
if !account.IsOpenCodeGo() && (!account.IsCNProvider() || !account.IsCodingPlan()) {
|
||||
switch {
|
||||
case account.IsOpenCodeGo():
|
||||
case account.IsCommandCode():
|
||||
// 有充值积分时上游跳过窗口检查,429 与窗口无关。
|
||||
if !commandCodeWindowsBinding(account.Extra) {
|
||||
return nil
|
||||
}
|
||||
case account.IsCNProvider() && account.IsCodingPlan():
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
provider := account.Platform
|
||||
suffixes := []string{cnExtraSuffix5hReset, cnExtraSuffixWeeklyReset}
|
||||
if account.IsOpenCodeGo() {
|
||||
if cnQuotaHasMonthlyWindow(provider) {
|
||||
suffixes = append(suffixes, cnExtraSuffixMonthlyReset)
|
||||
}
|
||||
var earliest *time.Time
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Command Code 用量超限的响应式处理,依据官方错误说明
|
||||
// (https://commandcode.ai/docs/troubleshooting/errors):
|
||||
//
|
||||
// - Rate limit:短时间请求过多,很快恢复,走默认 429 逻辑;
|
||||
// - Usage exceeded,三种来源:
|
||||
// 1. 5 小时 / 每周滚动窗口用满,文案如
|
||||
// "You've reached your 5-hour usage limit. Resets in 2h 41m (3:00 PM)";
|
||||
// 2. 月度积分耗尽;
|
||||
// 3. 组织为成员设的花费上限,分成员总额度与成员某个模型的额度两种,后者文案如
|
||||
// "You've reached the $10.00/mo spending limit your organization set for GLM-5. It resets in 3 days."
|
||||
//
|
||||
// 文档没有给出状态码与响应体结构,因此按文案分类,402 / 403 / 429 同样处理;
|
||||
// 页面路径中的 usage_exceeded 可能是错误码,一并识别。未识别的错误交回默认逻辑。
|
||||
//
|
||||
// 窗口用满写带原因的临时停调(而非 SetRateLimited):充值积分不受滚动窗口限制,
|
||||
// 额度探测发现充值积分后只清除这一类停调(见 queryCommandCodeUsage)。
|
||||
|
||||
type commandCodeUsageErrorKind int
|
||||
|
||||
const (
|
||||
commandCodeUsageErrorNone commandCodeUsageErrorKind = iota
|
||||
// commandCodeUsageWindowLimit 滚动窗口用满:冷却到窗口重置。
|
||||
commandCodeUsageWindowLimit
|
||||
// commandCodeUsageCreditsExhausted 积分耗尽:可恢复停调,积分恢复后由周期检测解除。
|
||||
commandCodeUsageCreditsExhausted
|
||||
// commandCodeUsageSpendLimit 组织花费上限:模型级只限当前模型,成员总额度按账号冷却。
|
||||
commandCodeUsageSpendLimit
|
||||
)
|
||||
|
||||
const (
|
||||
// commandCodeUsageLimitReason 是窗口用满临时停调的原因前缀,充值后据此只清除这一类停调。
|
||||
commandCodeUsageLimitReason = "command_code_usage_limit"
|
||||
commandCodeSpendLimitReason = "command_code_spend_limit"
|
||||
// 从文案解析出的重置时长上限:窗口最长为每周,花费上限最长按月。
|
||||
commandCodeMaxWindowCooldown = 8 * 24 * time.Hour
|
||||
commandCodeMaxSpendLimitCooldown = 32 * 24 * time.Hour
|
||||
// commandCodeAccountSpendLimitRecheck 是账号级花费上限(或作用域不明)的最长冷却:
|
||||
// 管理员可能随时调高上限,到期后由下一次请求重新确认。
|
||||
commandCodeAccountSpendLimitRecheck = time.Hour
|
||||
)
|
||||
|
||||
// commandCodeModelSpendLimitPattern 匹配组织为成员某个模型设的花费上限
|
||||
// ("... spending limit your organization set for GLM-5.");成员总额度没有 "for <模型>"。
|
||||
var commandCodeModelSpendLimitPattern = regexp.MustCompile(`(?i)spending limit your organization set for\s+([^.\s][^.]*)`)
|
||||
|
||||
// commandCodeSpendLimitIsModelScoped 报告花费上限是否只针对单个模型。
|
||||
func commandCodeSpendLimitIsModelScoped(body []byte) bool {
|
||||
match := commandCodeModelSpendLimitPattern.FindSubmatch(body)
|
||||
if match == nil {
|
||||
return false
|
||||
}
|
||||
target := strings.ToLower(strings.TrimSpace(string(match[1])))
|
||||
return target != "" && !strings.HasPrefix(target, "you")
|
||||
}
|
||||
|
||||
func classifyCommandCodeUsageError(body []byte) commandCodeUsageErrorKind {
|
||||
text := strings.ToLower(string(body))
|
||||
switch {
|
||||
case strings.Contains(text, "spending limit"):
|
||||
return commandCodeUsageSpendLimit
|
||||
case strings.Contains(text, "usage limit"):
|
||||
return commandCodeUsageWindowLimit
|
||||
case cnProviderResponseIndicatesInsufficientBalance(body),
|
||||
strings.Contains(text, "insufficient credit"),
|
||||
strings.Contains(text, "out of credits"),
|
||||
strings.Contains(text, "usage_exceeded"),
|
||||
strings.Contains(text, "usage exceeded"):
|
||||
return commandCodeUsageCreditsExhausted
|
||||
default:
|
||||
return commandCodeUsageErrorNone
|
||||
}
|
||||
}
|
||||
|
||||
// commandCodeResetAt 解析文案中的 "Resets in 2h 41m" / "resets in 3 days";无法解析
|
||||
// 或超过 maxWait 时返回 nil。
|
||||
func commandCodeResetAt(body []byte, now time.Time, maxWait time.Duration) *time.Time {
|
||||
after := parseOpenCodeGoUsageLimitResetDuration(extractUpstreamErrorMessage(body))
|
||||
if after <= 0 {
|
||||
after = parseOpenCodeGoUsageLimitResetDuration(string(body))
|
||||
}
|
||||
if after <= 0 || after > maxWait {
|
||||
return nil
|
||||
}
|
||||
until := now.Add(after)
|
||||
return &until
|
||||
}
|
||||
|
||||
// handleCommandCodeUsageError 处理已识别的 Command Code 用量超限;handled=false 时由
|
||||
// 调用方继续走默认逻辑。shouldDisable 与同类状态码的既有口径一致:429 不置位;
|
||||
// 只限单个模型时也不置位,避免调用方把整个账号拉黑。
|
||||
func (s *RateLimitService) handleCommandCodeUsageError(
|
||||
ctx context.Context,
|
||||
account *Account,
|
||||
statusCode int,
|
||||
responseBody []byte,
|
||||
upstreamMsg string,
|
||||
) (handled, shouldDisable bool) {
|
||||
accountWide := statusCode != http.StatusTooManyRequests
|
||||
now := time.Now()
|
||||
switch classifyCommandCodeUsageError(responseBody) {
|
||||
case commandCodeUsageWindowLimit:
|
||||
until := commandCodeResetAt(responseBody, now, commandCodeMaxWindowCooldown)
|
||||
if until == nil {
|
||||
until = cnProviderQuotaSnapshotReset(account, now)
|
||||
}
|
||||
if until == nil {
|
||||
return false, false
|
||||
}
|
||||
reason := commandCodeUsageLimitReason
|
||||
if msg := strings.TrimSpace(upstreamMsg); msg != "" {
|
||||
reason += ": " + msg
|
||||
}
|
||||
s.notifyAccountSchedulingBlocked(account, *until, commandCodeUsageLimitReason)
|
||||
if err := s.accountRepo.SetTempUnschedulable(ctx, account.ID, *until, reason); err != nil {
|
||||
slog.Warn("command_code_usage_limit_set_failed", "account_id", account.ID, "error", err)
|
||||
return false, false
|
||||
}
|
||||
slog.Info("command_code_usage_limit", "account_id", account.ID, "status_code", statusCode, "reset_at", until.UTC())
|
||||
return true, accountWide
|
||||
case commandCodeUsageCreditsExhausted:
|
||||
s.handleCNProviderInsufficientBalance(ctx, account, upstreamMsg)
|
||||
return true, accountWide
|
||||
case commandCodeUsageSpendLimit:
|
||||
return true, s.handleCommandCodeSpendLimit(ctx, account, statusCode, responseBody, now)
|
||||
default:
|
||||
return false, false
|
||||
}
|
||||
}
|
||||
|
||||
// handleCommandCodeSpendLimit 处理组织花费上限:文案指明模型且请求模型已知时只限该
|
||||
// 模型,冷却到文案中的重置时间;成员总额度或作用域不明时整个账号冷却,但最长
|
||||
// commandCodeAccountSpendLimitRecheck,避免管理员调高上限后账号仍停用数天,也不会
|
||||
// 因累积 403 被永久禁用。
|
||||
func (s *RateLimitService) handleCommandCodeSpendLimit(ctx context.Context, account *Account, statusCode int, responseBody []byte, now time.Time) (shouldDisable bool) {
|
||||
reset := commandCodeResetAt(responseBody, now, commandCodeMaxSpendLimitCooldown)
|
||||
modelKey := modelRateLimitKeyForUpstreamModelNotFound(ctx, account, tempUnschedulableModel(ctx, nil))
|
||||
if modelKey != "" && commandCodeSpendLimitIsModelScoped(responseBody) {
|
||||
until := reset
|
||||
if until == nil {
|
||||
fallback, ok := s.get429FallbackCooldown(ctx, account)
|
||||
if !ok || fallback <= 0 {
|
||||
fallback = time.Duration(defaultRateLimit429CooldownSeconds) * time.Second
|
||||
}
|
||||
next := now.Add(fallback)
|
||||
until = &next
|
||||
}
|
||||
if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, modelKey, *until, commandCodeSpendLimitReason); err != nil {
|
||||
slog.Warn("command_code_spend_limit_set_failed", "account_id", account.ID, "model", modelKey, "error", err)
|
||||
}
|
||||
slog.Info("command_code_spend_limit", "account_id", account.ID, "model", modelKey, "status_code", statusCode, "reset_at", until.UTC())
|
||||
return false
|
||||
}
|
||||
until := now.Add(commandCodeAccountSpendLimitRecheck)
|
||||
if reset != nil && reset.Before(until) {
|
||||
until = *reset
|
||||
}
|
||||
s.notifyAccountSchedulingBlocked(account, until, commandCodeSpendLimitReason)
|
||||
if err := s.accountRepo.SetTempUnschedulable(ctx, account.ID, until, commandCodeSpendLimitReason); err != nil {
|
||||
slog.Warn("command_code_spend_limit_set_failed", "account_id", account.ID, "error", err)
|
||||
}
|
||||
slog.Info("command_code_spend_limit", "account_id", account.ID, "status_code", statusCode, "until", until.UTC())
|
||||
return statusCode != http.StatusTooManyRequests
|
||||
}
|
||||
@@ -399,6 +399,28 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc
|
||||
upstreamMsg = truncateForLog([]byte(upstreamMsg), 512)
|
||||
}
|
||||
|
||||
// Command Code 用量超限按文案区分、与状态码无关(见 ratelimit_command_code.go);
|
||||
// 未识别的错误(含普通频率限制)继续走下面的默认逻辑。
|
||||
if account.IsCommandCode() && (statusCode == http.StatusPaymentRequired ||
|
||||
statusCode == http.StatusForbidden || statusCode == http.StatusTooManyRequests) {
|
||||
if handled, disable := s.handleCommandCodeUsageError(ctx, account, statusCode, responseBody, upstreamMsg); handled {
|
||||
return disable
|
||||
}
|
||||
}
|
||||
// Cline 积分、花费上限与 ClinePass 超限按结构化错误区分,只冷却对应的钱包。
|
||||
// 400 是请求错误,不能因回显的模型名或请求内容触发钱包冷却。
|
||||
if account.IsCline() && (statusCode == http.StatusPaymentRequired ||
|
||||
statusCode == http.StatusForbidden || statusCode == http.StatusTooManyRequests) {
|
||||
if s.handleClineError(ctx, account, statusCode, responseBody, upstreamMsg) {
|
||||
return false
|
||||
}
|
||||
// 402 只会是积分不足:冷却没写进去也不能落到下面的 402 默认分支——那里永久置
|
||||
// status=error,而周期探测只覆盖激活账号,充值后无法自动恢复。
|
||||
if statusCode == http.StatusPaymentRequired {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
switch statusCode {
|
||||
case 400:
|
||||
// "organization has been disabled" → 永久禁用
|
||||
@@ -515,9 +537,10 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc
|
||||
shouldDisable = true
|
||||
}
|
||||
case 402:
|
||||
// 国产供应商:余额不足是可恢复状态(充值/检测恢复后由周期任务自动解除),
|
||||
// 不能走 handleAuthError 永久置 status=error。改为可恢复的临时停调。
|
||||
if account.IsCNProvider() || account.IsOpenCodeZen() {
|
||||
// 国产供应商 / OpenCode Zen / Command Code:余额(积分)不足是可恢复状态
|
||||
// (充值/检测恢复后由周期任务自动解除),不能走 handleAuthError 永久置
|
||||
// status=error。改为可恢复的临时停调。
|
||||
if account.IsCNProvider() || account.IsOpenCodeZen() || account.IsCommandCode() {
|
||||
s.handleCNProviderInsufficientBalance(ctx, account, upstreamMsg)
|
||||
shouldDisable = true
|
||||
break
|
||||
@@ -1000,10 +1023,10 @@ func (s *RateLimitService) handle403(ctx context.Context, account *Account, upst
|
||||
s.handleCNProviderQuotaExhausted403(ctx, account, upstreamMsg)
|
||||
return true
|
||||
}
|
||||
// 国产供应商、openai 与 ollama_cloud 同口径:HTML 403(CDN/代理拦截页)不构成账号
|
||||
// 失效证据,且 403 在 failover 状态集里会被逐账号重放——直接 SetError 会让一个
|
||||
// 坏请求/一层坏代理连环永久禁用整组账号。走 HTML 豁免 + N 次累计 + 临时冷却。
|
||||
if account.Platform == PlatformOpenAI || IsCNProvider(account.Platform) || account.IsOpenCodeGo() || account.IsOllamaCloud() {
|
||||
// 国产供应商与 openai 同口径:HTML 403(CDN/代理拦截页)不构成账号失效证据,
|
||||
// 且 403 在 failover 状态集里会被逐账号重放——直接 SetError 会让一个坏请求/
|
||||
// 一层坏代理连环永久禁用整组账号。走 HTML 豁免 + N 次累计 + 临时冷却。
|
||||
if account.Platform == PlatformOpenAI || account.IsMultiProtocolAPIKey() {
|
||||
return s.handleOpenAI403(ctx, account, upstreamMsg, responseBody)
|
||||
}
|
||||
// 非 Antigravity 平台:保持原有行为
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
)
|
||||
|
||||
@@ -608,10 +609,10 @@ func (s *SchedulerSnapshotService) handleBulkAccountEvent(ctx context.Context, p
|
||||
continue
|
||||
}
|
||||
accountGroupIDs := s.normalizeGroupIDs(account.GroupIDs)
|
||||
switch account.Platform {
|
||||
case PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud:
|
||||
switch {
|
||||
case account.Platform != PlatformAntigravity && isConcreteRequestPlatform(account.Platform):
|
||||
addPlatformGroups(account.Platform, accountGroupIDs)
|
||||
case PlatformAntigravity:
|
||||
case account.Platform == PlatformAntigravity:
|
||||
// 批量更新可能刚关闭 mixed_scheduling,仍需清理两个兼容平台的旧快照。
|
||||
addPlatformGroups(PlatformAntigravity, accountGroupIDs)
|
||||
addPlatformGroups(PlatformAnthropic, accountGroupIDs)
|
||||
@@ -824,11 +825,9 @@ func (s *SchedulerSnapshotService) rebuildByAccount(ctx context.Context, account
|
||||
return s.rebuildBuckets(ctx, buckets, reason)
|
||||
}
|
||||
|
||||
// schedulerSnapshotPlatforms 是 canonical 桶覆盖的平台全集:新增 concrete
|
||||
// platform 必须同时扩展本数组与 scheduler_snapshot 的批量变更 switch(否则
|
||||
// 桶不在 canonical 集里、rebuild 不覆盖 → 缓存永不命中)。
|
||||
func schedulerSnapshotPlatforms() [12]string {
|
||||
return [12]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformOllamaCloud}
|
||||
// schedulerSnapshotPlatforms 返回需要维护调度快照的全部具体平台(平台清单)。
|
||||
func schedulerSnapshotPlatforms() []string {
|
||||
return domain.CompositePrecedencePlatformIDs()
|
||||
}
|
||||
|
||||
// 生命周期辅助函数有意排除 group0;full rebuild 构造 group0 canonical 集时必须显式调用 canonical helper。
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Record the routing golden from the pinned main source, never the checkout."""
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
|
||||
def format_golden(fixture):
|
||||
"""Keep observations readable and wrap case indexes in compact rows."""
|
||||
metadata = {key: value for key, value in fixture.items() if key != "results"}
|
||||
prefix = json.dumps(metadata, ensure_ascii=False, indent=2)[:-2]
|
||||
indexes = fixture["results"]
|
||||
rows = [" " + ", ".join(map(str, indexes[i:i + 32])) for i in range(0, len(indexes), 32)]
|
||||
return (prefix + ',\n "results": [\n' + ",\n".join(rows) + "\n ]\n}\n").encode("utf-8")
|
||||
|
||||
|
||||
def main():
|
||||
repo = Path(__file__).resolve().parents[4]
|
||||
driver = repo / "backend/internal/service/upstream_protocol_routing_matrix_test.go"
|
||||
source = driver.read_text()
|
||||
revision = re.search(r'const routingMatrixMainRevision = "([0-9a-f]{40})"', source).group(1)
|
||||
subprocess.run(["git", "cat-file", "-e", revision + "^{commit}"], cwd=repo, check=True)
|
||||
archive = subprocess.check_output(["git", "archive", revision, "backend"], cwd=repo)
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="sub2api-routing-main-") as scratch:
|
||||
root = Path(scratch)
|
||||
with tarfile.open(fileobj=io.BytesIO(archive)) as files:
|
||||
files.extractall(root, filter="data")
|
||||
recording_driver = root / "backend/internal/service/upstream_protocol_routing_matrix_test.go"
|
||||
recording_driver.write_text(source + r'''
|
||||
|
||||
func TestRecordUpstreamProtocolRoutingMainGolden(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
data, err := json.MarshalIndent(captureRoutingMatrixGolden(), "", " ")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.WriteFile(os.Getenv("ROUTING_MATRIX_RECORD_OUTPUT"), append(data, '\n'), 0o644))
|
||||
}
|
||||
''')
|
||||
output = root / "routing_main_golden.json"
|
||||
environment = dict(os.environ, ROUTING_MATRIX_RECORD_OUTPUT=str(output))
|
||||
subprocess.run(
|
||||
["go", "test", "-tags", "unit", "./internal/service/", "-run", "^TestRecordUpstreamProtocolRoutingMainGolden$", "-count=1"],
|
||||
cwd=root / "backend", env=environment, check=True,
|
||||
)
|
||||
data = output.read_bytes()
|
||||
fixture = json.loads(data)
|
||||
if fixture["source_revision"] != revision:
|
||||
raise RuntimeError("Recorded source revision differs from the pinned revision")
|
||||
destination = driver.parent / "testdata/upstream_protocol_routing_main_golden.json"
|
||||
destination.write_bytes(format_golden(fixture))
|
||||
print(f"Recorded {fixture['case_count']} cases from {revision} into {destination}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+3931
File diff suppressed because it is too large.
Load diff
@@ -19,6 +19,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
@@ -626,9 +627,7 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac
|
||||
return s.persistProbeFailure(ctx, account, intervalMinutes, now, 0, "missing_api_key", 0)
|
||||
}
|
||||
baseURL := account.GetCredential("base_url")
|
||||
// 多协议 adaptive 账号(CN 供应商 / ollama_cloud)的探测 base 与出站
|
||||
// base 同源:优先读 api_base_urls 分协议地址,而不是 legacy credentials.base_url。
|
||||
if (account.IsCNProvider() || account.IsOllamaCloud()) && account.IsAdaptiveAPIProtocol() {
|
||||
if account.RoutesProtocolByInbound() && account.IsAdaptiveAPIProtocol() {
|
||||
baseURL = account.GetCNProtocolBaseURL(APIProtocolChatCompletions)
|
||||
}
|
||||
if account.Platform == PlatformOpenAI {
|
||||
@@ -1010,17 +1009,7 @@ func decodeUpstreamBillingProbeSnapshot(extra map[string]any) *UpstreamBillingPr
|
||||
// type=apikey by the admin form, so only pre-existing type=upstream rows
|
||||
// cannot turn the probe on.
|
||||
func IsUpstreamBillingProbeIdentity(platform, accountType string) bool {
|
||||
if accountType != AccountTypeAPIKey {
|
||||
return false
|
||||
}
|
||||
switch platform {
|
||||
case PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo,
|
||||
PlatformTypeSafe, PlatformOllamaCloud:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return accountType == AccountTypeAPIKey && domain.IsConcretePlatform(platform)
|
||||
}
|
||||
|
||||
func isUpstreamBillingProbeAccount(account *Account) bool {
|
||||
@@ -1058,6 +1047,8 @@ var upstreamBillingProbeOfficialAPIDomains = []string{
|
||||
"deepseek.com",
|
||||
"opencode.ai",
|
||||
"typesafe.ai",
|
||||
"commandcode.ai",
|
||||
"cline.bot",
|
||||
}
|
||||
|
||||
func upstreamBillingProbeTargetIsOfficialAPI(baseURL string) bool {
|
||||
|
||||
@@ -625,7 +625,7 @@ func upstreamModelRegistryBaseURL(account *Account) string {
|
||||
return ""
|
||||
}
|
||||
switch {
|
||||
case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo() || account.IsOllamaCloud():
|
||||
case account.IsOpenAI() || account.IsMultiProtocolAPIKey():
|
||||
return account.GetOpenAIFormatBaseURL()
|
||||
case account.IsGrok():
|
||||
return account.GetGrokBaseURL()
|
||||
@@ -798,9 +798,8 @@ func (s *AccountTestService) buildUpstreamModelsRequest(ctx context.Context, acc
|
||||
return s.buildAntigravityAPIKeyModelsRequest(ctx, account)
|
||||
case account.IsGrok():
|
||||
return s.buildGrokUpstreamModelsRequest(ctx, account)
|
||||
case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo() || account.IsOllamaCloud():
|
||||
// 国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)、OpenCode Go 与
|
||||
// Ollama Cloud 复用 OpenAI /v1/models 探测。
|
||||
case account.IsOpenAI() || account.IsMultiProtocolAPIKey():
|
||||
// 多协议 API Key 供应商(国产厂商与聚合平台)复用 OpenAI /v1/models 探测。
|
||||
return s.buildOpenAIUpstreamModelsRequest(ctx, account)
|
||||
case account.IsGemini():
|
||||
return s.buildGeminiUpstreamModelsRequest(ctx, account)
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/apicompat"
|
||||
)
|
||||
|
||||
// resolveUpstreamProtocol 决定 OpenAI 网关本次请求发往上游的协议
|
||||
// (chat_completions / responses / anthropic),是 /v1/responses、
|
||||
// /v1/chat/completions、/v1/messages 三个入站入口共用的唯一判定。
|
||||
// 只做判断,不改写请求体、不发请求;各入口再按「入站 × 上游」选择转换路径。
|
||||
//
|
||||
// inbound 为入站协议;/v1/chat/completions 收到 Responses 形状请求体时按
|
||||
// responses 计。model 仅按模型分流的账号使用,取 upstreamRoutingModel 的结果。
|
||||
// catalog 为上游模型目录给出的该模型支持的协议(见 model_protocol_catalog.go),未知时为 nil。
|
||||
//
|
||||
// 优先级:
|
||||
// 1. 按模型分流的供应商(多模型聚合平台,如 OpenCode、Command Code):显式
|
||||
// api_protocol 直接生效;否则先得到该模型支持的协议集合(见 modelProtocolSet),
|
||||
// 入站协议在集合中时同协议直通,不在时走集合首项(首选协议)。
|
||||
// 2. adaptive(按入站协议分流):供应商提供入站协议的原生端点则走同协议,
|
||||
// 否则回落 Chat Completions。
|
||||
// 3. 显式 anthropic 协议 → Anthropic。
|
||||
// 4. shouldForwardOpenAIResponsesViaRawChatCompletions(显式 chat_completions、
|
||||
// 探针确认不支持 Responses 等)→ Chat Completions。
|
||||
// 5. 其余 → Responses。
|
||||
//
|
||||
// Grok 在 Responses / Chat Completions 入口有专属链路,须在调用本函数前分流。
|
||||
func resolveUpstreamProtocol(account *Account, inbound, model string, catalog []string) string {
|
||||
if account.routesByModel() {
|
||||
return account.resolveModelRoutedProtocolFor(model, inbound, catalog)
|
||||
}
|
||||
if account.IsAdaptiveAPIProtocol() {
|
||||
if account.providerSupportsProtocol(inbound) {
|
||||
return inbound
|
||||
}
|
||||
return APIProtocolChatCompletions
|
||||
}
|
||||
if account.IsAnthropicProtocol() {
|
||||
return APIProtocolAnthropic
|
||||
}
|
||||
if shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
|
||||
return APIProtocolChatCompletions
|
||||
}
|
||||
return APIProtocolResponses
|
||||
}
|
||||
|
||||
// resolveModelRoutedProtocol 返回按模型分流账号对该模型的首选上游协议(不考虑入站
|
||||
// 协议与上游模型目录),供连接测试等没有入站协议的场景使用。
|
||||
func (a *Account) resolveModelRoutedProtocol(model string) string {
|
||||
return a.resolveModelRoutedProtocolFor(model, "", nil)
|
||||
}
|
||||
|
||||
// resolveModelRoutedProtocolFor 按模型名解析按模型分流账号的上游协议:显式 pinned
|
||||
// 协议直接生效;否则取该模型支持的协议集合,入站协议在其中时同协议直通(省去一次
|
||||
// 协议转换),不在时走首选协议。
|
||||
func (a *Account) resolveModelRoutedProtocolFor(model, inbound string, catalog []string) string {
|
||||
switch proto := a.GetAPIProtocol(); proto {
|
||||
case APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses:
|
||||
return proto
|
||||
}
|
||||
set := a.modelProtocolSet(model, catalog)
|
||||
if slices.Contains(set, inbound) {
|
||||
return inbound
|
||||
}
|
||||
return set[0]
|
||||
}
|
||||
|
||||
// modelProtocolSet 返回模型支持的上游协议集合(首项为首选),来源依次为:
|
||||
// 1. 账号 protocol_rules 中命中的规则(管理员显式配置);
|
||||
// 2. 上游模型目录(catalog):首选沿用内置规则对该模型的首选(在集合内时),否则取目录首项;
|
||||
// 3. profile 内置规则——仅在账号未配置 protocol_rules 时,已配置但未命中视为有意不走内置规则;
|
||||
// 4. Chat Completions,避免落入 Responses 转换链。
|
||||
func (a *Account) modelProtocolSet(model string, catalog []string) []string {
|
||||
rules, configured := a.configuredProtocolRules()
|
||||
if configured {
|
||||
if set, ok := matchProtocolRuleSet(model, rules); ok {
|
||||
return set
|
||||
}
|
||||
}
|
||||
profileRules := a.providerProfile().Endpoints(a.GetCredential("account_mode")).ProtocolRules
|
||||
if set := a.supportedCatalogProtocols(catalog); len(set) > 0 {
|
||||
preferred := matchProtocolRules(model, profileRules)
|
||||
if slices.Contains(set, preferred) {
|
||||
return normalizeProtocolSet(preferred, set)
|
||||
}
|
||||
return set
|
||||
}
|
||||
if !configured {
|
||||
if set, ok := matchProtocolRuleSet(model, profileRules); ok {
|
||||
return set
|
||||
}
|
||||
}
|
||||
return []string{APIProtocolChatCompletions}
|
||||
}
|
||||
|
||||
// supportedCatalogProtocols 过滤出账号接入模式确有原生端点的目录协议。
|
||||
func (a *Account) supportedCatalogProtocols(catalog []string) []string {
|
||||
out := make([]string, 0, len(catalog))
|
||||
for _, protocol := range catalog {
|
||||
if isNativeUpstreamProtocol(protocol) && a.providerSupportsProtocol(protocol) && !slices.Contains(out, protocol) {
|
||||
out = append(out, protocol)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// upstreamRoutingModel 返回参与协议分流的模型名:仅按模型分流的账号需要,按账号
|
||||
// 模型映射与上游归一后的名字匹配规则;其余账号的分流与模型无关,返回空串。
|
||||
func upstreamRoutingModel(account *Account, body []byte, defaultMappedModel string) string {
|
||||
if !account.routesByModel() {
|
||||
return ""
|
||||
}
|
||||
return resolveMappedUpstreamModel(account, body, defaultMappedModel)
|
||||
}
|
||||
|
||||
// convertResponsesShapedChatBody 把发到 /v1/chat/completions 的 Responses 形状
|
||||
// 请求体(Cursor 兼容)转换为 Chat Completions 请求体。
|
||||
func (s *OpenAIGatewayService) convertResponsesShapedChatBody(body []byte) ([]byte, error) {
|
||||
var responsesReq apicompat.ResponsesRequest
|
||||
if err := json.Unmarshal(body, &responsesReq); err != nil {
|
||||
return nil, fmt.Errorf("parse responses-shaped chat completions request: %w", err)
|
||||
}
|
||||
chatReq, err := apicompat.ResponsesToChatCompletionsRequestWithOptions(
|
||||
&responsesReq,
|
||||
&apicompat.ResponsesToChatOptions{ReasoningContentByID: s.reasoningContentByID},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("convert responses-shaped chat completions request: %w", err)
|
||||
}
|
||||
chatBody, err := json.Marshal(chatReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal converted chat completions request: %w", err)
|
||||
}
|
||||
return chatBody, nil
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// The fixture is captured through the real gateway entry points on this main
|
||||
// revision, before provider profiles and resolveUpstreamProtocol were added.
|
||||
// Expected results never call routing helpers from the implementation under test.
|
||||
// Regenerate with python3 testdata/record_upstream_protocol_routing_main.py, which exports
|
||||
// this pinned revision before compiling and recording the same matrix driver.
|
||||
const routingMatrixMainRevision = "5fc0e486c3f6a8a191b8bd140f39b60457f611cf"
|
||||
const routingMatrixGoldenPath = "testdata/upstream_protocol_routing_main_golden.json"
|
||||
|
||||
type routingMatrixIngress struct {
|
||||
name string
|
||||
path string
|
||||
responsesBody bool
|
||||
forward func(*OpenAIGatewayService, *gin.Context, *Account, []byte) error
|
||||
}
|
||||
|
||||
func routingMatrixIngresses() []routingMatrixIngress {
|
||||
return []routingMatrixIngress{
|
||||
{
|
||||
name: "responses", path: "/v1/responses", responsesBody: true,
|
||||
forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error {
|
||||
_, err := svc.Forward(context.Background(), c, account, body)
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "chat", path: "/v1/chat/completions",
|
||||
forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error {
|
||||
_, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "chat_responses_shape", path: "/v1/chat/completions", responsesBody: true,
|
||||
forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error {
|
||||
_, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "messages", path: "/v1/messages",
|
||||
forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error {
|
||||
_, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "")
|
||||
return err
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type routingMatrixCase struct {
|
||||
platform string
|
||||
apiProtocol string
|
||||
mode string
|
||||
accountType string
|
||||
probe string
|
||||
addresses string
|
||||
rules bool
|
||||
ingress routingMatrixIngress
|
||||
model string
|
||||
}
|
||||
|
||||
func (tc routingMatrixCase) key() string {
|
||||
return fmt.Sprintf("%s|proto=%s|mode=%s|type=%s|probe=%s|addresses=%s|rules=%t|%s|%s",
|
||||
tc.platform, tc.apiProtocol, tc.mode, tc.accountType, tc.probe, tc.addresses, tc.rules, tc.ingress.name, tc.model)
|
||||
}
|
||||
|
||||
func (tc routingMatrixCase) account() *Account {
|
||||
credentials := map[string]any{"api_key": "sk-test"}
|
||||
if tc.addresses == "base" || tc.addresses == "both" {
|
||||
credentials["base_url"] = "http://base.example"
|
||||
}
|
||||
if tc.addresses == "split" || tc.addresses == "both" {
|
||||
credentials["api_base_urls"] = map[string]any{
|
||||
APIProtocolChatCompletions: "http://cc.example",
|
||||
APIProtocolResponses: "http://responses.example",
|
||||
APIProtocolAnthropic: "http://anthropic.example",
|
||||
}
|
||||
}
|
||||
if tc.apiProtocol != "" {
|
||||
credentials["api_protocol"] = tc.apiProtocol
|
||||
}
|
||||
if tc.mode != "" {
|
||||
credentials["account_mode"] = tc.mode
|
||||
}
|
||||
if tc.rules {
|
||||
credentials["protocol_rules"] = []any{
|
||||
map[string]any{"pattern": "glm-*", "protocol": APIProtocolAnthropic},
|
||||
map[string]any{"pattern": "gpt-*", "protocol": APIProtocolResponses},
|
||||
}
|
||||
}
|
||||
if tc.platform == PlatformOpenCodeGo {
|
||||
credentials["model_mapping"] = map[string]any{
|
||||
"mapped-gpt": "gpt-5.6-luna",
|
||||
"mapped-unsupported": "gemini-3.8-flash",
|
||||
}
|
||||
}
|
||||
extra := map[string]any{}
|
||||
switch tc.probe {
|
||||
case "yes":
|
||||
extra[openai_compat.ExtraKeyResponsesSupported] = true
|
||||
case "no":
|
||||
extra[openai_compat.ExtraKeyResponsesSupported] = false
|
||||
}
|
||||
return &Account{
|
||||
ID: 801, Name: "routing-matrix", Platform: tc.platform, Type: tc.accountType,
|
||||
Concurrency: 1, Credentials: credentials, Extra: extra,
|
||||
}
|
||||
}
|
||||
|
||||
func (tc routingMatrixCase) body() []byte {
|
||||
switch {
|
||||
case tc.ingress.responsesBody:
|
||||
return []byte(fmt.Sprintf(`{"model":%q,"input":"hello","max_output_tokens":32,"stream":false}`, tc.model))
|
||||
case tc.ingress.name == "messages":
|
||||
return []byte(fmt.Sprintf(`{"model":%q,"max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":false}`, tc.model))
|
||||
default:
|
||||
return []byte(fmt.Sprintf(`{"model":%q,"messages":[{"role":"user","content":"hello"}],"stream":false}`, tc.model))
|
||||
}
|
||||
}
|
||||
|
||||
func routingMatrixCases() []routingMatrixCase {
|
||||
var cases []routingMatrixCase
|
||||
protocols := []string{"", APIProtocolAdaptive, APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses, "invalid"}
|
||||
types := []string{AccountTypeAPIKey, AccountTypeUpstream, AccountTypeOAuth}
|
||||
probes := []string{"", "yes", "no"}
|
||||
addresses := []string{"none", "base", "split", "both"}
|
||||
add := func(platform string, modes, models []string, rulesOptions []bool, probeOptions, typeOptions []string, ingresses []routingMatrixIngress) {
|
||||
for _, proto := range protocols {
|
||||
for _, mode := range modes {
|
||||
for _, accountType := range typeOptions {
|
||||
for _, probe := range probeOptions {
|
||||
for _, address := range addresses {
|
||||
for _, rules := range rulesOptions {
|
||||
for _, ingress := range ingresses {
|
||||
for _, model := range models {
|
||||
cases = append(cases, routingMatrixCase{
|
||||
platform: platform, apiProtocol: proto, mode: mode, accountType: accountType,
|
||||
probe: probe, addresses: address, rules: rules, ingress: ingress, model: model,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
all := routingMatrixIngresses()
|
||||
modes := []string{"", AccountModePayG, AccountModeCoding, "invalid"}
|
||||
for _, provider := range []struct{ platform, model string }{
|
||||
{PlatformKimi, "kimi-k2"}, {PlatformZhipu, "glm-4.7"},
|
||||
{PlatformDeepseek, "deepseek-chat"}, {PlatformMiniMax, "minimax-m3"},
|
||||
} {
|
||||
add(provider.platform, modes, []string{provider.model, " " + provider.model + " "}, []bool{false}, probes, types, all)
|
||||
}
|
||||
add(PlatformOpenAI, []string{""}, []string{"gpt-5", " gpt-5 "}, []bool{false}, probes, types, all)
|
||||
add(PlatformOpenCodeGo, []string{"", AccountModeGo, AccountModeZen, "invalid"},
|
||||
[]string{"gpt-5.6-luna", "minimax-m3", "glm-5.3", "claude-sonnet-4", "qwen3.8-max", "qwen3.8-flash",
|
||||
"gemini-3.8-flash", "jev-1.13", " opencode/gpt-5.6-luna ", "mapped-gpt", "mapped-unsupported"},
|
||||
[]bool{false, true}, []string{"", "no"}, []string{AccountTypeAPIKey, AccountTypeUpstream}, all)
|
||||
// Grok has its own Responses and Chat Completions implementations; only the
|
||||
// Messages entry uses the routing logic covered by this compatibility matrix.
|
||||
add(PlatformGrok, []string{""}, []string{"grok-4", " grok-4 "}, []bool{false}, probes, types, all[3:])
|
||||
return cases
|
||||
}
|
||||
|
||||
type routingUpstreamRequest struct {
|
||||
URL string `json:"url"`
|
||||
Authorization string `json:"authorization,omitempty"`
|
||||
APIKey string `json:"api_key,omitempty"`
|
||||
AnthropicVersion string `json:"anthropic_version,omitempty"`
|
||||
BodyKind string `json:"body_kind"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
|
||||
type routingObservation struct {
|
||||
Requests []routingUpstreamRequest `json:"upstream,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Panic string `json:"panic,omitempty"`
|
||||
Status int `json:"status"`
|
||||
ClientErrorType string `json:"client_error_type,omitempty"`
|
||||
ClientErrorCode string `json:"client_error_code,omitempty"`
|
||||
ClientErrorMessage string `json:"client_error_message,omitempty"`
|
||||
}
|
||||
|
||||
func (o routingObservation) String() string {
|
||||
data, _ := json.Marshal(o)
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func observeRouting(tc routingMatrixCase) (obs routingObservation) {
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
body := tc.body()
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, tc.ingress.path, bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
obs.Panic = fmt.Sprint(r)
|
||||
}
|
||||
for i, req := range upstream.requests {
|
||||
kind := "other"
|
||||
switch {
|
||||
case gjson.GetBytes(upstream.bodies[i], "messages").Exists():
|
||||
kind = "messages"
|
||||
case gjson.GetBytes(upstream.bodies[i], "input").Exists():
|
||||
kind = "input"
|
||||
}
|
||||
obs.Requests = append(obs.Requests, routingUpstreamRequest{
|
||||
URL: req.URL.String(), Authorization: req.Header.Get("Authorization"),
|
||||
APIKey: req.Header.Get("X-Api-Key"), AnthropicVersion: req.Header.Get("Anthropic-Version"),
|
||||
BodyKind: kind, Model: gjson.GetBytes(upstream.bodies[i], "model").String(),
|
||||
})
|
||||
}
|
||||
obs.Status = c.Writer.Status()
|
||||
obs.ClientErrorType = gjson.Get(recorder.Body.String(), "error.type").String()
|
||||
obs.ClientErrorCode = gjson.Get(recorder.Body.String(), "error.code").String()
|
||||
obs.ClientErrorMessage = gjson.Get(recorder.Body.String(), "error.message").String()
|
||||
}()
|
||||
err := tc.ingress.forward(svc, c, tc.account(), body)
|
||||
if err != nil {
|
||||
obs.Error = err.Error()
|
||||
}
|
||||
return obs
|
||||
}
|
||||
|
||||
// Cases share many outcomes. Store each distinct observation once, then one
|
||||
// observation index per case in routingMatrixCases order. The key digest detects
|
||||
// any change to case identity or ordering, so matrix edits require a new capture.
|
||||
type routingMatrixGolden struct {
|
||||
SourceRevision string `json:"source_revision"`
|
||||
CaseCount int `json:"case_count"`
|
||||
CaseKeysSHA256 string `json:"case_keys_sha256"`
|
||||
Observations []routingObservation `json:"observations"`
|
||||
Results []int `json:"results"`
|
||||
}
|
||||
|
||||
func routingMatrixCaseDigest(cases []routingMatrixCase) string {
|
||||
var keys strings.Builder
|
||||
for _, tc := range cases {
|
||||
keys.WriteString(tc.key())
|
||||
keys.WriteByte('\n')
|
||||
}
|
||||
return fmt.Sprintf("%x", sha256.Sum256([]byte(keys.String())))
|
||||
}
|
||||
|
||||
func captureRoutingMatrixGolden() routingMatrixGolden {
|
||||
cases := routingMatrixCases()
|
||||
golden := routingMatrixGolden{SourceRevision: routingMatrixMainRevision, CaseCount: len(cases), CaseKeysSHA256: routingMatrixCaseDigest(cases)}
|
||||
indexByObservation := make(map[string]int)
|
||||
for _, tc := range cases {
|
||||
obs := observeRouting(tc)
|
||||
key := obs.String()
|
||||
index, ok := indexByObservation[key]
|
||||
if !ok {
|
||||
index = len(golden.Observations)
|
||||
golden.Observations = append(golden.Observations, obs)
|
||||
indexByObservation[key] = index
|
||||
}
|
||||
golden.Results = append(golden.Results, index)
|
||||
}
|
||||
return golden
|
||||
}
|
||||
|
||||
// Zhipu has no Responses endpoint. The refactor routes adaptive /responses to
|
||||
// Chat Completions even for unsupported upstream/oauth account types. Both
|
||||
// versions reject these accounts before transport, with these exact errors.
|
||||
// Only this complete before/after observation is permitted; other no-upstream
|
||||
// results and new panics still fail the golden comparison.
|
||||
func matchesKnownZhipuNonAPIKeyDifference(tc routingMatrixCase, want, got routingObservation) bool {
|
||||
if tc.platform != PlatformZhipu || tc.apiProtocol != APIProtocolAdaptive || tc.ingress.name != "responses" {
|
||||
return false
|
||||
}
|
||||
var oldError string
|
||||
switch tc.accountType {
|
||||
case AccountTypeUpstream:
|
||||
oldError = "unsupported account type: upstream"
|
||||
case AccountTypeOAuth:
|
||||
oldError = "access_token not found in credentials"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return reflect.DeepEqual(want, routingObservation{Error: oldError, Status: http.StatusOK}) &&
|
||||
reflect.DeepEqual(got, routingObservation{Error: "account 801 missing api_key", Status: http.StatusOK})
|
||||
}
|
||||
|
||||
func TestUpstreamProtocolRoutingMatrixMatchesMainGolden(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
data, err := os.ReadFile(routingMatrixGoldenPath)
|
||||
require.NoError(t, err)
|
||||
var golden routingMatrixGolden
|
||||
require.NoError(t, json.Unmarshal(data, &golden))
|
||||
cases := routingMatrixCases()
|
||||
require.Equal(t, routingMatrixMainRevision, golden.SourceRevision)
|
||||
require.Equal(t, len(cases), golden.CaseCount)
|
||||
require.Equal(t, routingMatrixCaseDigest(cases), golden.CaseKeysSHA256)
|
||||
require.Len(t, golden.Results, len(cases))
|
||||
|
||||
var differences []string
|
||||
mismatched := 0
|
||||
knownDifferences := 0
|
||||
for i, tc := range cases {
|
||||
index := golden.Results[i]
|
||||
require.GreaterOrEqual(t, index, 0)
|
||||
require.Less(t, index, len(golden.Observations))
|
||||
want := golden.Observations[index]
|
||||
got := observeRouting(tc)
|
||||
if reflect.DeepEqual(want, got) {
|
||||
continue
|
||||
}
|
||||
if matchesKnownZhipuNonAPIKeyDifference(tc, want, got) {
|
||||
knownDifferences++
|
||||
continue
|
||||
}
|
||||
mismatched++
|
||||
if len(differences) < 12 {
|
||||
differences = append(differences, fmt.Sprintf("%s\nmain: %s\ncurrent: %s", tc.key(), want, got))
|
||||
}
|
||||
}
|
||||
require.Zero(t, mismatched, "routing differs from main %s in %d cases:\n%s", golden.SourceRevision, mismatched, strings.Join(differences, "\n"))
|
||||
// 2 account types × 4 modes × 3 probe states × 4 address configurations ×
|
||||
// 2 model spellings. A disappeared or expanded exception requires review.
|
||||
require.Equal(t, 192, knownDifferences, "unexpected change to the declared Zhipu non-API-Key difference")
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func routingTestAccount(platform, accountType string, credentials, extra map[string]any) *Account {
|
||||
if credentials == nil {
|
||||
credentials = map[string]any{}
|
||||
}
|
||||
credentials["api_key"] = "sk-test"
|
||||
return &Account{Platform: platform, Type: accountType, Credentials: credentials, Extra: extra}
|
||||
}
|
||||
|
||||
func TestResolveUpstreamProtocol(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const (
|
||||
cc = APIProtocolChatCompletions
|
||||
responses = APIProtocolResponses
|
||||
anthropic = APIProtocolAnthropic
|
||||
)
|
||||
adaptive := func(platform string) *Account {
|
||||
return routingTestAccount(platform, AccountTypeAPIKey, map[string]any{"api_protocol": APIProtocolAdaptive}, nil)
|
||||
}
|
||||
pinned := func(platform, protocol string) *Account {
|
||||
return routingTestAccount(platform, AccountTypeAPIKey, map[string]any{"api_protocol": protocol}, nil)
|
||||
}
|
||||
openCode := func(mode string, credentials map[string]any) *Account {
|
||||
if credentials == nil {
|
||||
credentials = map[string]any{}
|
||||
}
|
||||
credentials["account_mode"] = mode
|
||||
return routingTestAccount(PlatformOpenCodeGo, AccountTypeAPIKey, credentials, nil)
|
||||
}
|
||||
openAIWithProbe := func(accountType string, supported any) *Account {
|
||||
extra := map[string]any{}
|
||||
if supported != nil {
|
||||
extra[openai_compat.ExtraKeyResponsesSupported] = supported
|
||||
}
|
||||
return routingTestAccount(PlatformOpenAI, accountType, nil, extra)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
account *Account
|
||||
inbound string
|
||||
model string
|
||||
want string
|
||||
}{
|
||||
// 按入站协议分流(国产单一厂商 adaptive)
|
||||
{"kimi adaptive anthropic inbound", adaptive(PlatformKimi), anthropic, "", anthropic},
|
||||
{"kimi adaptive cc inbound", adaptive(PlatformKimi), cc, "", cc},
|
||||
{"kimi adaptive responses inbound", adaptive(PlatformKimi), responses, "", responses},
|
||||
{"zhipu adaptive responses inbound falls back to cc", adaptive(PlatformZhipu), responses, "", cc},
|
||||
{"zhipu adaptive anthropic inbound", adaptive(PlatformZhipu), anthropic, "", anthropic},
|
||||
|
||||
// 显式固定协议,与入站无关
|
||||
{"kimi pinned anthropic", pinned(PlatformKimi, anthropic), cc, "", anthropic},
|
||||
{"kimi pinned cc", pinned(PlatformKimi, cc), responses, "", cc},
|
||||
{"kimi pinned responses", pinned(PlatformKimi, responses), anthropic, "", responses},
|
||||
{"zhipu pinned responses is unsupported and stays cc", pinned(PlatformZhipu, responses), responses, "", cc},
|
||||
|
||||
// 按模型分流(多模型聚合平台),与入站无关
|
||||
{"opencode go gpt", openCode(AccountModeGo, nil), anthropic, "gpt-5.6-luna", responses},
|
||||
{"opencode go minimax", openCode(AccountModeGo, nil), responses, "minimax-m3", anthropic},
|
||||
{"opencode go glm falls back to cc", openCode(AccountModeGo, nil), anthropic, "glm-5.3", cc},
|
||||
{"opencode go claude has no rule", openCode(AccountModeGo, nil), anthropic, "claude-sonnet-4", cc},
|
||||
{"opencode zen claude", openCode(AccountModeZen, nil), cc, "claude-sonnet-4", anthropic},
|
||||
{"opencode account rules override defaults", openCode(AccountModeGo, map[string]any{
|
||||
"protocol_rules": []any{map[string]any{"pattern": "glm-*", "protocol": anthropic}},
|
||||
}), cc, "glm-5.3", anthropic},
|
||||
{"opencode account rules miss falls back to cc", openCode(AccountModeGo, map[string]any{
|
||||
"protocol_rules": []any{map[string]any{"pattern": "glm-*", "protocol": anthropic}},
|
||||
}), cc, "gpt-5.6-luna", cc},
|
||||
{"opencode pinned protocol beats rules", openCode(AccountModeGo, map[string]any{"api_protocol": cc}), anthropic, "gpt-5.6-luna", cc},
|
||||
{"opencode ignores responses probe", func() *Account {
|
||||
account := openCode(AccountModeGo, nil)
|
||||
account.Extra = map[string]any{openai_compat.ExtraKeyResponsesSupported: false}
|
||||
return account
|
||||
}(), cc, "gpt-5.6-luna", responses},
|
||||
|
||||
// 无 profile 的账号按探针决定 Responses / CC
|
||||
{"openai apikey unknown probe", openAIWithProbe(AccountTypeAPIKey, nil), cc, "", responses},
|
||||
{"openai apikey probe unsupported", openAIWithProbe(AccountTypeAPIKey, false), anthropic, "", cc},
|
||||
{"openai oauth ignores probe", openAIWithProbe(AccountTypeOAuth, false), cc, "", responses},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
require.Equal(t, tc.want, resolveUpstreamProtocol(tc.account, tc.inbound, tc.model, nil), tc.name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutesByModelOnlyForAggregators(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
aggregators := map[string]bool{PlatformOpenCodeGo: true, PlatformCommandCode: true}
|
||||
for platform, profile := range providerProfiles {
|
||||
account := &Account{Platform: platform}
|
||||
require.Equal(t, aggregators[platform], account.routesByModel(), platform)
|
||||
require.Equal(t, aggregators[platform], profile.Routing == ProviderRoutingByModel, platform)
|
||||
}
|
||||
require.False(t, (&Account{Platform: PlatformOpenAI}).routesByModel())
|
||||
require.False(t, (*Account)(nil).routesByModel())
|
||||
}
|
||||
|
||||
func TestUpstreamRoutingModelOnlyForModelRoutedAccounts(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
body := []byte(`{"model":"gpt-5.6-luna","input":"hi"}`)
|
||||
openCode := routingTestAccount(PlatformOpenCodeGo, AccountTypeAPIKey, map[string]any{
|
||||
"model_mapping": map[string]any{"gpt-5.6-luna": "glm-5.3"},
|
||||
}, nil)
|
||||
require.Equal(t, "glm-5.3", upstreamRoutingModel(openCode, body, ""))
|
||||
require.Empty(t, upstreamRoutingModel(routingTestAccount(PlatformKimi, AccountTypeAPIKey, nil, nil), body, ""))
|
||||
}
|
||||
|
||||
// /v1/responses 转 Anthropic 上游时,计费模型名与上游模型名都应是去除首尾空白的
|
||||
// 请求模型;按模型分流(OpenCode)与显式 anthropic 协议(Kimi)账号行为一致。
|
||||
func TestResponsesToNativeAnthropicTrimsBillingModel(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
openCode := &Account{
|
||||
ID: 703,
|
||||
Name: "opencode-go",
|
||||
Platform: PlatformOpenCodeGo,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"account_mode": AccountModeGo,
|
||||
"api_base_urls": map[string]any{
|
||||
APIProtocolAnthropic: "http://anthropic.example",
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
account *Account
|
||||
model string
|
||||
}{
|
||||
{"opencode by model", openCode, "minimax-m3"},
|
||||
{"kimi pinned anthropic", nativeAnthropicTestAccount(), "kimi-k2"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
body := []byte(`{"model":" ` + tc.model + ` ","input":"hello","stream":false}`)
|
||||
upstream := &httpUpstreamRecorder{resp: nativeAnthropicStreamResponse()}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
|
||||
result, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", body), tc.account, body)
|
||||
require.NoError(t, err)
|
||||
require.True(t, strings.HasSuffix(upstream.lastReq.URL.Path, "/v1/messages"), upstream.lastReq.URL.String())
|
||||
require.Equal(t, tc.model, gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
require.Equal(t, tc.model, result.BillingModel)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
-- 平台白名单改由应用层的平台清单(internal/domain/platforms.go)统一校验,
|
||||
-- 新增平台不再需要修改数据库约束的迁移。
|
||||
--
|
||||
-- 1. user_platform_quotas.platform:admin 接口 / 设置校验 service.AllowedQuotaPlatforms,
|
||||
-- repository 写入前校验 domain.IsConcretePlatform,ent schema Validate 同源。
|
||||
-- 2. composite_model_routes.target_platform:admin 接口 binding、service
|
||||
-- compositeRouteFromInput 与 ent schema Validate 均校验为已登记的具体平台。
|
||||
--
|
||||
-- channel_monitors / channel_monitor_request_templates 的 provider CHECK 表示
|
||||
-- 渠道监控已实现的探测能力,不属于平台清单,保留不动。
|
||||
--
|
||||
-- DROP ... IF EXISTS 保证可重入。
|
||||
|
||||
ALTER TABLE user_platform_quotas
|
||||
DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check;
|
||||
|
||||
ALTER TABLE composite_model_routes
|
||||
DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check;
|
||||
@@ -1,77 +0,0 @@
|
||||
-- 把 Ollama Cloud 加入平台白名单。
|
||||
--
|
||||
-- 1. user_platform_quotas.platform CHECK
|
||||
-- 2. composite_model_routes.target_platform CHECK
|
||||
-- 3. channel_monitors / channel_monitor_request_templates provider CHECK
|
||||
--
|
||||
-- 顺序:必须晚于 241_add_typesafe_platform.sql。上游 241 把前两个平台 CHECK 覆写为
|
||||
-- 11 项(含 typesafe、不含 ollama_cloud),本迁移在其后重建为 12 项,即 241 的平台
|
||||
-- 集合 ∪ {ollama_cloud}。两张监控表的 provider CHECK 以 238_opencode_go_platform.sql
|
||||
-- 的 10 项为基准(typesafe 不是对话模型,不进 provider 白名单),并集 'ollama_cloud'。
|
||||
--
|
||||
-- DROP ... IF EXISTS + 幂等守卫保证可重入;新约束是旧约束的超集,存量行瞬时通过校验,
|
||||
-- 因此是默认的 validated 约束。零 DML 回填:与 237/238/241 一致,只放宽约束,不写任何
|
||||
-- DML。监控表的守卫以 pg_get_constraintdef 探测:约束已含 ollama_cloud 时整段跳过,避免
|
||||
-- 无谓重建。
|
||||
--
|
||||
-- 适用 fresh 建库、空表升级与已应用 241 的环境。若库中已存在 platform='ollama_cloud'
|
||||
-- 的行,说明其写入发生在更宽松的旧约束下,需在启动前停写核对;本迁移不做数据修复,
|
||||
-- 也不能替代该前置处置。
|
||||
|
||||
ALTER TABLE user_platform_quotas
|
||||
DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check;
|
||||
|
||||
ALTER TABLE user_platform_quotas
|
||||
ADD CONSTRAINT user_platform_quotas_platform_check
|
||||
CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok',
|
||||
'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe',
|
||||
'ollama_cloud'));
|
||||
|
||||
ALTER TABLE composite_model_routes
|
||||
DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check;
|
||||
|
||||
ALTER TABLE composite_model_routes
|
||||
ADD CONSTRAINT composite_model_routes_target_platform_check
|
||||
CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok',
|
||||
'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe',
|
||||
'ollama_cloud'));
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
monitor_constraint_def TEXT;
|
||||
template_constraint_def TEXT;
|
||||
BEGIN
|
||||
SELECT pg_get_constraintdef(c.oid)
|
||||
INTO monitor_constraint_def
|
||||
FROM pg_constraint c
|
||||
JOIN pg_class t ON t.oid = c.conrelid
|
||||
WHERE t.relname = 'channel_monitors'
|
||||
AND c.conname = 'channel_monitors_provider_check';
|
||||
|
||||
IF monitor_constraint_def IS NULL OR position('ollama_cloud' IN monitor_constraint_def) = 0 THEN
|
||||
ALTER TABLE channel_monitors
|
||||
DROP CONSTRAINT IF EXISTS channel_monitors_provider_check;
|
||||
ALTER TABLE channel_monitors
|
||||
ADD CONSTRAINT channel_monitors_provider_check
|
||||
CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok',
|
||||
'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go',
|
||||
'ollama_cloud'));
|
||||
END IF;
|
||||
|
||||
SELECT pg_get_constraintdef(c.oid)
|
||||
INTO template_constraint_def
|
||||
FROM pg_constraint c
|
||||
JOIN pg_class t ON t.oid = c.conrelid
|
||||
WHERE t.relname = 'channel_monitor_request_templates'
|
||||
AND c.conname = 'channel_monitor_request_templates_provider_check';
|
||||
|
||||
IF template_constraint_def IS NULL OR position('ollama_cloud' IN template_constraint_def) = 0 THEN
|
||||
ALTER TABLE channel_monitor_request_templates
|
||||
DROP CONSTRAINT IF EXISTS channel_monitor_request_templates_provider_check;
|
||||
ALTER TABLE channel_monitor_request_templates
|
||||
ADD CONSTRAINT channel_monitor_request_templates_provider_check
|
||||
CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok',
|
||||
'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go',
|
||||
'ollama_cloud'));
|
||||
END IF;
|
||||
END $$;
|
||||
@@ -0,0 +1,51 @@
|
||||
-- 把 Ollama Cloud 加入渠道监控 provider 白名单(channel_monitors /
|
||||
-- channel_monitor_request_templates 的 provider CHECK)。
|
||||
--
|
||||
-- 平台白名单(user_platform_quotas.platform、composite_model_routes.target_platform)
|
||||
-- 已由 242_drop_platform_check_constraints.sql 改为应用层按平台清单校验,本迁移
|
||||
-- 不得重建这两个约束。渠道监控 provider 表示已实现的探测能力,仍由数据库约束维护:
|
||||
-- 以 238_opencode_go_platform.sql 的 10 项为基准并集 'ollama_cloud'(typesafe 不是
|
||||
-- 对话模型,不进 provider 白名单)。
|
||||
--
|
||||
-- 守卫以 pg_get_constraintdef 探测:约束已含 ollama_cloud 时整段跳过,保证可重入。
|
||||
-- 新约束是旧约束的超集,存量行瞬时通过校验,因此是默认的 validated 约束。零 DML。
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
monitor_constraint_def TEXT;
|
||||
template_constraint_def TEXT;
|
||||
BEGIN
|
||||
SELECT pg_get_constraintdef(c.oid)
|
||||
INTO monitor_constraint_def
|
||||
FROM pg_constraint c
|
||||
JOIN pg_class t ON t.oid = c.conrelid
|
||||
WHERE t.relname = 'channel_monitors'
|
||||
AND c.conname = 'channel_monitors_provider_check';
|
||||
|
||||
IF monitor_constraint_def IS NULL OR position('ollama_cloud' IN monitor_constraint_def) = 0 THEN
|
||||
ALTER TABLE channel_monitors
|
||||
DROP CONSTRAINT IF EXISTS channel_monitors_provider_check;
|
||||
ALTER TABLE channel_monitors
|
||||
ADD CONSTRAINT channel_monitors_provider_check
|
||||
CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok',
|
||||
'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go',
|
||||
'ollama_cloud'));
|
||||
END IF;
|
||||
|
||||
SELECT pg_get_constraintdef(c.oid)
|
||||
INTO template_constraint_def
|
||||
FROM pg_constraint c
|
||||
JOIN pg_class t ON t.oid = c.conrelid
|
||||
WHERE t.relname = 'channel_monitor_request_templates'
|
||||
AND c.conname = 'channel_monitor_request_templates_provider_check';
|
||||
|
||||
IF template_constraint_def IS NULL OR position('ollama_cloud' IN template_constraint_def) = 0 THEN
|
||||
ALTER TABLE channel_monitor_request_templates
|
||||
DROP CONSTRAINT IF EXISTS channel_monitor_request_templates_provider_check;
|
||||
ALTER TABLE channel_monitor_request_templates
|
||||
ADD CONSTRAINT channel_monitor_request_templates_provider_check
|
||||
CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok',
|
||||
'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go',
|
||||
'ollama_cloud'));
|
||||
END IF;
|
||||
END $$;
|
||||
@@ -8,12 +8,11 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// ollamaCloudPlatformMigrationFile 是 Ollama Cloud 平台迁移:一次性重建
|
||||
// user_platform_quotas / composite_model_routes / channel_monitors /
|
||||
// channel_monitor_request_templates 四个 CHECK 约束。
|
||||
const ollamaCloudPlatformMigrationFile = "242_ollama_cloud_platform.sql"
|
||||
// ollamaCloudMonitorProviderMigrationFile 把 ollama_cloud 加入渠道监控 provider 白名单。
|
||||
// 平台白名单的两个 CHECK 已由 242 删除,改为应用层按平台清单校验。
|
||||
const ollamaCloudMonitorProviderMigrationFile = "243_ollama_cloud_channel_monitor_provider.sql"
|
||||
|
||||
// dmlStatementPattern 匹配 DML 关键字;242 只允许 DDL 约束变更。
|
||||
// dmlStatementPattern 匹配 DML 关键字;243 只允许 DDL 约束变更。
|
||||
var dmlStatementPattern = regexp.MustCompile(`(?i)\b(insert|update|delete|merge|truncate|copy|upsert)\b`)
|
||||
|
||||
// stripSQLLineComments 去掉 "--" 行注释,只对可执行语句做结构校验。
|
||||
@@ -34,39 +33,27 @@ func executableSQL(content []byte) string {
|
||||
return strings.Join(strings.Fields(stripSQLLineComments(string(content))), " ")
|
||||
}
|
||||
|
||||
// TestOllamaCloudPlatformMigration 校验 242 一次性重建四个约束:
|
||||
// 两张平台表为 241 的 11 项 ∪ {ollama_cloud}(12 项),两张监控表为 238 的 10 项
|
||||
// ∪ {ollama_cloud}(11 项,typesafe 不是对话模型不进 provider),且只有 DDL、零 DML。
|
||||
func TestOllamaCloudPlatformMigration(t *testing.T) {
|
||||
content, err := FS.ReadFile(ollamaCloudPlatformMigrationFile)
|
||||
// TestOllamaCloudMonitorProviderMigration 校验 243 只重建两张监控表的 provider CHECK
|
||||
// (238 的 10 项 ∪ {ollama_cloud},不含 typesafe),不触碰 242 已删除的平台 CHECK,且零 DML。
|
||||
func TestOllamaCloudMonitorProviderMigration(t *testing.T) {
|
||||
content, err := FS.ReadFile(ollamaCloudMonitorProviderMigrationFile)
|
||||
require.NoError(t, err)
|
||||
sql := executableSQL(content)
|
||||
|
||||
sql := strings.Join(strings.Fields(string(content)), " ")
|
||||
require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check")
|
||||
require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check")
|
||||
require.Contains(t, sql, "channel_monitors_provider_check")
|
||||
require.Contains(t, sql, "channel_monitor_request_templates_provider_check")
|
||||
require.NotContains(t, sql, "user_platform_quotas")
|
||||
require.NotContains(t, sql, "composite_model_routes")
|
||||
|
||||
// 四个约束各自恰好重建一次,不牵连其它约束。
|
||||
require.Equal(t, 4, strings.Count(sql, "ADD CONSTRAINT"), "242 只应新增四个约束")
|
||||
require.Equal(t, 4, strings.Count(sql, "CHECK ("), "242 只应包含四个 CHECK")
|
||||
|
||||
// 两张平台表:241 的平台集合 ∪ {ollama_cloud},必须同时保留 typesafe 与 ollama_cloud。
|
||||
require.Contains(t, sql,
|
||||
"CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'ollama_cloud'))")
|
||||
require.Contains(t, sql,
|
||||
"CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'ollama_cloud'))")
|
||||
|
||||
// 两张监控表:238 的 provider 集合 ∪ {ollama_cloud},不含 typesafe。
|
||||
require.Equal(t, 2, strings.Count(sql, "ADD CONSTRAINT"), "243 只应重建两个监控表约束")
|
||||
require.Equal(t, 2, strings.Count(sql,
|
||||
"CHECK (provider IN ('openai', 'anthropic', 'gemini', 'grok', 'antigravity', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'ollama_cloud'))"),
|
||||
"两张监控表应重建为同一个 provider 集合(不含 typesafe)")
|
||||
|
||||
// 监控表的两段保留幂等守卫:约束已含 ollama_cloud 时跳过重建。
|
||||
// 幂等守卫:约束已含 ollama_cloud 时跳过重建。
|
||||
require.Contains(t, sql, "position('ollama_cloud' IN monitor_constraint_def) = 0")
|
||||
require.Contains(t, sql, "position('ollama_cloud' IN template_constraint_def) = 0")
|
||||
|
||||
// 约束必须是默认 validated(非 NOT VALID),且整个文件只有 DDL。
|
||||
require.NotContains(t, sql, "NOT VALID", "平台 CHECK 必须是 validated 约束")
|
||||
require.NotRegexp(t, dmlStatementPattern, executableSQL(content), "242 不得包含 DML 语句")
|
||||
require.NotContains(t, sql, "NOT VALID", "provider CHECK 必须是 validated 约束")
|
||||
require.NotRegexp(t, dmlStatementPattern, sql, "243 不得包含 DML 语句")
|
||||
}
|
||||
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user