Files
sub2api/backend/internal/service/upstream_protocol_routing_test.go
T
SavitarCandClaude Opus 5.5 e2939cd8fa feat(platform): 接入 Command Code 平台
转发:
- 平台清单与 provider profile 新增 command_code:按模型分流,Chat
  Completions / Responses 基址 https://api.commandcode.ai/provider/v1,
  Anthropic 基址 https://api.commandcode.ai/provider;内置规则 claude-* →
  Anthropic、gpt-* → Responses(也支持 Chat Completions)。
- 原生 Anthropic 端点的版本感知拼接改按分流方式判断,转发与连接测试共用
  (Anthropic 基址带 /v1 时连接测试不再误报为配置错误)。

按模型的协议集合(模型支持入站协议时直通,免去协议转换):
- 分流规则可带协议集合 protocols(首项为首选协议):入站协议在集合中时同
  协议直通,否则走首选协议;只有一个协议时与原规则相同,OpenCode 行为不变。
- profile 新增 model_catalog:Command Code 的 /models 为每个模型给出
  supported_endpoints。官方默认地址的目录按地址全进程共享,自定义上游按账号
  隔离;目录请求的 UA 收敛与账号请求头覆写与转发一致。目录缓存 30 分钟、后台
  刷新,失败退避 5 分钟;从未加载成功时首批请求最多等 2 秒,冷启动也按目录
  分流。账号规则未命中的模型按目录取协议集合;目录不可用时回落内置规则(账号
  未配置规则时)或 Chat Completions。
- 三个入站入口共用的 resolveUpstreamProtocol 增加目录参数。
- 前端分流规则编辑器可为每条规则勾选"也支持"的协议;提供模型目录的平台,
  兜底行改为说明按上游模型列表选协议。

连接测试:
- 按模型分流的平台共用一条测试路径(协议与网关同一判定,含模型目录;默认
  测试模型取自 profile),不再落入 Claude 测试路径。
- 首个分支由"国产厂商"改为"按入站协议分流";adaptive 测试跳过 profile 未
  提供的 Anthropic 端点。现有国产厂商行为不变。
- 连接测试是 OpenCode 专属分流入口的最后一个调用方,改走统一判定后删除
  ResolveOpenCodeGoUpstreamProtocol、openCodeGoNativeProtocol,以及此前就只剩
  测试使用的 OpenCodeGoModelProtocol;路由矩阵的旧行为基准改为测试内独立复述。

额度与余额(/alpha/whoami、billing/credits、billing/subscriptions、
usage/summary):
- 额度探测写入 5 小时 / 每周窗口(限额套餐)与还原出的月度窗口,同时写入
  积分余额;余额探测只取积分。仅对官方主机上的 API Key 账号生效。
- 订阅周期或本周期用量取数失败时保留上一次的月度快照,不当作没有月度窗口
  清掉;窗口尚未开始(没有重置时间)时清掉上一个窗口的重置时间。
- whoami 取不到时探测整体失败,不按个人账户继续(组织账号会查到成员的个人
  钱包,并据此按余额停调)。
- 阈值停调与定时检测纳入 Command Code;有充值积分时上游跳过窗口检查,窗口
  快照不参与停调与冷却;积分低于余额阈值时临时停调。
- 上游计费探测的官方域名加入 commandcode.ai,不把 Key 发往官方主机上并不
  存在的中转计费接口。

上游错误(依据 commandcode.ai/docs/troubleshooting/errors,按文案分类,
402 / 403 / 429 同样处理):
- 5 小时 / 每周窗口用满:带原因的临时停调,到文案中的 "Resets in …",解析
  不出时回落额度快照;充值积分不受窗口限制,额度 / 余额探测发现充值积分后
  只解除这一类停调。
- 积分耗尽(含 usage_exceeded):可恢复的临时停调,积分恢复后由周期检测
  解除,不再永久置为 error。
- 组织花费上限:文案指明模型("set for <模型>")且请求模型已知时只写模型级
  限流;成员总额度或作用域不明时整个账号冷却,最长一小时。
- 普通频率限制走默认 429 逻辑,不再冷却到窗口重置点。

前端:
- 账号列表显示额度窗口与积分余额,阈值设置增加 command_code。单元格可见性
  改为按账号判定,与后端一致:只对官方主机上的 API Key 账号显示,自定义中转
  显示占位符,不再每次打开列表都探测出一行报错。
- 使用官网的官方标志(圆角方块内镂空 ⌘);配色为中性灰(品牌黑色已由
  Grok 使用)。

测试基准中原先用作"仅服务端登记"示例的 command_code 改为虚构的 acme_router;
新增的前端测试加入 CI 前端关键测试列表。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:11:05 +08:00

166 lines
6.8 KiB
Go

//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)
})
}
}