mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
feat(composite): serve cross-family pools via per-account protocol dispatch
解除 composite 候选池的协议族限制:入站任意协议族端点可服务池内任意
平台账号,厂商多协议时优先与入站相同的协议族(零转换),否则协议转换。
- routes:混族/全原生族池不再 400,落 generic 网关按选中账号分发;
全 OpenAI 族池仍走 OpenAI handler(不变)
- generic 调度器放行池:跨平台候选合并选号、池感知平台/模型门、
sticky 复检防塌缩(镜像 OpenAI 族池调度)
- generic 转发 base 协议化:多协议账号打 GetAnthropicProtocolBaseURL
的 {base}/v1/messages(无 ?beta=true、认证/clamp 同源),classic
anthropic 不回归
- generic Messages/Responses/ChatCompletions 循环池化:per-attempt
配额与渠道策略(复用 OpenAI 池策略)、attempt ctx + platform 作用域
渠道映射;纯 OpenAI 族账号按端点委派 OpenAI 网关同族链,usage 适配
进既有计费流;count_tokens 不可计数账号排除重选
- 谓词能力驱动(IsAnthropicProtocol/adaptive/GetAnthropicProtocolBaseURL),
不引入平台硬编码清单,后续多协议平台合入后零改动继承
This commit is contained in:
1 parent
16612cd6a7
commit
7ff8fd3458
14 files changed
+2229
-167
No files matched your search
@@ -0,0 +1,463 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// ---- composite generic Messages/CountTokens 池化(B1)测试 ----
|
||||
//
|
||||
// 构造手法对齐 gateway_handler_warmup_intercept_unit_test.go(真实 GatewayService +
|
||||
// fake scheduler cache / group repo / concurrency cache,RunModeSimple 跳过计费)与
|
||||
// openai_gateway_credential_failover_loop_test.go(fake HTTPUpstream 假上游)。
|
||||
|
||||
// compositePoolUpstreamCall 记录一次假上游调用。
|
||||
type compositePoolUpstreamCall struct {
|
||||
Path string
|
||||
Body []byte
|
||||
Authorization string
|
||||
APIKeyHeader string
|
||||
AccountID int64
|
||||
}
|
||||
|
||||
// compositePoolFakeUpstream 实现 service.HTTPUpstream,按调用序回放构造的响应。
|
||||
type compositePoolFakeUpstream struct {
|
||||
mu sync.Mutex
|
||||
calls []compositePoolUpstreamCall
|
||||
respond func(call compositePoolUpstreamCall, index int) *http.Response
|
||||
}
|
||||
|
||||
func (u *compositePoolFakeUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
|
||||
body, _ := io.ReadAll(req.Body)
|
||||
u.mu.Lock()
|
||||
call := compositePoolUpstreamCall{
|
||||
Path: req.URL.Path,
|
||||
Body: body,
|
||||
Authorization: req.Header.Get("Authorization"),
|
||||
APIKeyHeader: req.Header.Get("x-api-key"),
|
||||
AccountID: accountID,
|
||||
}
|
||||
u.calls = append(u.calls, call)
|
||||
respond := u.respond
|
||||
u.mu.Unlock()
|
||||
if respond != nil {
|
||||
return respond(call, len(u.calls)-1), nil
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusInternalServerError,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"type":"api_error","message":"upstream failed"}}`)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (u *compositePoolFakeUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
return u.Do(req, proxyURL, accountID, concurrency)
|
||||
}
|
||||
|
||||
func (u *compositePoolFakeUpstream) snapshot() []compositePoolUpstreamCall {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
return append([]compositePoolUpstreamCall(nil), u.calls...)
|
||||
}
|
||||
|
||||
// chatCompletionsOKResponse 返回一份带 usage 的非流式 Chat Completions 响应。
|
||||
func chatCompletionsOKResponse(model string, promptTokens, completionTokens int) *http.Response {
|
||||
body := fmt.Sprintf(
|
||||
`{"id":"chatcmpl-pool","object":"chat.completion","created":1,"model":%q,"choices":[{"index":0,"message":{"role":"assistant","content":"hi from %s"},"finish_reason":"stop"}],"usage":{"prompt_tokens":%d,"completion_tokens":%d}}`,
|
||||
model, model, promptTokens, completionTokens)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"req-cc-pool"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}
|
||||
}
|
||||
|
||||
// anthropicMessagesOKResponse 返回一份 Anthropic Messages 成功响应。
|
||||
func anthropicMessagesOKResponse() *http.Response {
|
||||
body := `{"id":"msg_pool_native","type":"message","role":"assistant","model":"claude-sonnet-4-5","content":[{"type":"text","text":"hi from anthropic"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":5}}`
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"req-native-pool"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}
|
||||
}
|
||||
|
||||
// countTokensOKResponse 返回一份 Anthropic count_tokens 成功响应。
|
||||
func countTokensOKResponse() *http.Response {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"input_tokens":42}`)),
|
||||
}
|
||||
}
|
||||
|
||||
// compositePoolUsageLogRepo 捕获 usage_log 写入(RunModeSimple 只走 best-effort 写入)。
|
||||
type compositePoolUsageLogRepo struct {
|
||||
service.UsageLogRepository
|
||||
mu sync.Mutex
|
||||
logs []*service.UsageLog
|
||||
}
|
||||
|
||||
func (r *compositePoolUsageLogRepo) CreateBestEffort(_ context.Context, log *service.UsageLog) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.logs = append(r.logs, log)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *compositePoolUsageLogRepo) snapshot() []*service.UsageLog {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return append([]*service.UsageLog(nil), r.logs...)
|
||||
}
|
||||
|
||||
// compositePoolMessagesHarness 组装 generic Messages/CountTokens 池化测试的 handler。
|
||||
type compositePoolMessagesHarness struct {
|
||||
handler *GatewayHandler
|
||||
group *service.Group
|
||||
openAIUpstream *compositePoolFakeUpstream
|
||||
gwUpstream *compositePoolFakeUpstream
|
||||
usageRepo *compositePoolUsageLogRepo
|
||||
}
|
||||
|
||||
func newCompositePoolMessagesHarness(t *testing.T, accounts []*service.Account) *compositePoolMessagesHarness {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
groupID := int64(41011)
|
||||
group := &service.Group{ID: groupID, Platform: service.PlatformComposite, Status: service.StatusActive, Hydrated: true}
|
||||
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
cfg.Security = config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}
|
||||
|
||||
usageRepo := &compositePoolUsageLogRepo{}
|
||||
openAIUpstream := &compositePoolFakeUpstream{}
|
||||
gwUpstream := &compositePoolFakeUpstream{}
|
||||
|
||||
schedulerCache := &fakeSchedulerCache{accounts: accounts}
|
||||
schedulerSnapshot := service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil)
|
||||
billingService := service.NewBillingService(cfg, nil)
|
||||
|
||||
gatewayService := service.NewGatewayService(
|
||||
nil, // accountRepo:调度走 scheduler snapshot
|
||||
&fakeGroupRepo{group: group},
|
||||
usageRepo, // usageLogRepo:捕获 usage 行
|
||||
nil, nil, nil, nil, // usageBillingRepo / userRepo / userSubRepo / userGroupRateRepo
|
||||
nil, // cache:禁用 sticky
|
||||
cfg,
|
||||
schedulerSnapshot,
|
||||
nil, // concurrencyService:负载感知降级
|
||||
billingService,
|
||||
nil, nil, nil, // rateLimitService / billingCacheService / identityService
|
||||
gwUpstream, // httpUpstream:generic Forward / CountTokens 假上游
|
||||
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
|
||||
openAIGatewayService := service.NewOpenAIGatewayService(
|
||||
nil, nil, nil, nil, nil, nil, nil,
|
||||
cfg,
|
||||
nil, nil,
|
||||
billingService,
|
||||
nil, nil,
|
||||
openAIUpstream, // httpUpstream:委派链假上游
|
||||
nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
|
||||
billingCacheService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCacheService.Stop)
|
||||
|
||||
handler := &GatewayHandler{
|
||||
gatewayService: gatewayService,
|
||||
openAIGatewayService: openAIGatewayService,
|
||||
billingCacheService: billingCacheService,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
|
||||
maxAccountSwitches: 3,
|
||||
cfg: cfg,
|
||||
}
|
||||
return &compositePoolMessagesHarness{
|
||||
handler: handler,
|
||||
group: group,
|
||||
openAIUpstream: openAIUpstream,
|
||||
gwUpstream: gwUpstream,
|
||||
usageRepo: usageRepo,
|
||||
}
|
||||
}
|
||||
|
||||
// newCompositePoolGatewayRequest 构造带候选池 ctx 与 composite 分组身份的请求。
|
||||
func (h *compositePoolMessagesHarness) newRequest(t *testing.T, path, body string, platforms ...string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
ctx := service.WithCompositeCandidatePlatforms(context.Background(), platforms)
|
||||
ctx = context.WithValue(ctx, ctxkey.Group, h.group)
|
||||
req = req.WithContext(ctx)
|
||||
c.Request = req
|
||||
|
||||
apiKey := &service.APIKey{
|
||||
ID: 41012,
|
||||
UserID: 41013,
|
||||
GroupID: &h.group.ID,
|
||||
Status: service.StatusActive,
|
||||
User: &service.User{ID: 41013, Concurrency: 10, Balance: 100},
|
||||
Group: h.group,
|
||||
}
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: apiKey.UserID, Concurrency: 10})
|
||||
return c, rec
|
||||
}
|
||||
|
||||
func poolMessagesBody() string {
|
||||
return `{"model":"my-model","max_tokens":64,"stream":false,"messages":[{"role":"user","content":"hello"}]}`
|
||||
}
|
||||
|
||||
func poolCountTokensBody() string {
|
||||
return `{"model":"my-model","messages":[{"role":"user","content":"hello"}]}`
|
||||
}
|
||||
|
||||
// poolKimiAccount 纯 OpenAI 族(CC 协议)kimi 账号:池选中后委派 ForwardAsAnthropic。
|
||||
func poolKimiAccount(id int64, groupID int64, priority int) *service.Account {
|
||||
return &service.Account{
|
||||
ID: id, Name: fmt.Sprintf("kimi-%d", id), Platform: service.PlatformKimi,
|
||||
Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true,
|
||||
Concurrency: 1, Priority: priority,
|
||||
AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "kimi-key",
|
||||
"base_url": "https://kimi.example/v1",
|
||||
"api_protocol": service.APIProtocolChatCompletions,
|
||||
"model_mapping": map[string]any{"my-model": "kimi-k3"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// poolAnthropicAccount anthropic 原生 APIKey 账号:走既有 generic Forward。
|
||||
func poolAnthropicAccount(id int64, groupID int64, priority int) *service.Account {
|
||||
return &service.Account{
|
||||
ID: id, Name: fmt.Sprintf("anthropic-%d", id), Platform: service.PlatformAnthropic,
|
||||
Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true,
|
||||
Concurrency: 1, Priority: priority,
|
||||
AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "anthropic-key",
|
||||
"base_url": "https://relay.example",
|
||||
"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// poolAdaptiveKimiAccount 多协议 adaptive kimi 账号(Anthropic 协议 base 可解析):
|
||||
// 走既有 generic Forward(service 层协议化 base)。
|
||||
func poolAdaptiveKimiAccount(id int64, groupID int64, priority int) *service.Account {
|
||||
return &service.Account{
|
||||
ID: id, Name: fmt.Sprintf("kimi-adaptive-%d", id), Platform: service.PlatformKimi,
|
||||
Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true,
|
||||
Concurrency: 1, Priority: priority,
|
||||
AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "adaptive-key",
|
||||
"api_protocol": service.APIProtocolAdaptive,
|
||||
"api_base_urls": map[string]any{"anthropic": "https://adaptive.example"},
|
||||
"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 池选中纯 OpenAI 族账号:委派 OpenAIGatewayService.ForwardAsAnthropic 转发(假上游
|
||||
// 收到 Chat Completions 请求),响应以 Anthropic Messages 格式写回,usage 适配进
|
||||
// 既有 RecordUsage 流(token 计数与模型映射链不丢)。
|
||||
func TestCompositePoolMessagesDelegatesPureOpenAIFamilyAccount(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(41101, 41011, 0)})
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return chatCompletionsOKResponse("kimi-k3", 11, 7)
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, "message", gjson.GetBytes(rec.Body.Bytes(), "type").String(),
|
||||
"委派链响应必须是 Anthropic Messages 格式")
|
||||
require.Equal(t, int64(11), gjson.GetBytes(rec.Body.Bytes(), "usage.input_tokens").Int())
|
||||
require.Equal(t, int64(7), gjson.GetBytes(rec.Body.Bytes(), "usage.output_tokens").Int())
|
||||
|
||||
// 假上游收到的是 Chat Completions 请求(协议转换链生效)。
|
||||
calls := h.openAIUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.True(t, strings.HasSuffix(calls[0].Path, "/chat/completions"), "upstream path=%s", calls[0].Path)
|
||||
require.Contains(t, string(calls[0].Body), `"model":"kimi-k3"`, "账号级 model_mapping 必须生效")
|
||||
require.Contains(t, calls[0].Authorization, "kimi-key")
|
||||
|
||||
// 选中账号 ops 记录为 kimi 账号。
|
||||
selected, ok := c.Get(opsAccountIDKey)
|
||||
require.True(t, ok)
|
||||
require.EqualValues(t, 41101, selected)
|
||||
|
||||
// usage 适配记录已提交:token 计数与模型映射链进入 usage 行。
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.Equal(t, 11, logs[0].InputTokens)
|
||||
require.Equal(t, 7, logs[0].OutputTokens)
|
||||
require.EqualValues(t, 41101, logs[0].AccountID)
|
||||
require.Equal(t, "my-model", logs[0].Model, "公开请求模型作为计费/展示模型记录")
|
||||
require.NotNil(t, logs[0].UpstreamModel)
|
||||
require.Equal(t, "kimi-k3", *logs[0].UpstreamModel)
|
||||
}
|
||||
|
||||
// 池选中多协议账号(adaptive,Anthropic 协议 base 可解析):走既有 generic Forward
|
||||
// (假上游收到 {base}/v1/messages 请求),不委派 OpenAI 链。
|
||||
func TestCompositePoolMessagesMultiProtocolAccountUsesGenericForward(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolAdaptiveKimiAccount(41201, 41011, 0)})
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return anthropicMessagesOKResponse()
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, "msg_pool_native", gjson.GetBytes(rec.Body.Bytes(), "id").String())
|
||||
|
||||
calls := h.gwUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.True(t, strings.HasSuffix(calls[0].Path, "/v1/messages"), "upstream path=%s", calls[0].Path)
|
||||
require.False(t, strings.HasSuffix(calls[0].Path, "/chat/completions"))
|
||||
require.Equal(t, "adaptive-key", calls[0].APIKeyHeader, "多协议账号默认 x-api-key 认证")
|
||||
require.Empty(t, h.openAIUpstream.snapshot(), "多协议账号不得委派 OpenAI 链")
|
||||
|
||||
selected, ok := c.Get(opsAccountIDKey)
|
||||
require.True(t, ok)
|
||||
require.EqualValues(t, 41201, selected)
|
||||
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.Equal(t, 12, logs[0].InputTokens)
|
||||
require.Equal(t, 5, logs[0].OutputTokens)
|
||||
}
|
||||
|
||||
// 委派链返回 UpstreamFailoverError:走既有 failover 语义换号重选,改用 anthropic
|
||||
// 原生账号的 generic Forward 完成请求。
|
||||
func TestCompositePoolMessagesDelegationFailoverSwitchesAccount(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{
|
||||
poolKimiAccount(41301, 41011, 0),
|
||||
poolAnthropicAccount(41302, 41011, 5),
|
||||
})
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return anthropicMessagesOKResponse()
|
||||
}
|
||||
// kimi 假上游默认回 500(respond 为 nil 时的兜底响应即 500)。
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, "msg_pool_native", gjson.GetBytes(rec.Body.Bytes(), "id").String(),
|
||||
"failover 后应由 anthropic 原生账号完成请求")
|
||||
|
||||
// 第一次委派失败(CC 上游 500),第二次走 generic Forward。
|
||||
require.Len(t, h.openAIUpstream.snapshot(), 1)
|
||||
require.Len(t, h.gwUpstream.snapshot(), 1)
|
||||
require.True(t, strings.HasSuffix(h.gwUpstream.snapshot()[0].Path, "/v1/messages"))
|
||||
|
||||
selected, ok := c.Get(opsAccountIDKey)
|
||||
require.True(t, ok)
|
||||
require.EqualValues(t, 41302, selected, "ops 记录最终选中的 anthropic 账号")
|
||||
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.EqualValues(t, 41302, logs[0].AccountID)
|
||||
}
|
||||
|
||||
// count_tokens 池请求选中纯 OpenAI 族账号:跳过该账号重选(排除集),而不是对
|
||||
// /v1/messages/count_tokens 报 500。池内无可计数账号时按无可用账号终止。
|
||||
func TestCompositePoolCountTokensSkipsUncountableOpenAIAccount(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(41401, 41011, 0)})
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages/count_tokens", poolCountTokensBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.CountTokens(c)
|
||||
|
||||
require.NotEqual(t, http.StatusOK, rec.Code, "纯 OpenAI 族账号被跳过后按无可用账号终止")
|
||||
require.Empty(t, h.gwUpstream.snapshot(), "不可计数账号不得转发 count_tokens")
|
||||
require.Empty(t, h.openAIUpstream.snapshot())
|
||||
}
|
||||
|
||||
// count_tokens 池请求跳过纯 OpenAI 族账号后改选可计数的 anthropic 账号并成功转发。
|
||||
func TestCompositePoolCountTokensSkipsThenForwardsCountableAccount(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{
|
||||
poolKimiAccount(41501, 41011, 0),
|
||||
poolAnthropicAccount(41502, 41011, 5),
|
||||
})
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return countTokensOKResponse()
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages/count_tokens", poolCountTokensBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.CountTokens(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, int64(42), gjson.GetBytes(rec.Body.Bytes(), "input_tokens").Int())
|
||||
|
||||
calls := h.gwUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.True(t, strings.HasSuffix(calls[0].Path, "/v1/messages/count_tokens"), "upstream path=%s", calls[0].Path)
|
||||
require.Equal(t, "anthropic-key", calls[0].APIKeyHeader)
|
||||
|
||||
selected, ok := c.Get(opsAccountIDKey)
|
||||
require.True(t, ok)
|
||||
require.EqualValues(t, 41502, selected, "ops 记录最终选中的可计数账号")
|
||||
}
|
||||
|
||||
// 池账号委派分发谓词与结果适配器的纯函数契约。
|
||||
func TestCompositePoolAccountDelegationPredicateAndAdapter(t *testing.T) {
|
||||
// 纯 OpenAI 族账号(含 openai/grok/国产 CC 供应商)→ 委派。
|
||||
require.True(t, compositePoolAccountDelegatesToOpenAI(poolKimiAccount(1, 1, 0)))
|
||||
require.True(t, compositePoolAccountDelegatesToOpenAI(&service.Account{Platform: service.PlatformOpenAI}))
|
||||
require.True(t, compositePoolAccountDelegatesToOpenAI(&service.Account{Platform: service.PlatformGrok}))
|
||||
|
||||
// anthropic 原生 / gemini / antigravity → 既有 Forward。
|
||||
require.False(t, compositePoolAccountDelegatesToOpenAI(poolAnthropicAccount(2, 1, 0)))
|
||||
require.False(t, compositePoolAccountDelegatesToOpenAI(&service.Account{Platform: service.PlatformGemini}))
|
||||
require.False(t, compositePoolAccountDelegatesToOpenAI(&service.Account{Platform: service.PlatformAntigravity}))
|
||||
|
||||
// 多协议(adaptive / anthropic-协议)账号 → 既有 Forward(service 协议化 base)。
|
||||
require.False(t, compositePoolAccountDelegatesToOpenAI(poolAdaptiveKimiAccount(3, 1, 0)))
|
||||
require.False(t, compositePoolAccountDelegatesToOpenAI(nil))
|
||||
|
||||
// 结果适配:usage token 计数与元数据逐字段映射,nil 安全。
|
||||
require.Nil(t, adaptOpenAIForwardResultToForwardResult(nil))
|
||||
adapted := adaptOpenAIForwardResultToForwardResult(&service.OpenAIForwardResult{
|
||||
RequestID: "rid",
|
||||
Usage: service.OpenAIUsage{InputTokens: 3, OutputTokens: 4, CacheCreationInputTokens: 5, CacheReadInputTokens: 6},
|
||||
Model: "public",
|
||||
UpstreamModel: "upstream",
|
||||
Stream: true,
|
||||
SearchCount: 2,
|
||||
})
|
||||
require.Equal(t, "rid", adapted.RequestID)
|
||||
require.Equal(t, 3, adapted.Usage.InputTokens)
|
||||
require.Equal(t, 4, adapted.Usage.OutputTokens)
|
||||
require.Equal(t, 5, adapted.Usage.CacheCreationInputTokens)
|
||||
require.Equal(t, 6, adapted.Usage.CacheReadInputTokens)
|
||||
require.Equal(t, "public", adapted.Model)
|
||||
require.Equal(t, "upstream", adapted.UpstreamModel)
|
||||
require.True(t, adapted.Stream)
|
||||
require.Equal(t, 2, adapted.SearchCount)
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// ---- composite generic Responses / ChatCompletions 池化(B2)测试 ----
|
||||
//
|
||||
// 复用 composite_generic_pool_messages_test.go(B1)的假上游 / usage 捕获 / harness
|
||||
// 组装手法:池候选 ctx + composite 分组身份 + RunModeSimple 跳过计费,委派链与
|
||||
// generic 转换链分别挂 openAIUpstream / gwUpstream 假上游。
|
||||
|
||||
func poolResponsesBody() string {
|
||||
return `{"model":"my-model","stream":false,"input":"hello","max_output_tokens":64}`
|
||||
}
|
||||
|
||||
func poolChatCompletionsBody() string {
|
||||
return `{"model":"my-model","stream":false,"messages":[{"role":"user","content":"hello"}]}`
|
||||
}
|
||||
|
||||
// poolKimiResponsesAccount 固定 responses 协议的 kimi 账号(UsesNativeCNResponses):
|
||||
// Responses 入站按原生 Responses 端点委派。
|
||||
func poolKimiResponsesAccount(id int64, groupID int64, priority int) *service.Account {
|
||||
return &service.Account{
|
||||
ID: id, Name: fmt.Sprintf("kimi-resp-%d", id), Platform: service.PlatformKimi,
|
||||
Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true,
|
||||
Concurrency: 1, Priority: priority,
|
||||
AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "kimi-resp-key",
|
||||
"base_url": "https://kimi.example/v1",
|
||||
"api_protocol": service.APIProtocolResponses,
|
||||
"model_mapping": map[string]any{"my-model": "kimi-k3"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// poolZhipuAdaptiveAccount 无原生 Responses 端点的 adaptive 国产账号(GLM 平台):
|
||||
// Responses 入站不委派(走既有 generic 转换链)。
|
||||
func poolZhipuAdaptiveAccount(id int64, groupID int64, priority int) *service.Account {
|
||||
return &service.Account{
|
||||
ID: id, Name: fmt.Sprintf("zhipu-adaptive-%d", id), Platform: service.PlatformZhipu,
|
||||
Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true,
|
||||
Concurrency: 1, Priority: priority,
|
||||
AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "zhipu-adaptive-key",
|
||||
"api_protocol": service.APIProtocolAdaptive,
|
||||
"api_base_urls": map[string]any{"anthropic": "https://zhipu-adaptive.example"},
|
||||
"model_mapping": map[string]any{"my-model": "glm-4.7"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// anthropicMessagesSSEStreamResponse 返回一段完整的 Anthropic Messages SSE 流。
|
||||
// generic Responses/CC → Anthropic 转换链强制上游流式(clientStream 无关),假上游
|
||||
// 必须以 SSE 回包,缓冲转换链聚合成入站协议格式写回。
|
||||
func anthropicMessagesSSEStreamResponse() *http.Response {
|
||||
sse := strings.Join([]string{
|
||||
`event: message_start`,
|
||||
`data: {"type":"message_start","message":{"id":"msg_pool_sse","type":"message","role":"assistant","model":"claude-sonnet-4-5","content":[],"usage":{"input_tokens":12,"output_tokens":1}}}`,
|
||||
``,
|
||||
`event: content_block_delta`,
|
||||
`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi from anthropic"}}`,
|
||||
``,
|
||||
`event: message_delta`,
|
||||
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}`,
|
||||
``,
|
||||
`event: message_stop`,
|
||||
`data: {"type":"message_stop"}`,
|
||||
``,
|
||||
}, "\n")
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}, "X-Request-Id": []string{"req-native-pool-sse"}},
|
||||
Body: io.NopCloser(strings.NewReader(sse)),
|
||||
}
|
||||
}
|
||||
|
||||
// 池选中纯 OpenAI 族账号(国产 CC 固定):Responses 入站委派 OpenAI 网关
|
||||
// Responses 链(链内降级 Responses→CC 直转原生 CC 端点),响应以 Responses 格式
|
||||
// 写回,usage 适配进既有 RecordUsage 流(token 计数与模型映射链不丢)。
|
||||
func TestCompositePoolResponsesDelegatesPureOpenAIFamilyAccount(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(42101, 41011, 0)})
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return chatCompletionsOKResponse("kimi-k3", 11, 7)
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.Responses(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, "response", gjson.GetBytes(rec.Body.Bytes(), "object").String(),
|
||||
"委派链响应必须是 OpenAI Responses 格式")
|
||||
require.Equal(t, int64(11), gjson.GetBytes(rec.Body.Bytes(), "usage.input_tokens").Int())
|
||||
require.Equal(t, int64(7), gjson.GetBytes(rec.Body.Bytes(), "usage.output_tokens").Int())
|
||||
|
||||
// 假上游收到的是 Responses→CC 降级转换后的 Chat Completions 请求(链内分流生效)。
|
||||
calls := h.openAIUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.True(t, strings.HasSuffix(calls[0].Path, "/chat/completions"), "upstream path=%s", calls[0].Path)
|
||||
require.Contains(t, string(calls[0].Body), `"model":"kimi-k3"`, "账号级 model_mapping 必须生效")
|
||||
require.Contains(t, calls[0].Authorization, "kimi-key")
|
||||
require.Empty(t, h.gwUpstream.snapshot(), "纯 OpenAI 族账号不得走 generic 转换链")
|
||||
|
||||
// usage 适配记录已提交:token 计数与模型映射链进入 usage 行。
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.Equal(t, 11, logs[0].InputTokens)
|
||||
require.Equal(t, 7, logs[0].OutputTokens)
|
||||
require.EqualValues(t, 42101, logs[0].AccountID)
|
||||
require.Equal(t, "my-model", logs[0].Model, "公开请求模型作为计费/展示模型记录")
|
||||
require.NotNil(t, logs[0].UpstreamModel)
|
||||
require.Equal(t, "kimi-k3", *logs[0].UpstreamModel)
|
||||
}
|
||||
|
||||
// 池选中固定 responses 协议的国产账号(UsesNativeCNResponses):Responses 入站
|
||||
// 委派 OpenAI 链直连原生 Responses 端点(零转换)。
|
||||
func TestCompositePoolResponsesDelegatesNativeCNResponsesAccount(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiResponsesAccount(42151, 41011, 0)})
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return openAIResponsesOKResponse("my-model", 13, 8)
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.Responses(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, int64(13), gjson.GetBytes(rec.Body.Bytes(), "usage.input_tokens").Int())
|
||||
require.Equal(t, int64(8), gjson.GetBytes(rec.Body.Bytes(), "usage.output_tokens").Int())
|
||||
|
||||
calls := h.openAIUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.True(t, strings.HasSuffix(calls[0].Path, "/responses"), "upstream path=%s", calls[0].Path)
|
||||
require.False(t, strings.HasSuffix(calls[0].Path, "/chat/completions"), "原生 Responses 账号不得降级 CC")
|
||||
require.Empty(t, h.gwUpstream.snapshot())
|
||||
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.Equal(t, 13, logs[0].InputTokens)
|
||||
require.Equal(t, 8, logs[0].OutputTokens)
|
||||
require.EqualValues(t, 42151, logs[0].AccountID)
|
||||
}
|
||||
|
||||
// 池选中 anthropic 原生账号:走既有 generic Responses→Anthropic 转换链(假上游
|
||||
// 收到 {base}/v1/messages),不委派 OpenAI 链。
|
||||
func TestCompositePoolResponsesAnthropicAccountUsesGenericConversion(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolAnthropicAccount(42201, 41011, 0)})
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return anthropicMessagesSSEStreamResponse()
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.Responses(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, int64(12), gjson.GetBytes(rec.Body.Bytes(), "usage.input_tokens").Int())
|
||||
require.Equal(t, int64(5), gjson.GetBytes(rec.Body.Bytes(), "usage.output_tokens").Int())
|
||||
|
||||
calls := h.gwUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.True(t, strings.HasSuffix(calls[0].Path, "/v1/messages"), "upstream path=%s", calls[0].Path)
|
||||
require.Equal(t, "anthropic-key", calls[0].APIKeyHeader)
|
||||
require.Empty(t, h.openAIUpstream.snapshot(), "anthropic 账号不得委派 OpenAI 链")
|
||||
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.Equal(t, 12, logs[0].InputTokens)
|
||||
require.Equal(t, 5, logs[0].OutputTokens)
|
||||
}
|
||||
|
||||
// Responses 委派链返回 failover 错误:走既有 failover 语义换号重选,改用
|
||||
// anthropic 原生账号的 generic 转换链完成请求。
|
||||
func TestCompositePoolResponsesDelegationFailoverSwitchesAccount(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{
|
||||
poolKimiAccount(42301, 41011, 0),
|
||||
poolAnthropicAccount(42302, 41011, 5),
|
||||
})
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return anthropicMessagesSSEStreamResponse()
|
||||
}
|
||||
// kimi 假上游默认回 500(respond 为 nil 时的兜底响应即 500)。
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.Responses(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, int64(12), gjson.GetBytes(rec.Body.Bytes(), "usage.input_tokens").Int(),
|
||||
"failover 后应由 anthropic 账号的 generic 转换链完成请求")
|
||||
|
||||
// 第一次委派失败(CC 上游 500),第二次走 generic 转换链。
|
||||
require.Len(t, h.openAIUpstream.snapshot(), 1)
|
||||
require.Len(t, h.gwUpstream.snapshot(), 1)
|
||||
require.True(t, strings.HasSuffix(h.gwUpstream.snapshot()[0].Path, "/v1/messages"))
|
||||
|
||||
selected, ok := c.Get(opsAccountIDKey)
|
||||
require.True(t, ok)
|
||||
require.EqualValues(t, 42302, selected, "ops 记录最终选中的 anthropic 账号")
|
||||
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.EqualValues(t, 42302, logs[0].AccountID)
|
||||
}
|
||||
|
||||
// 池选中纯 OpenAI 族账号(国产 CC 固定):CC 入站委派 OpenAI 网关 CC 链,同族
|
||||
// 零转换直转原生 CC 端点,响应与 usage 走既有链路。
|
||||
func TestCompositePoolChatCompletionsDelegatesPureOpenAIFamilyAccount(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(42401, 41011, 0)})
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return chatCompletionsOKResponse("kimi-k3", 11, 7)
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/chat/completions", poolChatCompletionsBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.ChatCompletions(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, "hi from kimi-k3", gjson.GetBytes(rec.Body.Bytes(), "choices.0.message.content").String(),
|
||||
"同族 CC 入站零转换,响应为 Chat Completions 格式")
|
||||
require.Equal(t, int64(11), gjson.GetBytes(rec.Body.Bytes(), "usage.prompt_tokens").Int())
|
||||
|
||||
calls := h.openAIUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.True(t, strings.HasSuffix(calls[0].Path, "/chat/completions"), "upstream path=%s", calls[0].Path)
|
||||
require.Contains(t, string(calls[0].Body), `"model":"kimi-k3"`, "账号级 model_mapping 必须生效")
|
||||
require.Contains(t, calls[0].Authorization, "kimi-key")
|
||||
require.Empty(t, h.gwUpstream.snapshot(), "纯 OpenAI 族账号不得走 generic 转换链")
|
||||
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.Equal(t, 11, logs[0].InputTokens)
|
||||
require.Equal(t, 7, logs[0].OutputTokens)
|
||||
require.EqualValues(t, 42401, logs[0].AccountID)
|
||||
require.Equal(t, "my-model", logs[0].Model)
|
||||
require.NotNil(t, logs[0].UpstreamModel)
|
||||
require.Equal(t, "kimi-k3", *logs[0].UpstreamModel)
|
||||
}
|
||||
|
||||
// 池选中 adaptive 多协议账号:CC 入站由 OpenAI CC 链直转供应商原生 CC 端点
|
||||
// (入站同族优先,零转换;与其在纯 OpenAI 族池中的行为一致),不走 CC→Anthropic
|
||||
// 既有转换链。
|
||||
func TestCompositePoolChatCompletionsAdaptiveAccountDelegatesNativeCC(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolAdaptiveKimiAccount(42451, 41011, 0)})
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return chatCompletionsOKResponse("claude-sonnet-4-5", 9, 4)
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/chat/completions", poolChatCompletionsBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.ChatCompletions(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, int64(9), gjson.GetBytes(rec.Body.Bytes(), "usage.prompt_tokens").Int())
|
||||
|
||||
calls := h.openAIUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.True(t, strings.HasSuffix(calls[0].Path, "/chat/completions"), "upstream path=%s", calls[0].Path)
|
||||
require.Empty(t, h.gwUpstream.snapshot(), "adaptive 账号 CC 入站走原生 CC,不经 generic 转换链")
|
||||
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.Equal(t, 9, logs[0].InputTokens)
|
||||
require.Equal(t, 4, logs[0].OutputTokens)
|
||||
require.EqualValues(t, 42451, logs[0].AccountID)
|
||||
}
|
||||
|
||||
// 池选中 anthropic 原生账号:CC 入站走既有 generic CC→Anthropic 转换链(假上游
|
||||
// 收到 {base}/v1/messages),不委派 OpenAI 链。
|
||||
func TestCompositePoolChatCompletionsAnthropicAccountUsesGenericConversion(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolAnthropicAccount(42501, 41011, 0)})
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return anthropicMessagesSSEStreamResponse()
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/chat/completions", poolChatCompletionsBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.ChatCompletions(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
require.Equal(t, int64(12), gjson.GetBytes(rec.Body.Bytes(), "usage.prompt_tokens").Int())
|
||||
|
||||
calls := h.gwUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.True(t, strings.HasSuffix(calls[0].Path, "/v1/messages"), "upstream path=%s", calls[0].Path)
|
||||
require.Empty(t, h.openAIUpstream.snapshot(), "anthropic 账号不得委派 OpenAI 链")
|
||||
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.Equal(t, 12, logs[0].InputTokens)
|
||||
require.Equal(t, 5, logs[0].OutputTokens)
|
||||
}
|
||||
|
||||
// CC 委派链返回 failover 错误:走既有 failover 语义换号重选,改用 anthropic
|
||||
// 原生账号的 generic 转换链完成请求。
|
||||
func TestCompositePoolChatCompletionsDelegationFailoverSwitchesAccount(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{
|
||||
poolKimiAccount(42601, 41011, 0),
|
||||
poolAnthropicAccount(42602, 41011, 5),
|
||||
})
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return anthropicMessagesSSEStreamResponse()
|
||||
}
|
||||
// kimi 假上游默认回 500(respond 为 nil 时的兜底响应即 500)。
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/chat/completions", poolChatCompletionsBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.ChatCompletions(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, int64(12), gjson.GetBytes(rec.Body.Bytes(), "usage.prompt_tokens").Int(),
|
||||
"failover 后应由 anthropic 账号的 generic 转换链完成请求")
|
||||
|
||||
require.Len(t, h.openAIUpstream.snapshot(), 1)
|
||||
require.Len(t, h.gwUpstream.snapshot(), 1)
|
||||
require.True(t, strings.HasSuffix(h.gwUpstream.snapshot()[0].Path, "/v1/messages"))
|
||||
|
||||
selected, ok := c.Get(opsAccountIDKey)
|
||||
require.True(t, ok)
|
||||
require.EqualValues(t, 42602, selected, "ops 记录最终选中的 anthropic 账号")
|
||||
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.EqualValues(t, 42602, logs[0].AccountID)
|
||||
}
|
||||
|
||||
// B2 端点委派分发谓词与结果适配器(图片计费字段)的纯函数契约。
|
||||
func TestCompositePoolTextEndpointDelegationPredicates(t *testing.T) {
|
||||
// Responses 入站:纯 OpenAI 族与原生 Responses 账号 → 委派。
|
||||
require.True(t, compositePoolAccountDelegatesResponsesToOpenAI(poolKimiAccount(1, 1, 0)))
|
||||
require.True(t, compositePoolAccountDelegatesResponsesToOpenAI(&service.Account{Platform: service.PlatformOpenAI}))
|
||||
require.True(t, compositePoolAccountDelegatesResponsesToOpenAI(&service.Account{Platform: service.PlatformGrok}))
|
||||
require.True(t, compositePoolAccountDelegatesResponsesToOpenAI(poolKimiResponsesAccount(2, 1, 0)))
|
||||
// 有原生 Responses 端点的 adaptive 账号同样委派(入站同族零转换)。
|
||||
require.True(t, compositePoolAccountDelegatesResponsesToOpenAI(poolAdaptiveKimiAccount(3, 1, 0)))
|
||||
|
||||
// anthropic 原生 / gemini / antigravity / 无原生 Responses 的 adaptive → 既有转换。
|
||||
require.False(t, compositePoolAccountDelegatesResponsesToOpenAI(poolAnthropicAccount(4, 1, 0)))
|
||||
require.False(t, compositePoolAccountDelegatesResponsesToOpenAI(&service.Account{Platform: service.PlatformGemini}))
|
||||
require.False(t, compositePoolAccountDelegatesResponsesToOpenAI(&service.Account{Platform: service.PlatformAntigravity}))
|
||||
require.False(t, compositePoolAccountDelegatesResponsesToOpenAI(poolZhipuAdaptiveAccount(5, 1, 0)))
|
||||
require.False(t, compositePoolAccountDelegatesResponsesToOpenAI(nil))
|
||||
|
||||
// CC 入站:OpenAI 兼容族(含 adaptive,链内直转原生 CC)→ 委派。
|
||||
require.True(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(poolKimiAccount(6, 1, 0)))
|
||||
require.True(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(poolAdaptiveKimiAccount(7, 1, 0)))
|
||||
require.True(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(poolZhipuAdaptiveAccount(8, 1, 0)))
|
||||
require.True(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(&service.Account{Platform: service.PlatformGrok}))
|
||||
|
||||
// anthropic-协议 / gemini / antigravity → 既有转换。
|
||||
require.False(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(poolAnthropicAccount(9, 1, 0)))
|
||||
require.False(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(&service.Account{Platform: service.PlatformGemini}))
|
||||
require.False(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(&service.Account{Platform: service.PlatformAntigravity}))
|
||||
require.False(t, compositePoolAccountDelegatesChatCompletionsToOpenAI(nil))
|
||||
|
||||
// 结果适配:图片/搜索计费字段逐字段映射,nil 安全。
|
||||
require.Nil(t, adaptOpenAIForwardResultToForwardResult(nil))
|
||||
adapted := adaptOpenAIForwardResultToForwardResult(&service.OpenAIForwardResult{
|
||||
ImageCount: 2,
|
||||
ImageSize: "2K",
|
||||
ImageInputSize: "1K",
|
||||
ImageOutputSize: "2K",
|
||||
ImageOutputSizes: []string{"2K", "2K"},
|
||||
ImageSizeSource: "response",
|
||||
ImageSizeBreakdown: map[string]int{"2K": 2},
|
||||
SearchCount: 3,
|
||||
})
|
||||
require.Equal(t, 2, adapted.ImageCount)
|
||||
require.Equal(t, "2K", adapted.ImageSize)
|
||||
require.Equal(t, "1K", adapted.ImageInputSize)
|
||||
require.Equal(t, "2K", adapted.ImageOutputSize)
|
||||
require.Equal(t, []string{"2K", "2K"}, adapted.ImageOutputSizes)
|
||||
require.Equal(t, "response", adapted.ImageSizeSource)
|
||||
require.Equal(t, map[string]int{"2K": 2}, adapted.ImageSizeBreakdown)
|
||||
require.Equal(t, 3, adapted.SearchCount)
|
||||
}
|
||||
|
||||
// openAIResponsesOKResponse 返回一份带 usage 的非流式 Responses 成功响应。
|
||||
func openAIResponsesOKResponse(model string, inputTokens, outputTokens int) *http.Response {
|
||||
body := fmt.Sprintf(
|
||||
`{"id":"resp_pool","object":"response","created_at":1,"status":"completed","model":%q,"output":[],"usage":{"input_tokens":%d,"output_tokens":%d}}`,
|
||||
model, inputTokens, outputTokens)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"req-resp-pool"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}
|
||||
}
|
||||
@@ -217,3 +217,96 @@ func respondCompositePoolAttemptPolicyFailure(c *gin.Context, failure compositeP
|
||||
}
|
||||
write(c, http.StatusServiceUnavailable, "api_error", "Service temporarily unavailable")
|
||||
}
|
||||
|
||||
// compositePoolAccountDelegatesToOpenAI 报告池请求选中的账号是否需要委派 OpenAI
|
||||
// 网关的 /v1/messages 兼容链转发。generic(Anthropic 原生)转发路径覆盖:
|
||||
// anthropic 原生、gemini / antigravity 既有调度平台,以及能解析出 Anthropic 协议
|
||||
// 上游 base 的 anthropic-协议 / adaptive 多协议账号(service 层已按账号协议化
|
||||
// 上游 base);其余纯 OpenAI 族账号(openai/grok/国产供应商/OpenCode Go,无
|
||||
// Anthropic 协议能力)由委派链完成协议转换。仅池激活时调用。
|
||||
func compositePoolAccountDelegatesToOpenAI(account *service.Account) bool {
|
||||
if account == nil {
|
||||
return false
|
||||
}
|
||||
switch account.Platform {
|
||||
case service.PlatformAnthropic, service.PlatformGemini, service.PlatformAntigravity:
|
||||
return false
|
||||
}
|
||||
if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() {
|
||||
// 多协议账号走既有 generic Forward(servable 门已保证 Anthropic 协议
|
||||
// base 非空);不应停留在 Chat Completions 协议上被误委派。
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// compositePoolAccountDelegatesResponsesToOpenAI 报告池请求选中的账号在入站
|
||||
// /v1/responses 时是否委派 OpenAI 网关 Responses 链(OpenAIGatewayService.Forward)
|
||||
// 转发。入站同族优先(零或近零转换):纯 OpenAI 族账号(openai/grok/国产 CC 固定/
|
||||
// OpenCode Go)与具备原生 Responses 端点的国产账号(UsesNativeCNResponses,含
|
||||
// fixed responses 与 adaptive)交该链按账号协议直连或轻量转换;anthropic 原生 /
|
||||
// gemini / antigravity / anthropic-协议 / 无原生 Responses 的 adaptive 账号走
|
||||
// 既有 generic Responses→Anthropic 转换。仅池激活时调用。
|
||||
func compositePoolAccountDelegatesResponsesToOpenAI(account *service.Account) bool {
|
||||
if account == nil {
|
||||
return false
|
||||
}
|
||||
return compositePoolAccountDelegatesToOpenAI(account) || account.UsesNativeCNResponses()
|
||||
}
|
||||
|
||||
// compositePoolAccountDelegatesChatCompletionsToOpenAI 报告池请求选中的账号在入站
|
||||
// /v1/chat/completions 时是否委派 OpenAI 网关 CC 链(OpenAIGatewayService.
|
||||
// ForwardAsChatCompletions)转发。入站同族优先(零转换):OpenAI 兼容族账号交该链,
|
||||
// 其中 adaptive 国产账号由该链直转供应商原生 CC 端点(forwardAsChatCompletions 的
|
||||
// adaptive 分支,与其在纯 OpenAI 族池中的行为一致);anthropic-协议 / gemini /
|
||||
// antigravity 走既有 generic CC→Anthropic 转换。仅池激活时调用。
|
||||
func compositePoolAccountDelegatesChatCompletionsToOpenAI(account *service.Account) bool {
|
||||
if account == nil {
|
||||
return false
|
||||
}
|
||||
return account.IsOpenAICompatible() && !account.IsAnthropicProtocol()
|
||||
}
|
||||
|
||||
// adaptOpenAIForwardResultToForwardResult 把委派链(OpenAIGatewayService 转发方法)
|
||||
// 的转发结果适配进 generic 计费链的 ForwardResult:usage token 计数、模型、请求
|
||||
// 元数据与图片/搜索计费字段逐字段映射,经既有 usage 提交流入账,计费不丢。
|
||||
// nil 安全;错误路径携带的部分结果(流中断排水 usage)同样适配。
|
||||
func adaptOpenAIForwardResultToForwardResult(src *service.OpenAIForwardResult) *service.ForwardResult {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
return &service.ForwardResult{
|
||||
RequestID: src.RequestID,
|
||||
UpstreamHeaders: src.UpstreamHeaders,
|
||||
Usage: service.ClaudeUsage{
|
||||
InputTokens: src.Usage.InputTokens,
|
||||
OutputTokens: src.Usage.OutputTokens,
|
||||
CacheCreationInputTokens: src.Usage.CacheCreationInputTokens,
|
||||
CacheReadInputTokens: src.Usage.CacheReadInputTokens,
|
||||
ImageOutputTokens: src.Usage.ImageOutputTokens,
|
||||
},
|
||||
Model: src.Model,
|
||||
UpstreamModel: src.UpstreamModel,
|
||||
UpstreamResponseModel: src.UpstreamResponseModel,
|
||||
UpstreamResponseModelConflict: src.UpstreamResponseModelConflict,
|
||||
UpstreamResponseServiceTier: src.UpstreamResponseServiceTier,
|
||||
Stream: src.Stream,
|
||||
Duration: src.Duration,
|
||||
FirstTokenMs: src.FirstTokenMs,
|
||||
ClientDisconnect: src.ClientDisconnect,
|
||||
ReasoningEffort: src.ReasoningEffort,
|
||||
RequestedReasoningEffort: src.RequestedReasoningEffort,
|
||||
ServiceTier: src.ServiceTier,
|
||||
SearchCount: src.SearchCount,
|
||||
AudioUsage: src.AudioUsage,
|
||||
// 生图计费字段:/v1/responses 是 token+图片混合计费端点,委派链产出的
|
||||
// 图片尺寸/数量必须随 usage 进入 generic 计费链(B2 扩展)。
|
||||
ImageCount: src.ImageCount,
|
||||
ImageSize: src.ImageSize,
|
||||
ImageInputSize: src.ImageInputSize,
|
||||
ImageOutputSize: src.ImageOutputSize,
|
||||
ImageOutputSizes: src.ImageOutputSizes,
|
||||
ImageSizeSource: src.ImageSizeSource,
|
||||
ImageSizeBreakdown: src.ImageSizeBreakdown,
|
||||
}
|
||||
}
|
||||
@@ -637,6 +637,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
}
|
||||
fallbackUsed := false
|
||||
|
||||
// composite 账号池请求状态(B1:generic Messages 循环池化)。池激活判定与
|
||||
// generic 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求
|
||||
// poolDenials 恒为空、attempt 策略不生效,整条路径零变化。
|
||||
isPoolRequest := service.GenericCompositePoolActive(c.Request.Context())
|
||||
poolDenials := newCompositePoolPlatformDenials()
|
||||
|
||||
// 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。
|
||||
// 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。
|
||||
if h.gatewayService.IsSingleAntigravityAccountGroup(c.Request.Context(), currentAPIKey.GroupID) {
|
||||
@@ -679,7 +685,16 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
zap.Bool("has_bound_session", hasBoundSession),
|
||||
zap.Int("failed_account_count", len(fs.FailedAccountIDs)),
|
||||
)
|
||||
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), currentAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID)
|
||||
// 池请求把业务限制 deny 过的平台按 deniedPlatforms 整平台 mask 后重选
|
||||
//(候选池 immutable,mask 只叠加在当前请求 ctx 之上);无 deny 时
|
||||
// 返回原 ctx,非池请求不经此分支,选号 ctx 与原行为一致。
|
||||
selectCtx := c.Request.Context()
|
||||
if isPoolRequest {
|
||||
if maskedCtx, ok := compositePoolSelectionRetryContext(selectCtx, poolDenials); ok {
|
||||
selectCtx = maskedCtx
|
||||
}
|
||||
}
|
||||
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, currentAPIKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, parsedReq.MetadataUserID, subject.UserID)
|
||||
if err != nil {
|
||||
if failoverClientGone(c) {
|
||||
reqLog.Info("gateway.account_select_aborted_client_disconnected", zap.Error(err))
|
||||
@@ -736,6 +751,36 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
zap.Bool("sticky_honored", sessionBoundAccountID > 0 && sessionBoundAccountID == account.ID),
|
||||
)
|
||||
|
||||
// composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform
|
||||
// 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved
|
||||
// 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数,
|
||||
// 放在槽位获取前:deny 不占并发槽。generic 循环无 previous_response_id,
|
||||
// 无 pinned 分支;deny 记入 poolDenials 后按 masked 候选池整平台重选,
|
||||
// 候选全部被业务限制时按原语义终止,不误报 model unsupported。
|
||||
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping}
|
||||
isPoolAttempt := false
|
||||
if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
attemptPolicy = evaluateCompositePoolAttemptPolicy(
|
||||
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false)
|
||||
isPoolAttempt = true
|
||||
if attemptPolicy.Failure.denied() {
|
||||
releaseCompositePoolSelection(selection)
|
||||
// 选号链可能已为该账号注册会话槽:排除前释放,镜像 profit-veto 分支。
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey)
|
||||
poolDenials.deny(account.Platform)
|
||||
fs.FailedAccountIDs[account.ID] = struct{}{}
|
||||
// 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。
|
||||
if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok {
|
||||
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
|
||||
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
|
||||
}
|
||||
respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// 检查请求拦截(预热请求、SUGGESTION MODE等)
|
||||
if account.IsInterceptWarmupEnabled() {
|
||||
interceptType := detectInterceptType(body, reqModel, parsedReq.MaxTokens, isClaudeCodeClient)
|
||||
@@ -890,9 +935,15 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
// ===== 用户消息串行队列 END =====
|
||||
|
||||
// 渠道模型映射只作用于本次账号尝试,避免 failover 后污染原始 ParsedRequest。
|
||||
if channelMapping.Mapped {
|
||||
attemptParsedReq.Model = channelMapping.MappedModel
|
||||
if err := attemptParsedReq.ReplaceBody(h.gatewayService.ReplaceModelInBody(attemptParsedReq.Body.Bytes(), channelMapping.MappedModel)); err != nil {
|
||||
// 池请求按选中平台的渠道映射(attempt 策略产出,platform-scoped)派生,
|
||||
// 不用 composite 作用域的请求级映射(无 resolved 平台时跨平台行匹配不可靠)。
|
||||
attemptChannelMapping := channelMapping
|
||||
if isPoolAttempt {
|
||||
attemptChannelMapping = attemptPolicy.Mapping
|
||||
}
|
||||
if attemptChannelMapping.Mapped {
|
||||
attemptParsedReq.Model = attemptChannelMapping.MappedModel
|
||||
if err := attemptParsedReq.ReplaceBody(h.gatewayService.ReplaceModelInBody(attemptParsedReq.Body.Bytes(), attemptChannelMapping.MappedModel)); err != nil {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body")
|
||||
return
|
||||
}
|
||||
@@ -914,10 +965,26 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
if fs.ForceCacheBilling {
|
||||
requestCtx = service.WithForceCacheBilling(requestCtx)
|
||||
}
|
||||
// 池请求的 attempt 局部 ctx 携带选中平台(不写回 c.Request):forward 内的
|
||||
// 渠道定价作用域与计费 QuotaPlatform 跟随实际平台,对齐 OpenAI 池 attempt 语义。
|
||||
if isPoolRequest {
|
||||
requestCtx = compositePoolAttemptContext(requestCtx, account)
|
||||
}
|
||||
// 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover
|
||||
writerSizeBeforeForward := c.Writer.Size()
|
||||
if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey {
|
||||
result, err = h.antigravityGatewayService.Forward(requestCtx, c, account, attemptBody, hasBoundSession)
|
||||
} else if isPoolRequest && compositePoolAccountDelegatesToOpenAI(account) {
|
||||
// 纯 OpenAI 族账号(无 Anthropic 协议能力)在池激活时委派 OpenAI 网关的
|
||||
// /v1/messages 兼容链:Anthropic → Responses/CC 协议转换、响应写回与
|
||||
// failover 错误信封都由该链完成,错误信封已是 Anthropic 风格,不再二次包装。
|
||||
// promptCacheKey 传 ""(内部按 cache_control / metadata 会话种子兜底);
|
||||
// defaultMappedModel 与 OpenAI handler Messages 路径同源。
|
||||
openAIResult, delegateErr := h.openAIGatewayService.ForwardAsAnthropic(
|
||||
requestCtx, c, account, attemptBody, "",
|
||||
strings.TrimSpace(resolveOpenAIMessagesDispatchMappedModel(c, apiKey, reqModel)))
|
||||
result = adaptOpenAIForwardResultToForwardResult(openAIResult)
|
||||
err = delegateErr
|
||||
} else {
|
||||
result, err = h.gatewayService.Forward(requestCtx, c, account, attemptParsedReq)
|
||||
}
|
||||
@@ -960,7 +1027,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
// 使用量记录通过有界 worker 池提交,避免请求热路径创建无界 goroutine。
|
||||
// ForceCacheBilling 提前拍成标量,避免 worker 闭包保活 failover 状态里的响应体。
|
||||
forceCacheBilling := fs.ForceCacheBilling
|
||||
// 池请求按选中平台计量 user×platform 配额(attempt ctx 携带 resolved
|
||||
// 平台);非池保持准入语义不变。
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey)
|
||||
if isPoolAttempt {
|
||||
quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, currentAPIKey)
|
||||
}
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
|
||||
@@ -979,7 +1051,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
RequestPayloadHash: requestPayloadHash,
|
||||
ForceCacheBilling: forceCacheBilling,
|
||||
APIKeyService: h.apiKeyService,
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel),
|
||||
}); err != nil {
|
||||
logger.L().With(
|
||||
zap.String("component", "handler.gateway.messages"),
|
||||
@@ -2220,16 +2292,36 @@ func (h *GatewayHandler) CountTokens(c *gin.Context) {
|
||||
}
|
||||
sessionHash := h.gatewayService.GenerateSessionHash(parsedReq)
|
||||
|
||||
// 选择支持该模型的账号
|
||||
account, err := h.gatewayService.SelectAccountForModel(c.Request.Context(), apiKey.GroupID, sessionHash, parsedReq.Model)
|
||||
if err != nil {
|
||||
reqLog.Warn("gateway.count_tokens_select_account_failed", zap.Error(err))
|
||||
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, parsedReq.Model, parsedReq.Model, service.PlatformAnthropic)
|
||||
if !cls.ModelNotFound {
|
||||
markOpsRoutingCapacityLimitedIfNoAvailable(c, err)
|
||||
// 选择支持该模型的账号。池请求(B1:generic CountTokens 最小池化)选中纯
|
||||
// OpenAI 族账号时该账号不可计数:跳过(记入排除集重选)而不是对
|
||||
// /v1/messages/count_tokens 报 500;可计数账号与单目标请求按既有语义直接转发。
|
||||
isPoolRequest := service.GenericCompositePoolActive(c.Request.Context())
|
||||
var excludedAccountIDs map[int64]struct{}
|
||||
var account *service.Account
|
||||
for {
|
||||
account, err = h.gatewayService.SelectAccountForModelWithExclusions(c.Request.Context(), apiKey.GroupID, sessionHash, parsedReq.Model, excludedAccountIDs)
|
||||
if err != nil {
|
||||
reqLog.Warn("gateway.count_tokens_select_account_failed", zap.Error(err))
|
||||
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, parsedReq.Model, parsedReq.Model, service.PlatformAnthropic)
|
||||
if !cls.ModelNotFound {
|
||||
markOpsRoutingCapacityLimitedIfNoAvailable(c, err)
|
||||
}
|
||||
h.errorResponse(c, cls.Status, cls.ErrType, cls.Message)
|
||||
return
|
||||
}
|
||||
h.errorResponse(c, cls.Status, cls.ErrType, cls.Message)
|
||||
return
|
||||
if !isPoolRequest || service.GenericCompositePoolCountableAccount(account) {
|
||||
break
|
||||
}
|
||||
reqLog.Info("gateway.count_tokens_pool_skip_uncountable_account",
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.String("account_platform", account.Platform),
|
||||
)
|
||||
// 选号链可能已为该账号注册会话槽:排除前释放,再用排除集重选。
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash)
|
||||
if excludedAccountIDs == nil {
|
||||
excludedAccountIDs = make(map[int64]struct{})
|
||||
}
|
||||
excludedAccountIDs[account.ID] = struct{}{}
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
|
||||
@@ -180,6 +180,17 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
if groupPlatform == service.PlatformGemini && selectionSessionHash != "" {
|
||||
selectionSessionHash = "gemini:" + selectionSessionHash
|
||||
}
|
||||
// composite 账号池请求状态(B2:generic CC 循环池化)。池激活判定与 generic
|
||||
// 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求 poolDenials
|
||||
// 恒为空、attempt 策略与委派分支不生效,整条路径零变化。
|
||||
isPoolRequest := service.GenericCompositePoolActive(c.Request.Context())
|
||||
poolDenials := newCompositePoolPlatformDenials()
|
||||
// 委派 CC 链的 promptCacheKey 语义对齐 OpenAI handler CC 路径(headers →
|
||||
// prompt_cache_key 提取,仅池激活时计算,非池请求不新增解析)。
|
||||
var poolPromptCacheKey string
|
||||
if isPoolRequest {
|
||||
poolPromptCacheKey = h.openAIGatewayService.ExtractSessionID(c, body)
|
||||
}
|
||||
// 3. Account selection + failover loop
|
||||
fs := NewFailoverState(h.maxAccountSwitches, false)
|
||||
if groupPlatform == service.PlatformGemini {
|
||||
@@ -190,7 +201,16 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
if failoverClientGone(c) {
|
||||
return
|
||||
}
|
||||
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
|
||||
// 池请求把业务限制 deny 过的平台按 deniedPlatforms 整平台 mask 后重选
|
||||
//(候选池 immutable,mask 只叠加在当前请求 ctx 之上);无 deny 时
|
||||
// 返回原 ctx,非池请求不经此分支,选号 ctx 与原行为一致。
|
||||
selectCtx := c.Request.Context()
|
||||
if isPoolRequest {
|
||||
if maskedCtx, ok := compositePoolSelectionRetryContext(selectCtx, poolDenials); ok {
|
||||
selectCtx = maskedCtx
|
||||
}
|
||||
}
|
||||
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, apiKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
|
||||
if err != nil {
|
||||
if failoverClientGone(c) {
|
||||
reqLog.Info("gateway.cc.account_select_aborted_client_disconnected", zap.Error(err))
|
||||
@@ -228,6 +248,41 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
account := selection.Account
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform
|
||||
// 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved
|
||||
// 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数,
|
||||
// 放在槽位获取前:deny 不占并发槽。CC 循环无 previous_response_id 状态,
|
||||
// 无 pinned 分支;deny 记入 poolDenials 后按 masked 候选池整平台重选,
|
||||
// 候选全部被业务限制时按原语义终止,不误报 model unsupported。
|
||||
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping}
|
||||
isPoolAttempt := false
|
||||
if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
attemptPolicy = evaluateCompositePoolAttemptPolicy(
|
||||
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false)
|
||||
isPoolAttempt = true
|
||||
if attemptPolicy.Failure.denied() {
|
||||
releaseCompositePoolSelection(selection)
|
||||
// 选号链可能已为该账号注册会话槽(键与选号一致):排除前释放
|
||||
//(镜像 Messages 池分支)。
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, selectionSessionHash)
|
||||
poolDenials.deny(account.Platform)
|
||||
fs.FailedAccountIDs[account.ID] = struct{}{}
|
||||
// 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。
|
||||
if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok {
|
||||
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
|
||||
if streamStarted {
|
||||
h.handleStreamingAwareError(cc, status, code, message, true)
|
||||
return
|
||||
}
|
||||
h.chatCompletionsErrorResponse(cc, status, code, message)
|
||||
}
|
||||
respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Acquire account concurrency slot
|
||||
accountReleaseFunc := selection.ReleaseFunc
|
||||
if !selection.Acquired {
|
||||
@@ -284,12 +339,24 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
|
||||
// 5. Forward request
|
||||
writerSizeBeforeForward := c.Writer.Size()
|
||||
// 渠道模型映射只作用于本次账号尝试:池请求按选中平台的渠道映射(attempt
|
||||
// 策略产出,platform-scoped)派生,非池保持请求级映射语义不变。
|
||||
attemptChannelMapping := channelMapping
|
||||
if isPoolAttempt {
|
||||
attemptChannelMapping = attemptPolicy.Mapping
|
||||
}
|
||||
forwardBody := body
|
||||
if channelMapping.Mapped {
|
||||
forwardBody = h.gatewayService.ReplaceModelInBody(body, channelMapping.MappedModel)
|
||||
if attemptChannelMapping.Mapped {
|
||||
forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel)
|
||||
}
|
||||
var result *service.ForwardResult
|
||||
setActualUpstreamEndpoint(c, "")
|
||||
// 池请求的 attempt 局部 ctx 携带选中平台(不写回 c.Request):forward 内的
|
||||
// 渠道定价作用域与计费 QuotaPlatform 跟随实际平台,对齐 Messages 池 attempt 语义。
|
||||
attemptCtx := c.Request.Context()
|
||||
if isPoolRequest {
|
||||
attemptCtx = compositePoolAttemptContext(attemptCtx, account)
|
||||
}
|
||||
if account.Platform == service.PlatformGemini {
|
||||
if h.geminiCompatService == nil {
|
||||
h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "upstream_error", "Gemini compatibility service is not configured")
|
||||
@@ -298,7 +365,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
}
|
||||
return
|
||||
}
|
||||
result, err = h.geminiCompatService.ForwardAsChatCompletions(c.Request.Context(), c, account, forwardBody)
|
||||
result, err = h.geminiCompatService.ForwardAsChatCompletions(attemptCtx, c, account, forwardBody)
|
||||
} else if shouldUseAntigravityCompat(account) {
|
||||
if h.antigravityGatewayService == nil {
|
||||
h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "upstream_error", "Antigravity compatibility service is not configured")
|
||||
@@ -308,9 +375,18 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
setActualUpstreamEndpoint(c, EndpointAntigravityGenerateContent)
|
||||
result, err = h.antigravityGatewayService.ForwardAsChatCompletions(c.Request.Context(), c, account, forwardBody, parsedReq)
|
||||
result, err = h.antigravityGatewayService.ForwardAsChatCompletions(attemptCtx, c, account, forwardBody, parsedReq)
|
||||
} else if isPoolRequest && compositePoolAccountDelegatesChatCompletionsToOpenAI(account) {
|
||||
// OpenAI 兼容族账号在池激活时委派 OpenAI 网关 CC 链:入站同族优先
|
||||
//(零转换,adaptive 账号由该链直转供应商原生 CC 端点),响应写回与
|
||||
// failover 错误信封都由该链完成,错误信封已是 OpenAI CC 风格,不再二次
|
||||
// 包装。defaultMappedModel 传 "",与 OpenAI handler CC 路径一致。
|
||||
openAIResult, delegateErr := h.openAIGatewayService.ForwardAsChatCompletions(
|
||||
attemptCtx, c, account, forwardBody, poolPromptCacheKey, "")
|
||||
result = adaptOpenAIForwardResultToForwardResult(openAIResult)
|
||||
err = delegateErr
|
||||
} else {
|
||||
result, err = h.gatewayService.ForwardAsChatCompletions(c.Request.Context(), c, account, forwardBody, parsedReq)
|
||||
result, err = h.gatewayService.ForwardAsChatCompletions(attemptCtx, c, account, forwardBody, parsedReq)
|
||||
}
|
||||
|
||||
if accountReleaseFunc != nil {
|
||||
@@ -358,6 +434,11 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
|
||||
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
// 池请求按选中平台计量 user×platform 配额(attempt ctx 携带 resolved
|
||||
// 平台);非池保持准入语义不变。
|
||||
if isPoolAttempt {
|
||||
quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey)
|
||||
}
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
|
||||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||||
@@ -376,7 +457,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
RequestPayloadHash: requestPayloadHash,
|
||||
APIKeyService: h.apiKeyService,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel),
|
||||
}); err != nil {
|
||||
reqLog.Error("gateway.cc.record_usage_failed",
|
||||
zap.Int64("account_id", account.ID),
|
||||
|
||||
@@ -180,6 +180,12 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
}
|
||||
sessionHash := h.gatewayService.GenerateSessionHash(parsedReq)
|
||||
|
||||
// composite 账号池请求状态(B2:generic Responses 循环池化)。池激活判定与
|
||||
// generic 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求
|
||||
// poolDenials 恒为空、attempt 策略与委派分支不生效,整条路径零变化。
|
||||
isPoolRequest := service.GenericCompositePoolActive(requestCtx)
|
||||
poolDenials := newCompositePoolPlatformDenials()
|
||||
|
||||
// 3. Account selection + failover loop
|
||||
fs := NewFailoverState(h.maxAccountSwitches, false)
|
||||
|
||||
@@ -187,7 +193,16 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
if failoverClientGone(c) {
|
||||
return
|
||||
}
|
||||
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(requestCtx, apiKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
|
||||
// 池请求把业务限制 deny 过的平台按 deniedPlatforms 整平台 mask 后重选
|
||||
//(候选池 immutable,mask 只叠加在当前请求 ctx 之上);无 deny 时
|
||||
// 返回原 ctx,非池请求不经此分支,选号 ctx 与原行为一致。
|
||||
selectCtx := requestCtx
|
||||
if isPoolRequest {
|
||||
if maskedCtx, ok := compositePoolSelectionRetryContext(selectCtx, poolDenials); ok {
|
||||
selectCtx = maskedCtx
|
||||
}
|
||||
}
|
||||
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, apiKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
|
||||
if err != nil {
|
||||
if failoverClientGone(c) {
|
||||
reqLog.Info("gateway.responses.account_select_aborted_client_disconnected", zap.Error(err))
|
||||
@@ -225,6 +240,41 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
account := selection.Account
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform
|
||||
// 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved
|
||||
// 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数,
|
||||
// 放在槽位获取前:deny 不占并发槽。generic Responses 循环无
|
||||
// previous_response_id,无 pinned 分支;deny 记入 poolDenials 后按 masked
|
||||
// 候选池整平台重选,候选全部被业务限制时按原语义终止,不误报 model
|
||||
// unsupported。
|
||||
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: requestCtx, Mapping: channelMapping}
|
||||
isPoolAttempt := false
|
||||
if isPoolRequest && compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
attemptPolicy = evaluateCompositePoolAttemptPolicy(
|
||||
requestCtx, h.billingCacheService, h.openAIGatewayService, apiKey, subscription, account, reqModel, false)
|
||||
isPoolAttempt = true
|
||||
if attemptPolicy.Failure.denied() {
|
||||
releaseCompositePoolSelection(selection)
|
||||
// 选号链可能已为该账号注册会话槽:排除前释放(镜像 Messages 池分支)。
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash)
|
||||
poolDenials.deny(account.Platform)
|
||||
fs.FailedAccountIDs[account.ID] = struct{}{}
|
||||
// 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。
|
||||
if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); !ok {
|
||||
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
|
||||
if streamStarted {
|
||||
h.handleStreamingAwareError(cc, status, code, message, true)
|
||||
return
|
||||
}
|
||||
h.responsesErrorResponse(cc, status, code, message)
|
||||
}
|
||||
respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Acquire account concurrency slot
|
||||
accountReleaseFunc := selection.ReleaseFunc
|
||||
if !selection.Acquired {
|
||||
@@ -275,12 +325,25 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
|
||||
// 5. Forward request
|
||||
writerSizeBeforeForward := c.Writer.Size()
|
||||
// 渠道模型映射只作用于本次账号尝试:池请求按选中平台的渠道映射(attempt
|
||||
// 策略产出,platform-scoped)派生,非池保持请求级映射语义不变。
|
||||
attemptChannelMapping := channelMapping
|
||||
if isPoolAttempt {
|
||||
attemptChannelMapping = attemptPolicy.Mapping
|
||||
}
|
||||
forwardBody := body
|
||||
if channelMapping.Mapped {
|
||||
forwardBody = h.gatewayService.ReplaceModelInBody(body, channelMapping.MappedModel)
|
||||
if attemptChannelMapping.Mapped {
|
||||
forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel)
|
||||
}
|
||||
var result *service.ForwardResult
|
||||
setActualUpstreamEndpoint(c, "")
|
||||
// 池请求的 attempt 局部 ctx 携带选中平台(不写回 requestCtx,否则下一轮
|
||||
// 选号会被 resolved 平台截断池语义):forward 内的渠道定价作用域与计费
|
||||
// QuotaPlatform 跟随实际平台,对齐 Messages 池 attempt 语义。
|
||||
attemptCtx := requestCtx
|
||||
if isPoolRequest {
|
||||
attemptCtx = compositePoolAttemptContext(attemptCtx, account)
|
||||
}
|
||||
if shouldUseAntigravityCompat(account) {
|
||||
if h.antigravityGatewayService == nil {
|
||||
h.responsesErrorResponse(c, http.StatusBadGateway, "upstream_error", "Antigravity compatibility service is not configured")
|
||||
@@ -290,9 +353,18 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
setActualUpstreamEndpoint(c, EndpointAntigravityGenerateContent)
|
||||
result, err = h.antigravityGatewayService.ForwardAsResponses(requestCtx, c, account, forwardBody, parsedReq)
|
||||
result, err = h.antigravityGatewayService.ForwardAsResponses(attemptCtx, c, account, forwardBody, parsedReq)
|
||||
} else if isPoolRequest && compositePoolAccountDelegatesResponsesToOpenAI(account) {
|
||||
// 纯 OpenAI 族 / 原生 Responses 账号在池激活时委派 OpenAI 网关 Responses
|
||||
// 链:入站同族优先(零或近零转换),响应写回与 failover 错误信封都由该
|
||||
// 链完成,错误信封已是 OpenAI Responses 风格,不再二次包装。
|
||||
// promptCacheKey 由链内从 body 派生(与 OpenAI handler Responses 路径一致)。
|
||||
setOpenAIClientTransportHTTP(c)
|
||||
openAIResult, delegateErr := h.openAIGatewayService.Forward(attemptCtx, c, account, forwardBody)
|
||||
result = adaptOpenAIForwardResultToForwardResult(openAIResult)
|
||||
err = delegateErr
|
||||
} else {
|
||||
result, err = h.gatewayService.ForwardAsResponses(requestCtx, c, account, forwardBody, parsedReq)
|
||||
result, err = h.gatewayService.ForwardAsResponses(attemptCtx, c, account, forwardBody, parsedReq)
|
||||
}
|
||||
|
||||
if accountReleaseFunc != nil {
|
||||
@@ -341,6 +413,11 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
|
||||
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
// 池请求按选中平台计量 user×platform 配额(attempt ctx 携带 resolved
|
||||
// 平台);非池保持准入语义不变。
|
||||
if isPoolAttempt {
|
||||
quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey)
|
||||
}
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
|
||||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||||
@@ -359,7 +436,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
RequestPayloadHash: requestPayloadHash,
|
||||
APIKeyService: h.apiKeyService,
|
||||
SessionID: sessionID,
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel),
|
||||
}); err != nil {
|
||||
reqLog.Error("gateway.responses.record_usage_failed",
|
||||
zap.Int64("account_id", account.ID),
|
||||
|
||||
@@ -566,8 +566,8 @@ func isCompositeOpenAIFamilyPool(candidates []string) bool {
|
||||
|
||||
// isOpenAIResponsesCompatibleGatewayPlatform 报告请求是否应进入 OpenAI 兼容族
|
||||
// handler。账号池请求没有单一目标平台:池候选全部属于兼容族才进入,混入其他
|
||||
// 族时返回 false,由 dispatchOpenAICompatibleGateway 显式拒绝,不允许按池大小
|
||||
// 或猜测选族。
|
||||
// 族的池返回 false 落通用网关(generic handler 按选中账号的协议能力分发,
|
||||
// 不再显式拒绝),不允许按池大小或猜测选族。
|
||||
func isOpenAIResponsesCompatibleGatewayPlatform(c *gin.Context) bool {
|
||||
if candidates, ok := compositePoolCandidatePlatforms(c); ok {
|
||||
return isCompositeOpenAIFamilyPool(candidates)
|
||||
@@ -577,15 +577,16 @@ func isOpenAIResponsesCompatibleGatewayPlatform(c *gin.Context) bool {
|
||||
|
||||
// dispatchOpenAICompatibleGateway 把文本端点(messages/responses/chat
|
||||
// completions)路由进 OpenAI 兼容族:账号池候选全部属于兼容族 → OpenAI 网关;
|
||||
// 跨族池 → 显式 400(点名候选,不落入通用网关的错误协议);单目标沿用既有族
|
||||
// 判断落通用网关。
|
||||
// 其余(跨族池 / 全原生协议族池)落通用网关——generic handler 在池激活时按
|
||||
// 选中账号的协议能力分发转发,不信任「一定有 anthropic 能力」;单目标沿用
|
||||
// 既有族判断落通用网关。
|
||||
func dispatchOpenAICompatibleGateway(c *gin.Context, openAIHandler, genericHandler gin.HandlerFunc) {
|
||||
if candidates, ok := compositePoolCandidatePlatforms(c); ok {
|
||||
if isCompositeOpenAIFamilyPool(candidates) {
|
||||
openAIHandler(c)
|
||||
return
|
||||
}
|
||||
rejectCompositeCrossFamilyPool(c, candidates)
|
||||
genericHandler(c)
|
||||
return
|
||||
}
|
||||
if isOpenAICompatibleGatewayFamilyPlatform(getGroupPlatform(c)) {
|
||||
@@ -597,15 +598,15 @@ func dispatchOpenAICompatibleGateway(c *gin.Context, openAIHandler, genericHandl
|
||||
|
||||
// dispatchOpenAICompatibleCountTokens 沿用 count_tokens 的既有语义:openai 与
|
||||
// 国产兼容供应商走 OpenAI CountTokens,grok 走本地估算;账号池候选全部属于
|
||||
// 兼容族时进入 OpenAI CountTokens(沿用其原有端点能力/不支持语义),跨族池
|
||||
// 明确拒绝。
|
||||
// 兼容族时进入 OpenAI CountTokens(沿用其原有端点能力/不支持语义),其余池落
|
||||
// 通用 CountTokens(generic 链路对不可计数账号按排除重选处理)。
|
||||
func dispatchOpenAICompatibleCountTokens(c *gin.Context, compatibleHandler, grokHandler, genericHandler gin.HandlerFunc) {
|
||||
if candidates, ok := compositePoolCandidatePlatforms(c); ok {
|
||||
if isCompositeOpenAIFamilyPool(candidates) {
|
||||
compatibleHandler(c)
|
||||
return
|
||||
}
|
||||
rejectCompositeCrossFamilyPool(c, candidates)
|
||||
genericHandler(c)
|
||||
return
|
||||
}
|
||||
switch getGroupPlatform(c) {
|
||||
@@ -618,23 +619,6 @@ func dispatchOpenAICompatibleCountTokens(c *gin.Context, compatibleHandler, grok
|
||||
}
|
||||
}
|
||||
|
||||
// rejectCompositeCrossFamilyPool 对混入非兼容族候选(或全部为原生协议族)的
|
||||
// 账号池写显式 400 并点名候选平台:这类请求没有统一的 handler 家族,
|
||||
// 猜测单个平台或落入通用网关都会产生误导性错误。
|
||||
func rejectCompositeCrossFamilyPool(c *gin.Context, candidates []string) {
|
||||
foreign := make([]string, 0, len(candidates))
|
||||
for _, platform := range candidates {
|
||||
if !isOpenAICompatibleGatewayFamilyPlatform(platform) {
|
||||
foreign = append(foreign, platform)
|
||||
}
|
||||
}
|
||||
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf(
|
||||
"Composite account pool for this model spans multiple protocol families (candidates: %s; unsupported for OpenAI-compatible endpoints: %s)",
|
||||
strings.Join(candidates, ", "),
|
||||
strings.Join(foreign, ", "),
|
||||
))
|
||||
}
|
||||
|
||||
func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) gin.HandlerFunc {
|
||||
if resolver == nil {
|
||||
resolver = service.NewCompositeRouteResolver(nil)
|
||||
|
||||
@@ -157,9 +157,10 @@ func TestDispatchOpenAICompatibleGatewaySingleDeepSeekMatchesPoolFamily(t *testi
|
||||
require.Zero(t, generic)
|
||||
}
|
||||
|
||||
// 跨原生协议族池(兼容族混 anthropic/gemini/antigravity,或全部为原生族)
|
||||
// 必须显式 400 并点名候选平台,不得落入通用 handler。
|
||||
func TestDispatchOpenAICompatibleGatewayRejectsCrossFamilyPool(t *testing.T) {
|
||||
// 跨原生协议族池(兼容族混 anthropic/gemini/antigravity,或全部为原生族)不再
|
||||
// 显式 400:B1 起 routes 解除族门禁,落通用 handler,由 generic 网关按选中账号
|
||||
// 的协议能力分发转发。
|
||||
func TestDispatchOpenAICompatibleGatewayRoutesCrossFamilyPoolToGeneric(t *testing.T) {
|
||||
for _, subset := range [][]string{
|
||||
{service.PlatformAnthropic, service.PlatformDeepseek},
|
||||
{service.PlatformOpenAI, service.PlatformGrok, service.PlatformGemini},
|
||||
@@ -168,20 +169,15 @@ func TestDispatchOpenAICompatibleGatewayRejectsCrossFamilyPool(t *testing.T) {
|
||||
{service.PlatformAnthropic, service.PlatformGemini, service.PlatformAntigravity},
|
||||
} {
|
||||
var openAI, generic int
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext(
|
||||
service.WithCompositeCandidatePlatforms(context.Background(), subset))
|
||||
dispatchOpenAICompatibleGateway(c,
|
||||
func(c *gin.Context) { openAI++ },
|
||||
func(c *gin.Context) { generic++ })
|
||||
require.Zero(t, openAI, "subset=%v must not enter the OpenAI handler", subset)
|
||||
require.Zero(t, generic, "subset=%v must not fall through to the generic handler", subset)
|
||||
require.True(t, c.IsAborted(), "subset=%v must abort", subset)
|
||||
require.Equal(t, http.StatusBadRequest, recorder.Code, "subset=%v", subset)
|
||||
for _, platform := range subset {
|
||||
require.Contains(t, recorder.Body.String(), platform, "subset=%v must name every candidate", subset)
|
||||
}
|
||||
require.Equal(t, 1, generic, "subset=%v must fall through to the generic handler", subset)
|
||||
require.False(t, c.IsAborted(), "subset=%v must not be aborted", subset)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,8 +212,8 @@ func TestDispatchOpenAICompatibleGatewayKeepsGenericTargets(t *testing.T) {
|
||||
require.Equal(t, 1, generic)
|
||||
}
|
||||
|
||||
// count_tokens 沿用既有端点语义:兼容族池进 OpenAI CountTokens,跨族池
|
||||
// 明确拒绝,grok 单目标保留 GrokCountTokens。
|
||||
// count_tokens 沿用既有端点语义:兼容族池进 OpenAI CountTokens,跨族池落通用
|
||||
// CountTokens,grok 单目标保留 GrokCountTokens。
|
||||
func TestDispatchOpenAICompatibleCountTokensPoolAndSingle(t *testing.T) {
|
||||
var compatible, grok, generic int
|
||||
handlers := []gin.HandlerFunc{
|
||||
@@ -242,7 +238,7 @@ func TestDispatchOpenAICompatibleCountTokensPoolAndSingle(t *testing.T) {
|
||||
require.Zero(t, grok)
|
||||
require.Zero(t, generic)
|
||||
|
||||
// 跨族池拒绝,任何 handler 都不执行。
|
||||
// 跨族池落通用 CountTokens(generic 链路对不可计数账号按排除重选处理)。
|
||||
c := newContext(func(c *gin.Context) {
|
||||
c.Request = c.Request.WithContext(service.WithCompositeCandidatePlatforms(c.Request.Context(),
|
||||
[]string{service.PlatformAnthropic, service.PlatformDeepseek}))
|
||||
@@ -251,8 +247,8 @@ func TestDispatchOpenAICompatibleCountTokensPoolAndSingle(t *testing.T) {
|
||||
dispatchOpenAICompatibleCountTokens(c, handlers[0], handlers[1], handlers[2])
|
||||
require.Zero(t, compatible)
|
||||
require.Zero(t, grok)
|
||||
require.Zero(t, generic)
|
||||
require.True(t, c.IsAborted())
|
||||
require.Equal(t, 1, generic)
|
||||
require.False(t, c.IsAborted())
|
||||
|
||||
// grok 单目标保留本地估算路径。
|
||||
compatible, grok, generic = 0, 0, 0
|
||||
@@ -340,33 +336,86 @@ func TestCompositeTargetPlatformMiddlewareUsesAnthropicEnvelopeOnMessages(t *tes
|
||||
require.Contains(t, decoded.Error.Message, "totally-unknown-alias")
|
||||
}
|
||||
|
||||
// 跨族池在 /v1/messages 上同样返回 Anthropic 信封;CC 端点保持 OpenAI 信封。
|
||||
func TestCompositeCrossFamilyPoolEnvelopeFollowsInboundProtocol(t *testing.T) {
|
||||
// 跨族池在 /v1/messages 上不再被 400 拒绝:混族池与全兼容族池一样按族归属
|
||||
// 分发(混族落通用 handler),信封由具体 handler 的错误路径决定。
|
||||
func TestCompositeCrossFamilyPoolFallsThroughOnMessagesAndChatCompletions(t *testing.T) {
|
||||
crossFamily := []string{service.PlatformAnthropic, service.PlatformDeepseek}
|
||||
|
||||
// /v1/messages:Anthropic 信封。
|
||||
// /v1/messages:混族池落通用 handler,不再 400。
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext(
|
||||
service.WithCompositeCandidatePlatforms(context.Background(), crossFamily))
|
||||
dispatchOpenAICompatibleGateway(c, func(c *gin.Context) {}, func(c *gin.Context) {})
|
||||
require.True(t, c.IsAborted())
|
||||
var decoded struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &decoded))
|
||||
require.Equal(t, "error", decoded.Type, "messages-family rejections must use the Anthropic envelope")
|
||||
var openAI, generic int
|
||||
dispatchOpenAICompatibleGateway(c,
|
||||
func(c *gin.Context) { openAI++ },
|
||||
func(c *gin.Context) { generic++ })
|
||||
require.Zero(t, openAI)
|
||||
require.Equal(t, 1, generic)
|
||||
require.False(t, c.IsAborted())
|
||||
require.Equal(t, http.StatusOK, recorder.Code, "cross-family pool must reach the generic handler instead of being rejected")
|
||||
|
||||
// /v1/chat/completions:OpenAI 信封。
|
||||
// /v1/chat/completions:混族池同样落通用 handler(B2 再做池化循环)。
|
||||
recorder2 := httptest.NewRecorder()
|
||||
c2, _ := gin.CreateTestContext(recorder2)
|
||||
c2.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil).WithContext(
|
||||
service.WithCompositeCandidatePlatforms(context.Background(), crossFamily))
|
||||
dispatchOpenAICompatibleGateway(c2, func(c *gin.Context) {}, func(c *gin.Context) {})
|
||||
require.True(t, c2.IsAborted())
|
||||
var decoded2 struct {
|
||||
Type string `json:"type"`
|
||||
var openAI2, generic2 int
|
||||
dispatchOpenAICompatibleGateway(c2,
|
||||
func(c *gin.Context) { openAI2++ },
|
||||
func(c *gin.Context) { generic2++ })
|
||||
require.Zero(t, openAI2)
|
||||
require.Equal(t, 1, generic2)
|
||||
require.False(t, c2.IsAborted())
|
||||
}
|
||||
|
||||
// B1 解门禁后的完整路由行为(httptest engine + fake ownership resolver):
|
||||
// 混族池(anthropic+kimi)POST /v1/messages 不再 400、进入 generic handler;
|
||||
// 全 OpenAI 族池仍走 OpenAI handler(不回归)。
|
||||
func TestCompositePoolMessagesDispatchEndToEnd(t *testing.T) {
|
||||
newRouter := func(ownership compositePoolOwnershipStub, openAI, generic gin.HandlerFunc) *gin.Engine {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) {
|
||||
groupID := int64(1)
|
||||
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
|
||||
GroupID: &groupID,
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
|
||||
})
|
||||
c.Next()
|
||||
})))
|
||||
resolver := service.NewCompositeRouteResolver(compositeRouteRepoStub{})
|
||||
resolver.SetModelOwnershipResolver(ownership.ResolveModelOwnership)
|
||||
router.Use(compositeTargetPlatformMiddleware(resolver))
|
||||
// 与 RegisterAPIGatewayRoutes 相同的 /v1/messages 分发闭包。
|
||||
router.POST("/v1/messages", func(c *gin.Context) {
|
||||
dispatchOpenAICompatibleGateway(c, openAI, generic)
|
||||
})
|
||||
return router
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(recorder2.Body.Bytes(), &decoded2))
|
||||
require.Empty(t, decoded2.Type, "chat completions rejections must keep the OpenAI envelope")
|
||||
|
||||
// 混族池:进入 generic handler(不再 400)。
|
||||
genericCalled := false
|
||||
router := newRouter(compositePoolOwnershipStub{platforms: []string{service.PlatformAnthropic, service.PlatformKimi}},
|
||||
func(c *gin.Context) { t.Fatal("mixed pool must not enter the OpenAI handler") },
|
||||
func(c *gin.Context) { genericCalled = true; c.Status(http.StatusNoContent) })
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"cn-alias","max_tokens":1,"messages":[]}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
require.True(t, genericCalled, "mixed pool /v1/messages must reach the generic handler")
|
||||
require.Equal(t, http.StatusNoContent, w.Code)
|
||||
|
||||
// 全 OpenAI 族池:仍走 OpenAI handler(不回归)。
|
||||
openAICalled := false
|
||||
router2 := newRouter(compositePoolOwnershipStub{platforms: []string{service.PlatformDeepseek, service.PlatformKimi}},
|
||||
func(c *gin.Context) { openAICalled = true; c.Status(http.StatusNoContent) },
|
||||
func(c *gin.Context) { t.Fatal("all-OpenAI-family pool must not enter the generic handler") })
|
||||
req2 := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"cn-alias","messages":[]}`))
|
||||
req2.Header.Set("Content-Type", "application/json")
|
||||
w2 := httptest.NewRecorder()
|
||||
router2.ServeHTTP(w2, req2)
|
||||
require.True(t, openAICalled, "all-OpenAI-family pool /v1/messages must keep the OpenAI handler")
|
||||
require.Equal(t, http.StatusNoContent, w2.Code)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// composite 跨平台候选池(account_pool)在 generic(Anthropic 原生)网关侧的接入点。
|
||||
//
|
||||
// 池上下文契约与能力谓词的所有权在 composite_platform.go / composite_account_claims.go;
|
||||
// OpenAI 兼容族接入点镜像见 openai_gateway_scheduling.go。已定稿设计中 generic 网关
|
||||
// 是统一池执行器:按选中账号的协议能力自动分发转发,因此池成员资格只要求
|
||||
// 「平台 ∈ 候选池」且账号可被 generic messages 路径服务,具体协议分支(原生
|
||||
// Anthropic / anthropic-协议 / adaptive / OpenAI 兼容委派)由 handler 层分发决定。
|
||||
// 本文件能力判定全部走能力谓词,不引入新的平台硬编码清单——ollama_cloud 合入后
|
||||
// 凭账号协议能力自动继承,无需改这里。
|
||||
|
||||
// GenericCompositePoolActive 报告当前请求是否按「composite account_pool」进入
|
||||
// generic 调度器。语义镜像 openAICompositePoolActive:显式 resolved 平台优先于池
|
||||
// (ctx 已带 ResolvedTargetPlatform,含 Gemini pin 语义,此时即使 ctx 残留候选池
|
||||
// 也按单平台旧行为调度);池请求 ctx 携带候选池且无 resolved 平台。
|
||||
// 导出供 handler 层做池激活分发判定,与调度器共用同一谓词。
|
||||
func GenericCompositePoolActive(ctx context.Context) bool {
|
||||
if _, resolved := ResolvedTargetPlatformFromContext(ctx); resolved {
|
||||
return false
|
||||
}
|
||||
return len(CompositeCandidatePlatformsFromContext(ctx)) > 0
|
||||
}
|
||||
|
||||
// genericCompositePoolAllowsAccount 判定账号是否属于本次请求的候选池,且账号可被
|
||||
// generic messages 路径服务。无池时恒为 false,调用方据此保持原平台相等门行为;
|
||||
// 候选池 immutable,选号 / sticky / 抢槽后复检都必须重新经过本谓词,防止池外账号
|
||||
// 经复检路径混入(池塌缩)。
|
||||
func genericCompositePoolAllowsAccount(ctx context.Context, account *Account) bool {
|
||||
if account == nil || !genericCompositePoolAccountServable(account) {
|
||||
return false
|
||||
}
|
||||
for _, platform := range CompositeCandidatePlatformsFromContext(ctx) {
|
||||
if platform == account.Platform {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// genericCompositePoolAccountServable 报告账号能否被 generic messages 路径服务。
|
||||
// 纯能力判定,不依赖候选池:
|
||||
// - PlatformAnthropic:generic 网关原生账号(OAuth/APIKey/ServiceAccount);
|
||||
// - gemini / antigravity:既有 generic 调度支持的平台;
|
||||
// - anthropic-协议 / adaptive 多协议账号:要求能解析出 Anthropic 协议上游 base
|
||||
// (GetAnthropicProtocolBaseURL 非空,含 api_base_urls.anthropic 与供应商×模式
|
||||
// 默认端点),避免入池后转发期才发现无端点可用;
|
||||
// - OpenAI 兼容账号(openai/grok/国产供应商/opencode_go):转发由 handler 层
|
||||
// 委派协议转换链服务,不因账号停留在 Chat Completions 协议而被池排除。
|
||||
func genericCompositePoolAccountServable(account *Account) bool {
|
||||
if account == nil {
|
||||
return false
|
||||
}
|
||||
switch account.Platform {
|
||||
case PlatformAnthropic, PlatformGemini, PlatformAntigravity:
|
||||
return true
|
||||
}
|
||||
if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() {
|
||||
return strings.TrimSpace(account.GetAnthropicProtocolBaseURL()) != ""
|
||||
}
|
||||
return account.IsOpenAICompatible()
|
||||
}
|
||||
|
||||
// GenericCompositePoolCountableAccount 报告账号可被 generic count_tokens 链路服务
|
||||
// (端点转发或本地估算兜底由 handler 分发决定):anthropic 原生 / anthropic-协议 /
|
||||
// adaptive / gemini / antigravity 可计数;纯 OpenAI 族(无 Anthropic 协议能力)不算。
|
||||
// 导出供 handler 层在池请求跳过不可计数账号(重选而非 500)。
|
||||
func GenericCompositePoolCountableAccount(account *Account) bool {
|
||||
if account == nil {
|
||||
return false
|
||||
}
|
||||
switch account.Platform {
|
||||
case PlatformAnthropic, PlatformGemini, PlatformAntigravity:
|
||||
return true
|
||||
}
|
||||
return account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol()
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
package service
|
||||
|
||||
// generic(Anthropic 原生)网关侧 composite 跨平台候选池(account_pool)测试。
|
||||
//
|
||||
// 镜像 openai_composite_pool_scheduling_test.go / composite_pool_contract_test.go
|
||||
// 的构造手法(fake repo/cache + credentials 携带 model_mapping / api_protocol /
|
||||
// api_base_urls)。覆盖:
|
||||
// a. {anthropic, kimi(adaptive)} 双平台池按 priority/LRU 跨平台选中;
|
||||
// b. claim 门:候选平台内不 claim 模型的账号不被选(非池请求保持
|
||||
// IsModelSupported 原语义);
|
||||
// c. sticky 命中池外 / 已不 claim 账号时被池成员门拦下,绑定不清;
|
||||
// d. failover 排除后跨平台选中并粘新账号,池不塌缩;
|
||||
// e. 负载感知链路(SelectAccountWithLoadAwareness / resolvePlatform)放行池,
|
||||
// 原 "composite candidate pool" 报错不再出现;
|
||||
// f. 池谓词契约:servable / countable / resolved 平台 pin 优先。
|
||||
// g. 转发 base 协议化:adaptive / anthropic-协议账号经 generic 转发打
|
||||
// {base}/v1/messages(无 ?beta=true);classic anthropic 保持
|
||||
// base_url+/v1/messages?beta=true + x-api-key 不回归;count_tokens 与
|
||||
// passthrough 链同源。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// ---- 测试专用 fake ----
|
||||
|
||||
// genericPoolTestGroupRepo 提供 composite 分组解析(GetByIDLite / GetByID)。
|
||||
type genericPoolTestGroupRepo struct {
|
||||
GroupRepository
|
||||
group *Group
|
||||
}
|
||||
|
||||
func (r *genericPoolTestGroupRepo) GetByID(context.Context, int64) (*Group, error) {
|
||||
if r.group == nil {
|
||||
return nil, errors.New("group not found")
|
||||
}
|
||||
return r.group, nil
|
||||
}
|
||||
|
||||
func (r *genericPoolTestGroupRepo) GetByIDLite(_ context.Context, _ int64) (*Group, error) {
|
||||
if r.group == nil {
|
||||
return nil, errors.New("group not found")
|
||||
}
|
||||
return r.group, nil
|
||||
}
|
||||
|
||||
// genericPoolTestAccountRepo 平台过滤语义与生产 repo 一致;组维度按 GroupIDs /
|
||||
// AccountGroups 过滤(对齐生产 ListSchedulableByGroupIDAndPlatform 的 SQL 语义),
|
||||
// 指针接收者支持用例中途改账号状态。
|
||||
type genericPoolTestAccountRepo struct {
|
||||
AccountRepository
|
||||
accounts []Account
|
||||
}
|
||||
|
||||
func (r *genericPoolTestAccountRepo) 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("account not found")
|
||||
}
|
||||
|
||||
func (r *genericPoolTestAccountRepo) listByPlatform(platform string) []Account {
|
||||
var out []Account
|
||||
for i := range r.accounts {
|
||||
if r.accounts[i].Platform == platform {
|
||||
out = append(out, r.accounts[i])
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *genericPoolTestAccountRepo) ListSchedulableByGroupIDAndPlatform(_ context.Context, groupID int64, platform string) ([]Account, error) {
|
||||
var out []Account
|
||||
for i := range r.accounts {
|
||||
if r.accounts[i].Platform != platform {
|
||||
continue
|
||||
}
|
||||
for _, ag := range r.accounts[i].AccountGroups {
|
||||
if ag.GroupID == groupID {
|
||||
out = append(out, r.accounts[i])
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *genericPoolTestAccountRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]Account, error) {
|
||||
return r.listByPlatform(platform), nil
|
||||
}
|
||||
|
||||
func (r *genericPoolTestAccountRepo) ListSchedulableUngroupedByPlatform(_ context.Context, platform string) ([]Account, error) {
|
||||
var out []Account
|
||||
for i := range r.accounts {
|
||||
if r.accounts[i].Platform == platform && len(r.accounts[i].AccountGroups) == 0 {
|
||||
out = append(out, r.accounts[i])
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// genericPoolTestAccount 构造池用 APIKey 账号:credentials 携带 model_mapping 与
|
||||
// 多协议字段(api_protocol / api_base_urls),extra 透传(认证 scheme 覆写等)。
|
||||
func genericPoolTestAccount(id int64, platform string, groupID int64, priority int, credentials map[string]any, extra map[string]any) Account {
|
||||
account := Account{
|
||||
ID: id,
|
||||
Platform: platform,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 1,
|
||||
Priority: priority,
|
||||
AccountGroups: []AccountGroup{{AccountID: id, GroupID: groupID}},
|
||||
Credentials: credentials,
|
||||
}
|
||||
if extra != nil {
|
||||
account.Extra = extra
|
||||
}
|
||||
return account
|
||||
}
|
||||
|
||||
func newGenericPoolTestService(accounts []Account, group *Group, cache GatewayCache, cfg *config.Config) (*GatewayService, *genericPoolTestAccountRepo) {
|
||||
repo := &genericPoolTestAccountRepo{accounts: accounts}
|
||||
if cfg == nil {
|
||||
cfg = &config.Config{}
|
||||
}
|
||||
svc := &GatewayService{
|
||||
accountRepo: repo,
|
||||
groupRepo: &genericPoolTestGroupRepo{group: group},
|
||||
cache: cache,
|
||||
cfg: cfg,
|
||||
}
|
||||
return svc, repo
|
||||
}
|
||||
|
||||
func newGenericPoolTestGroup(id int64) *Group {
|
||||
return &Group{
|
||||
ID: id,
|
||||
Platform: PlatformComposite,
|
||||
Status: "active",
|
||||
Hydrated: true,
|
||||
}
|
||||
}
|
||||
|
||||
func genericPoolTestContext(pool []string) context.Context {
|
||||
return WithCompositeCandidatePlatforms(context.Background(), pool)
|
||||
}
|
||||
|
||||
// ---- a. 跨平台按 priority / LRU 选中 ----
|
||||
|
||||
func TestGenericCompositePool_SelectsAcrossPlatformsByPriorityAndLoad(t *testing.T) {
|
||||
groupID := int64(41001)
|
||||
group := newGenericPoolTestGroup(groupID)
|
||||
// 公开模型 my-model 由两个平台账号分别经显式映射 claim(claims 规则 A)。
|
||||
model := "my-model"
|
||||
pool := []string{PlatformAnthropic, PlatformKimi}
|
||||
ctx := genericPoolTestContext(pool)
|
||||
|
||||
build := func(anthropicPriority, kimiPriority int, anthropicUsed, kimiUsed *time.Time) *GatewayService {
|
||||
anthropic := genericPoolTestAccount(44001, PlatformAnthropic, groupID, anthropicPriority,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil)
|
||||
kimi := genericPoolTestAccount(44002, PlatformKimi, groupID, kimiPriority,
|
||||
map[string]any{
|
||||
"model_mapping": map[string]any{"my-model": "kimi-k3"},
|
||||
"api_protocol": APIProtocolAdaptive,
|
||||
}, nil)
|
||||
anthropic.LastUsedAt = anthropicUsed
|
||||
kimi.LastUsedAt = kimiUsed
|
||||
svc, _ := newGenericPoolTestService([]Account{anthropic, kimi}, group, &compositePoolTestCache{}, nil)
|
||||
return svc
|
||||
}
|
||||
|
||||
// priority 更小者跨平台获胜:kimi(0) 压过 anthropic(5)。
|
||||
selected, err := build(5, 0, nil, nil).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44002, selected.ID)
|
||||
|
||||
// 反转 priority:anthropic(0) 获胜。
|
||||
selected, err = build(0, 5, nil, nil).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44001, selected.ID)
|
||||
|
||||
// 同 priority 时 LRU:从未使用的账号获胜。
|
||||
now := time.Now()
|
||||
selected, err = build(0, 0, &now, nil).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44002, selected.ID)
|
||||
|
||||
// 更久未用(或从未使用)的账号获胜。
|
||||
stale := now.Add(-2 * time.Hour)
|
||||
recent := now.Add(-1 * time.Hour)
|
||||
selected, err = build(0, 0, &stale, &recent).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44001, selected.ID)
|
||||
|
||||
// 池 immutable:ctx 候选池完整、未写 ResolvedTargetPlatform(不塌缩)。
|
||||
require.ElementsMatch(t, pool, CompositeCandidatePlatformsFromContext(ctx))
|
||||
_, resolved := ResolvedTargetPlatformFromContext(ctx)
|
||||
require.False(t, resolved)
|
||||
}
|
||||
|
||||
// ---- b. claim 门:候选平台内不 claim 模型的账号不被选 ----
|
||||
|
||||
func TestGenericCompositePool_ClaimGateFiltersNonClaimingAccounts(t *testing.T) {
|
||||
groupID := int64(41002)
|
||||
group := newGenericPoolTestGroup(groupID)
|
||||
model := "my-model"
|
||||
pool := []string{PlatformAnthropic, PlatformKimi, PlatformZhipu}
|
||||
ctx := genericPoolTestContext(pool)
|
||||
|
||||
// zhipu 在候选池中但不 claim my-model(mapping 未命中)→ 被 claims 谓词过滤。
|
||||
accounts := []Account{
|
||||
genericPoolTestAccount(44101, PlatformAnthropic, groupID, 5,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil),
|
||||
genericPoolTestAccount(44102, PlatformKimi, groupID, 1,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "kimi-k3"}}, nil),
|
||||
genericPoolTestAccount(44103, PlatformZhipu, groupID, 0,
|
||||
map[string]any{"model_mapping": map[string]any{"other-model": "glm-5.2"}}, nil),
|
||||
}
|
||||
svc, _ := newGenericPoolTestService(accounts, group, &compositePoolTestCache{}, nil)
|
||||
|
||||
selected, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44102, selected.ID, "最低 priority 的 zhipu 不 claim 模型,应由 claim 命中的 kimi 入选")
|
||||
|
||||
// 谓词直测:池请求用 claims(防 IsModelSupported 的 allow-all 冒领),非池请求
|
||||
// 保持 IsModelSupported 原语义。
|
||||
poolCtx := genericPoolTestContext([]string{PlatformKimi, PlatformZhipu})
|
||||
// 空 mapping 的 kimi 账号对无关平台模型是 allow-all(旧语义),但 claims 规则 B
|
||||
// 下 detector 平台不一致 → 池路径不得入选。
|
||||
kimiEmpty := genericPoolTestAccount(44104, PlatformKimi, groupID, 0, nil, nil)
|
||||
require.True(t, kimiEmpty.IsModelSupported("deepseek-chat"), "旧语义 allow-all 仍成立,池路径必须改用 claims 谓词")
|
||||
require.False(t, svc.gatewaySchedulingModelSupported(poolCtx, &kimiEmpty, "deepseek-chat"))
|
||||
require.True(t, svc.gatewaySchedulingModelSupported(context.Background(), &kimiEmpty, "deepseek-chat"))
|
||||
// 池内平台 + 显式 mapping 命中:claims 通过。
|
||||
require.True(t, svc.gatewaySchedulingModelSupported(poolCtx, &accounts[2], "other-model"))
|
||||
}
|
||||
|
||||
// ---- c. sticky 命中池外 / 已不 claim 账号时被池成员门拦下 ----
|
||||
|
||||
func TestGenericCompositePool_StickyBlockedOutsidePoolOrClaimless(t *testing.T) {
|
||||
groupID := int64(41003)
|
||||
group := newGenericPoolTestGroup(groupID)
|
||||
sessionHash := "sessgenericpool01"
|
||||
model := "my-model"
|
||||
pool := []string{PlatformAnthropic, PlatformKimi}
|
||||
ctx := genericPoolTestContext(pool)
|
||||
|
||||
// 池外账号(openai)也声明 my-model:仅池成员门能拦下它。
|
||||
accounts := []Account{
|
||||
genericPoolTestAccount(44201, PlatformAnthropic, groupID, 0,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil),
|
||||
genericPoolTestAccount(44202, PlatformKimi, groupID, 0,
|
||||
map[string]any{
|
||||
"model_mapping": map[string]any{"my-model": "kimi-k3"},
|
||||
"api_protocol": APIProtocolAdaptive,
|
||||
}, nil),
|
||||
genericPoolTestAccount(44203, PlatformOpenAI, groupID, 0,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "gpt-5.5"}}, nil),
|
||||
}
|
||||
cache := &compositePoolTestCache{}
|
||||
svc, _ := newGenericPoolTestService(accounts, group, cache, nil)
|
||||
|
||||
// Case 1:绑定指向池外 openai 账号 → 池成员门拦下,改选池内账号;随后按既有
|
||||
// 选号绑定行为把绑定更新到新选中的账号(与 OpenAI 族 failover 语义一致)。
|
||||
require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 44203))
|
||||
selected, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil)
|
||||
require.NoError(t, err)
|
||||
require.NotEqualValues(t, 44203, selected.ID)
|
||||
require.EqualValues(t, 44201, selected.ID)
|
||||
bound, ok := cache.binding(groupID, sessionHash)
|
||||
require.True(t, ok)
|
||||
require.EqualValues(t, 44201, bound)
|
||||
|
||||
// Case 2:绑定指向 anthropic,但账号 mapping 已不 claim my-model → sticky miss,
|
||||
// 改选 claim 命中的池内账号(kimi)。
|
||||
require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 44201))
|
||||
accounts[0].Credentials = map[string]any{"model_mapping": map[string]any{"other-model": "claude-sonnet-4-5"}}
|
||||
selected, err = svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44202, selected.ID)
|
||||
}
|
||||
|
||||
// ---- d. failover 排除后跨平台选中并粘新账号,池不塌缩 ----
|
||||
|
||||
func TestGenericCompositePool_FailoverExcludesFailedAccountAndSticksToNewPlatform(t *testing.T) {
|
||||
groupID := int64(41004)
|
||||
group := newGenericPoolTestGroup(groupID)
|
||||
sessionHash := "sessgenericpool02"
|
||||
model := "my-model"
|
||||
pool := []string{PlatformAnthropic, PlatformKimi}
|
||||
ctx := genericPoolTestContext(pool)
|
||||
|
||||
accounts := []Account{
|
||||
genericPoolTestAccount(44301, PlatformAnthropic, groupID, 0,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil),
|
||||
genericPoolTestAccount(44302, PlatformKimi, groupID, 0,
|
||||
map[string]any{
|
||||
"model_mapping": map[string]any{"my-model": "kimi-k3"},
|
||||
"api_protocol": APIProtocolAdaptive,
|
||||
}, nil),
|
||||
}
|
||||
cache := &compositePoolTestCache{}
|
||||
svc, _ := newGenericPoolTestService(accounts, group, cache, nil)
|
||||
|
||||
first, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44301, first.ID)
|
||||
|
||||
// 排除失败账号后跨平台选中 kimi,并更新同组绑定。
|
||||
excluded := map[int64]struct{}{44301: {}}
|
||||
second, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, excluded)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44302, second.ID)
|
||||
bound, ok := cache.binding(groupID, sessionHash)
|
||||
require.True(t, ok)
|
||||
require.EqualValues(t, 44302, bound)
|
||||
|
||||
// 后续请求粘新账号;原报错文案不再出现。
|
||||
third, err := svc.SelectAccountForModelWithExclusions(ctx, &groupID, sessionHash, model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44302, third.ID)
|
||||
require.ElementsMatch(t, pool, CompositeCandidatePlatformsFromContext(ctx))
|
||||
}
|
||||
|
||||
// ---- e. 负载感知链路放行池(resolvePlatform 池分支不再报错) ----
|
||||
|
||||
func TestGenericCompositePool_LoadAwareSelectsAcrossPlatforms(t *testing.T) {
|
||||
groupID := int64(41005)
|
||||
group := newGenericPoolTestGroup(groupID)
|
||||
model := "my-model"
|
||||
pool := []string{PlatformAnthropic, PlatformKimi}
|
||||
ctx := genericPoolTestContext(pool)
|
||||
|
||||
cfg := &config.Config{}
|
||||
cfg.Gateway.Scheduling.LoadBatchEnabled = true
|
||||
accounts := []Account{
|
||||
genericPoolTestAccount(44401, PlatformAnthropic, groupID, 5,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil),
|
||||
genericPoolTestAccount(44402, PlatformKimi, groupID, 0,
|
||||
map[string]any{
|
||||
"model_mapping": map[string]any{"my-model": "kimi-k3"},
|
||||
"api_protocol": APIProtocolAdaptive,
|
||||
}, nil),
|
||||
}
|
||||
svc, _ := newGenericPoolTestService(accounts, group, &compositePoolTestCache{}, cfg)
|
||||
svc.concurrencyService = NewConcurrencyService(schedulerTestConcurrencyCache{})
|
||||
|
||||
selection, err := svc.SelectAccountWithLoadAwareness(ctx, &groupID, "", model, nil, "", 0)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, selection)
|
||||
require.EqualValues(t, 44402, selection.Account.ID, "priority 更小的 kimi 跨平台获胜,resolvePlatform 池分支不再报 candidate pool 错误")
|
||||
|
||||
// sticky 命中池内账号时正常复检通过。
|
||||
sessionHash := "sessgenericpool05"
|
||||
require.NoError(t, svc.BindStickySession(ctx, &groupID, sessionHash, 44401))
|
||||
selection, err = svc.SelectAccountWithLoadAwareness(ctx, &groupID, sessionHash, model, nil, "", 0)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44401, selection.Account.ID, "池内 sticky 正常命中")
|
||||
|
||||
// sticky 命中的账号不再 claim 模型:Layer 1.5 模型门拦下,回退负载感知选中
|
||||
// 仍在 claim 的池内账号。
|
||||
accounts[0].Credentials = map[string]any{"model_mapping": map[string]any{"other-model": "claude-sonnet-4-5"}}
|
||||
selection, err = svc.SelectAccountWithLoadAwareness(ctx, &groupID, sessionHash, model, nil, "", 0)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44402, selection.Account.ID)
|
||||
}
|
||||
|
||||
// ---- e2. 显式 resolved 平台 pin 优先于池(单平台旧行为保持) ----
|
||||
|
||||
func TestGenericCompositePool_ResolvedPlatformPinBeatsPool(t *testing.T) {
|
||||
groupID := int64(41006)
|
||||
group := newGenericPoolTestGroup(groupID)
|
||||
model := "my-model"
|
||||
|
||||
accounts := []Account{
|
||||
genericPoolTestAccount(44501, PlatformAnthropic, groupID, 0,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil),
|
||||
genericPoolTestAccount(44502, PlatformKimi, groupID, 5,
|
||||
map[string]any{
|
||||
"model_mapping": map[string]any{"my-model": "kimi-k3"},
|
||||
"api_protocol": APIProtocolAdaptive,
|
||||
}, nil),
|
||||
}
|
||||
svc, _ := newGenericPoolTestService(accounts, group, &compositePoolTestCache{}, nil)
|
||||
|
||||
// pin 到 kimi:即便 anthropic priority 更高也按单平台旧行为选中 kimi。
|
||||
pinnedCtx := WithResolvedTargetPlatform(genericPoolTestContext([]string{PlatformAnthropic, PlatformKimi}), PlatformKimi)
|
||||
selected, err := svc.SelectAccountForModelWithExclusions(pinnedCtx, &groupID, "", model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44502, selected.ID)
|
||||
}
|
||||
|
||||
// ---- f. 池谓词契约:servable / countable / pin 判定 ----
|
||||
|
||||
func TestCompositeGenericPoolPredicates(t *testing.T) {
|
||||
poolCtx := genericPoolTestContext([]string{PlatformAnthropic, PlatformKimi, PlatformOpenAI})
|
||||
|
||||
anthropicNative := genericPoolTestAccount(1, PlatformAnthropic, 7, 0, nil, nil)
|
||||
anthropicOAuth := Account{ID: 2, Platform: PlatformAnthropic, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true}
|
||||
kimiAdaptive := genericPoolTestAccount(3, PlatformKimi, 7, 0,
|
||||
map[string]any{"api_protocol": APIProtocolAdaptive}, nil)
|
||||
kimiChat := genericPoolTestAccount(4, PlatformKimi, 7, 0,
|
||||
map[string]any{"api_protocol": APIProtocolChatCompletions}, nil)
|
||||
zhipuAnthropic := genericPoolTestAccount(5, PlatformZhipu, 7, 0,
|
||||
map[string]any{"api_protocol": APIProtocolAnthropic}, nil)
|
||||
openai := genericPoolTestAccount(6, PlatformOpenAI, 7, 0, nil, nil)
|
||||
gemini := Account{ID: 7, Platform: PlatformGemini, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true}
|
||||
antigravity := Account{ID: 8, Platform: PlatformAntigravity, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true}
|
||||
|
||||
// servable:anthropic 原生(含 OAuth)/ adaptive / anthropic-协议 / gemini /
|
||||
// antigravity / OpenAI 兼容(委派)均可入池。
|
||||
require.True(t, genericCompositePoolAccountServable(&anthropicNative))
|
||||
require.True(t, genericCompositePoolAccountServable(&anthropicOAuth))
|
||||
require.True(t, genericCompositePoolAccountServable(&kimiAdaptive))
|
||||
require.True(t, genericCompositePoolAccountServable(&zhipuAnthropic))
|
||||
require.True(t, genericCompositePoolAccountServable(&kimiChat), "纯 OpenAI 协议国产账号由 handler 委派转发,池成员资格保留")
|
||||
require.True(t, genericCompositePoolAccountServable(&openai))
|
||||
require.True(t, genericCompositePoolAccountServable(&gemini))
|
||||
require.True(t, genericCompositePoolAccountServable(&antigravity))
|
||||
|
||||
// 池成员资格:平台 ∈ 候选池为准;池外平台一律拒绝。
|
||||
require.True(t, genericCompositePoolAllowsAccount(poolCtx, &kimiAdaptive))
|
||||
require.True(t, genericCompositePoolAllowsAccount(poolCtx, &anthropicNative))
|
||||
require.True(t, genericCompositePoolAllowsAccount(poolCtx, &openai))
|
||||
require.False(t, genericCompositePoolAllowsAccount(poolCtx, &gemini), "gemini 不在候选池")
|
||||
require.False(t, genericCompositePoolAllowsAccount(context.Background(), &kimiAdaptive), "无池恒 false")
|
||||
|
||||
// countable:anthropic 原生 / anthropic-协议 / adaptive / gemini / antigravity
|
||||
// 可计数;纯 OpenAI 族(chat_completions 国产 / openai)不算。
|
||||
require.True(t, GenericCompositePoolCountableAccount(&anthropicNative))
|
||||
require.True(t, GenericCompositePoolCountableAccount(&anthropicOAuth))
|
||||
require.True(t, GenericCompositePoolCountableAccount(&kimiAdaptive))
|
||||
require.True(t, GenericCompositePoolCountableAccount(&zhipuAnthropic))
|
||||
require.True(t, GenericCompositePoolCountableAccount(&gemini))
|
||||
require.True(t, GenericCompositePoolCountableAccount(&antigravity))
|
||||
require.False(t, GenericCompositePoolCountableAccount(&kimiChat))
|
||||
require.False(t, GenericCompositePoolCountableAccount(&openai))
|
||||
|
||||
// 池激活判定:resolved 平台优先于池;无池恒 false。
|
||||
require.True(t, GenericCompositePoolActive(poolCtx))
|
||||
require.False(t, GenericCompositePoolActive(WithResolvedTargetPlatform(poolCtx, PlatformKimi)))
|
||||
require.False(t, GenericCompositePoolActive(context.Background()))
|
||||
}
|
||||
|
||||
// ---- g. 转发 base 协议化 ----
|
||||
|
||||
// newAdaptiveAnthropicBaseAccount 构造多协议 APIKey 账号,api_base_urls.anthropic
|
||||
// 指向给定上游 base(adaptive),或 base_url + api_protocol=anthropic。
|
||||
func newAdaptiveAnthropicBaseAccount(id int64, platform string, credentials map[string]any, extra map[string]any) *Account {
|
||||
account := genericPoolTestAccount(id, platform, 0, 0, credentials, extra)
|
||||
return &account
|
||||
}
|
||||
|
||||
func newForwardTestContext() (*gin.Context, *httptest.ResponseRecorder) {
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
return c, rec
|
||||
}
|
||||
|
||||
func newForwardTestService(allowInsecureHTTP bool) *GatewayService {
|
||||
cfg := &config.Config{}
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = allowInsecureHTTP
|
||||
return &GatewayService{cfg: cfg}
|
||||
}
|
||||
|
||||
// TestAnthropicProtocolUpstreamTargetURL_AdaptiveAndAnthropicProtocolNoBeta:
|
||||
// adaptive / anthropic-协议账号经 generic 转发打 {base}/v1/messages,无 ?beta=true;
|
||||
// 认证与实际 base 同源(默认 x-api-key,opt-in Bearer / ollama base 强制 Bearer)。
|
||||
func TestAnthropicProtocolUpstreamTargetURL_AdaptiveAndAnthropicProtocolNoBeta(t *testing.T) {
|
||||
upstreamURL := "http://127.0.0.1:45991/anthropic"
|
||||
svc := newForwardTestService(true)
|
||||
body := []byte(`{"model":"claude-sonnet-4-5","max_tokens":100}`)
|
||||
|
||||
build := func(credentials map[string]any, extra map[string]any) (*http.Request, error) {
|
||||
account := newAdaptiveAnthropicBaseAccount(46001, PlatformKimi, credentials, extra)
|
||||
c, _ := newForwardTestContext()
|
||||
req, _, err := svc.buildUpstreamRequest(context.Background(), c, account, body, "upstream-key", "apikey", "claude-sonnet-4-5", false, false)
|
||||
return req, err
|
||||
}
|
||||
|
||||
// adaptive:api_base_urls.anthropic 生效,{base}/v1/messages 无 beta 参数。
|
||||
req, err := build(map[string]any{
|
||||
"api_key": "upstream-key",
|
||||
"api_protocol": APIProtocolAdaptive,
|
||||
"api_base_urls": map[string]any{"anthropic": upstreamURL},
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, upstreamURL+"/v1/messages", req.URL.String())
|
||||
require.Empty(t, req.URL.RawQuery)
|
||||
require.Equal(t, "upstream-key", req.Header.Get("x-api-key"), "Kimi 默认保持 x-api-key 认证")
|
||||
require.Empty(t, req.Header.Get("Authorization"))
|
||||
|
||||
// adaptive + opt-in Bearer:认证仍与同一 base 同源。
|
||||
req, err = build(map[string]any{
|
||||
"api_key": "upstream-key",
|
||||
"api_protocol": APIProtocolAdaptive,
|
||||
"api_base_urls": map[string]any{"anthropic": upstreamURL},
|
||||
}, map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, upstreamURL+"/v1/messages", req.URL.String())
|
||||
require.Equal(t, "Bearer upstream-key", req.Header.Get("Authorization"))
|
||||
require.Empty(t, req.Header.Get("x-api-key"))
|
||||
|
||||
// anthropic-protocol:credential base_url 即 Anthropic 端点,朴素拼接无 beta。
|
||||
req, err = build(map[string]any{
|
||||
"api_key": "upstream-key",
|
||||
"api_protocol": APIProtocolAnthropic,
|
||||
"base_url": upstreamURL,
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, upstreamURL+"/v1/messages", req.URL.String())
|
||||
require.Empty(t, req.URL.RawQuery)
|
||||
|
||||
// 协议化 base 指向 ollama.com:clamp 与认证判定同源(Bearer + max_tokens 压到 cap)。
|
||||
ollamaBody, _ := sjson.SetBytes(body, "model", "deepseek-v4")
|
||||
ollamaBody, _ = sjson.SetBytes(ollamaBody, "max_tokens", 200000)
|
||||
account := newAdaptiveAnthropicBaseAccount(46002, PlatformDeepseek, map[string]any{
|
||||
"api_key": "upstream-key",
|
||||
"api_protocol": APIProtocolAdaptive,
|
||||
"api_base_urls": map[string]any{"anthropic": "https://ollama.com"},
|
||||
}, nil)
|
||||
c, _ := newForwardTestContext()
|
||||
req, wireBody, err := svc.buildUpstreamRequest(context.Background(), c, account, ollamaBody, "upstream-key", "apikey", "deepseek-v4", false, false)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "https://ollama.com/v1/messages", req.URL.String())
|
||||
require.Empty(t, req.URL.RawQuery)
|
||||
require.Equal(t, "Bearer upstream-key", req.Header.Get("Authorization"), "ollama 上游按实际 base 强制 Bearer")
|
||||
require.EqualValues(t, 65535, gjson.GetBytes(wireBody, "max_tokens").Int(), "clamp 与协议化 base 同源判定")
|
||||
}
|
||||
|
||||
// TestAnthropicProtocolUpstreamTargetURL_ClassicAnthropicKeepsBeta:classic
|
||||
// anthropic 账号保持 base_url+/v1/messages?beta=true + x-api-key 不回归;
|
||||
// count_tokens 与 passthrough 链同源。
|
||||
func TestAnthropicProtocolUpstreamTargetURL_ClassicAnthropicKeepsBeta(t *testing.T) {
|
||||
upstreamURL := "https://relay.example.com"
|
||||
svc := newForwardTestService(false)
|
||||
account := newAdaptiveAnthropicBaseAccount(46003, PlatformAnthropic, map[string]any{
|
||||
"api_key": "anthropic-key",
|
||||
"base_url": upstreamURL,
|
||||
}, nil)
|
||||
body := []byte(`{"model":"claude-sonnet-4-5","max_tokens":100}`)
|
||||
|
||||
// messages:beta=true + x-api-key。
|
||||
c, _ := newForwardTestContext()
|
||||
req, _, err := svc.buildUpstreamRequest(context.Background(), c, account, body, "anthropic-key", "apikey", "claude-sonnet-4-5", false, false)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, upstreamURL+"/v1/messages?beta=true", req.URL.String())
|
||||
require.Equal(t, "beta=true", req.URL.RawQuery)
|
||||
require.Equal(t, "anthropic-key", req.Header.Get("x-api-key"))
|
||||
require.Empty(t, req.Header.Get("Authorization"))
|
||||
|
||||
// count_tokens:beta=true + x-api-key。
|
||||
c, _ = newForwardTestContext()
|
||||
ctReq, _, err := svc.buildCountTokensRequest(context.Background(), c, account, body, "anthropic-key", "apikey", "claude-sonnet-4-5", false)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, upstreamURL+"/v1/messages/count_tokens?beta=true", ctReq.URL.String())
|
||||
require.Equal(t, "anthropic-key", ctReq.Header.Get("x-api-key"))
|
||||
|
||||
// passthrough 链:classic 账号不回归。
|
||||
c, _ = newForwardTestContext()
|
||||
ptReq, _, err := svc.buildUpstreamRequestAnthropicAPIKeyPassthrough(context.Background(), c, account, body, "anthropic-key")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, upstreamURL+"/v1/messages?beta=true", ptReq.URL.String())
|
||||
require.Equal(t, "anthropic-key", ptReq.Header.Get("x-api-key"))
|
||||
|
||||
// count_tokens 协议化 base:{base}/v1/messages/count_tokens,无 beta 参数,
|
||||
// 认证与同一 base 同源(opt-in Bearer)。
|
||||
adaptiveAccount := newAdaptiveAnthropicBaseAccount(46004, PlatformKimi, map[string]any{
|
||||
"api_key": "upstream-key",
|
||||
"api_protocol": APIProtocolAdaptive,
|
||||
"api_base_urls": map[string]any{"anthropic": upstreamURL},
|
||||
}, map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer})
|
||||
c, _ = newForwardTestContext()
|
||||
adaptiveCTReq, _, err := svc.buildCountTokensRequest(context.Background(), c, adaptiveAccount, body, "upstream-key", "apikey", "my-model", false)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, upstreamURL+"/v1/messages/count_tokens", adaptiveCTReq.URL.String())
|
||||
require.Empty(t, adaptiveCTReq.URL.RawQuery)
|
||||
require.Equal(t, "Bearer upstream-key", adaptiveCTReq.Header.Get("Authorization"))
|
||||
}
|
||||
@@ -300,14 +300,19 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough(
|
||||
token string,
|
||||
) (*http.Request, []byte, error) {
|
||||
body = stripDeferredToolCacheControl(body)
|
||||
// 与 buildUpstreamRequest 同源的 base 协议化:CN/多协议账号按协议 base 拼
|
||||
// /v1/messages(无 ?beta=true);classic anthropic 保持
|
||||
// GetBaseURL()+"/v1/messages?beta=true"。认证 / clamp 与本次实际选用的 base 同源。
|
||||
targetURL := claudeAPIURL
|
||||
baseURL := account.GetBaseURL()
|
||||
if baseURL != "" {
|
||||
validatedURL, err := s.validateUpstreamBaseURL(baseURL)
|
||||
anthropicBase := anthropicUpstreamBaseForAuth(account)
|
||||
if account.Type == AccountTypeAPIKey {
|
||||
protocolTargetURL, err := s.anthropicUpstreamTargetURL(account, "/v1/messages")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
targetURL = validatedURL + "/v1/messages?beta=true"
|
||||
if protocolTargetURL != "" {
|
||||
targetURL = protocolTargetURL
|
||||
}
|
||||
}
|
||||
|
||||
// 能力维度 body sanitize:透传路径上 anthropic-beta header 原样透传客户端值,
|
||||
@@ -326,8 +331,8 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough(
|
||||
}
|
||||
|
||||
// Ollama Cloud DeepSeek 出站 max_tokens clamp:判定与上方 targetURL 的
|
||||
// base 取值同源(GetBaseURL),详见 helper 注释。
|
||||
body = clampOllamaCloudAnthropicMessagesMaxTokens(account, account.GetBaseURL(), body)
|
||||
// 协议化 base 取值同源,详见 helper 注释。
|
||||
body = clampOllamaCloudAnthropicMessagesMaxTokens(account, anthropicBase, body)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
@@ -353,8 +358,8 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough(
|
||||
req.Header.Del("x-goog-api-key")
|
||||
req.Header.Del("cookie")
|
||||
// Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方
|
||||
// targetURL 的 base 取值),其余保持 extra/default 行为。
|
||||
setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL())
|
||||
// targetURL 的协议化 base 取值),其余保持 extra/default 行为。
|
||||
setAnthropicAPIKeyAuthHeader(req.Header, account, token, anthropicBase)
|
||||
|
||||
if getHeaderRaw(req.Header, "content-type") == "" {
|
||||
setHeaderRaw(req.Header, "content-type", "application/json")
|
||||
|
||||
@@ -394,14 +394,19 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough(
|
||||
token string,
|
||||
) (*http.Request, error) {
|
||||
body = stripDeferredToolCacheControl(body)
|
||||
// 与 buildUpstreamRequestAnthropicAPIKeyPassthrough 同源的 base 协议化:
|
||||
// CN/多协议账号按协议 base 拼 /v1/messages/count_tokens(无 ?beta=true);
|
||||
// classic anthropic 保持 GetBaseURL()+"/v1/messages/count_tokens?beta=true"。
|
||||
targetURL := claudeAPICountTokensURL
|
||||
baseURL := account.GetBaseURL()
|
||||
if baseURL != "" {
|
||||
validatedURL, err := s.validateUpstreamBaseURL(baseURL)
|
||||
anthropicBase := anthropicUpstreamBaseForAuth(account)
|
||||
if account.Type == AccountTypeAPIKey {
|
||||
protocolTargetURL, err := s.anthropicUpstreamTargetURL(account, "/v1/messages/count_tokens")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
targetURL = validatedURL + "/v1/messages/count_tokens?beta=true"
|
||||
if protocolTargetURL != "" {
|
||||
targetURL = protocolTargetURL
|
||||
}
|
||||
}
|
||||
body = sanitizeCountTokensRequestBody(body)
|
||||
|
||||
@@ -441,8 +446,8 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough(
|
||||
req.Header.Del("x-goog-api-key")
|
||||
req.Header.Del("cookie")
|
||||
// Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方
|
||||
// targetURL 的 base 取值),其余保持 extra/default 行为。
|
||||
setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL())
|
||||
// targetURL 的协议化 base 取值),其余保持 extra/default 行为。
|
||||
setAnthropicAPIKeyAuthHeader(req.Header, account, token, anthropicBase)
|
||||
|
||||
if req.Header.Get("content-type") == "" {
|
||||
req.Header.Set("content-type", "application/json")
|
||||
@@ -461,16 +466,19 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough(
|
||||
// buildCountTokensRequest 构建 count_tokens 上游请求
|
||||
func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Context, account *Account, body []byte, token, tokenType, modelID string, mimicClaudeCode bool) (*http.Request, []byte, error) {
|
||||
body = stripDeferredToolCacheControl(body)
|
||||
// 确定目标 URL
|
||||
// 确定目标 URL。base 协议化与 buildUpstreamRequest 同源:CN/多协议账号
|
||||
//(api_protocol=anthropic/adaptive)按 {base}/v1/messages/count_tokens 拼、
|
||||
// 不带 ?beta=true;classic anthropic 保持 GetBaseURL()+...?beta=true。认证与
|
||||
// 本次实际选用的 base 同源(anthropicUpstreamBaseForAuth)。
|
||||
targetURL := claudeAPICountTokensURL
|
||||
anthropicBase := anthropicUpstreamBaseForAuth(account)
|
||||
if account.Type == AccountTypeAPIKey {
|
||||
baseURL := account.GetBaseURL()
|
||||
if baseURL != "" {
|
||||
validatedURL, err := s.validateUpstreamBaseURL(baseURL)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
targetURL = validatedURL + "/v1/messages/count_tokens?beta=true"
|
||||
protocolTargetURL, err := s.anthropicUpstreamTargetURL(account, "/v1/messages/count_tokens")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if protocolTargetURL != "" {
|
||||
targetURL = protocolTargetURL
|
||||
}
|
||||
} else if account.IsCustomBaseURLEnabled() {
|
||||
customURL := account.GetCustomBaseURL()
|
||||
@@ -553,8 +561,8 @@ func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Con
|
||||
setHeaderRaw(req.Header, "authorization", "Bearer "+token)
|
||||
} else {
|
||||
// Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方
|
||||
// targetURL 的 base 取值),其余保持 extra/default 行为。
|
||||
setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL())
|
||||
// targetURL 的协议化 base 取值),其余保持 extra/default 行为。
|
||||
setAnthropicAPIKeyAuthHeader(req.Header, account, token, anthropicBase)
|
||||
}
|
||||
|
||||
// 白名单透传 headers(恢复真实 wire casing)
|
||||
|
||||
@@ -57,13 +57,17 @@ func (s *GatewayService) SelectAccountForModelWithExclusions(ctx context.Context
|
||||
return nil, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel)
|
||||
}
|
||||
if isCompositePoolDecision(decision) {
|
||||
// 多平台候选池由统一 OpenAI 兼容 selector 选择(openai_gateway_scheduling
|
||||
// 链路);generic 调度器不消费池,显式失败避免以空平台误调度。
|
||||
return nil, fmt.Errorf("%w supporting model: %s (composite candidate pool %s)", ErrNoAvailableAccounts, requestedModel, strings.Join(decision.CandidatePlatforms, ","))
|
||||
// 多平台候选池:generic 网关成为统一池执行器,按候选平台跨平台选号。
|
||||
// 平台保持 composite 哨兵(仅用于日志/诊断,下游门按 ctx 候选池判定);
|
||||
// 池不改写请求体模型,最终平台由选号结果决定。候选池写回 ctx
|
||||
//(immutable),供 listSchedulableAccounts 与 sticky/模型门使用。
|
||||
ctx = WithCompositeRouteDecision(ctx, decision)
|
||||
platform = PlatformComposite
|
||||
} else {
|
||||
platform = decision.TargetPlatform
|
||||
requestedModel = decision.UpstreamModel
|
||||
ctx = WithCompositeRouteDecision(ctx, decision)
|
||||
}
|
||||
platform = decision.TargetPlatform
|
||||
requestedModel = decision.UpstreamModel
|
||||
ctx = WithCompositeRouteDecision(ctx, decision)
|
||||
}
|
||||
} else {
|
||||
// 无分组时只使用原生 anthropic 平台
|
||||
@@ -216,7 +220,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro
|
||||
}
|
||||
}
|
||||
|
||||
platform, hasForcePlatform, err := s.resolvePlatform(ctx, groupID, group, requestedModel)
|
||||
ctx, platform, hasForcePlatform, err := s.resolvePlatform(ctx, groupID, group, requestedModel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -301,11 +305,11 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro
|
||||
if !s.isGatewayAccountProfitEligible(ctx, account) {
|
||||
continue
|
||||
}
|
||||
if !s.isAccountAllowedForPlatform(account, platform, useMixed) {
|
||||
if !s.gatewaySchedulingPlatformMatchesAccount(ctx, account, platform, useMixed) {
|
||||
filteredPlatform++
|
||||
continue
|
||||
}
|
||||
if requestedModel != "" && !s.isModelSupportedByAccountWithContext(ctx, account, requestedModel) {
|
||||
if requestedModel != "" && !s.gatewaySchedulingModelSupported(ctx, account, requestedModel) {
|
||||
filteredModelMapping++
|
||||
continue
|
||||
}
|
||||
@@ -361,8 +365,8 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro
|
||||
|
||||
gatePass := s.isAccountSchedulableForSelection(stickyAccount) &&
|
||||
s.isGatewayAccountProfitEligible(ctx, stickyAccount) &&
|
||||
s.isAccountAllowedForPlatform(stickyAccount, platform, useMixed) &&
|
||||
(requestedModel == "" || s.isModelSupportedByAccountWithContext(ctx, stickyAccount, requestedModel)) &&
|
||||
s.gatewaySchedulingPlatformMatchesAccount(ctx, stickyAccount, platform, useMixed) &&
|
||||
(requestedModel == "" || s.gatewaySchedulingModelSupported(ctx, stickyAccount, requestedModel)) &&
|
||||
!isChannelRestricted(stickyAccount) &&
|
||||
s.isAccountSchedulableForModelSelection(ctx, stickyAccount, requestedModel) &&
|
||||
s.isAccountSchedulableForQuota(stickyAccount) &&
|
||||
@@ -545,9 +549,9 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro
|
||||
// 注意:不再检查 isAccountInGroup,因为 accountByID 已经从按分组过滤的
|
||||
// accounts 列表构建,账号一定在分组内。而 scheduler snapshot 缓存
|
||||
// 反序列化后 AccountGroups 字段为空,导致 isAccountInGroup 永远返回 false。
|
||||
platformOK := s.isAccountAllowedForPlatform(account, platform, useMixed)
|
||||
platformOK := s.gatewaySchedulingPlatformMatchesAccount(ctx, account, platform, useMixed)
|
||||
profitOK := s.isGatewayAccountProfitEligible(ctx, account)
|
||||
modelSupported := requestedModel == "" || s.isModelSupportedByAccountWithContext(ctx, account, requestedModel)
|
||||
modelSupported := requestedModel == "" || s.gatewaySchedulingModelSupported(ctx, account, requestedModel)
|
||||
channelOK := !isChannelRestricted(account)
|
||||
modelSchedulable := s.isAccountSchedulableForModelSelection(ctx, account, requestedModel)
|
||||
quotaOK := s.isAccountSchedulableForQuota(account)
|
||||
@@ -670,10 +674,10 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro
|
||||
if !s.isGatewayAccountProfitEligible(ctx, acc) {
|
||||
continue
|
||||
}
|
||||
if !s.isAccountAllowedForPlatform(acc, platform, useMixed) {
|
||||
if !s.gatewaySchedulingPlatformMatchesAccount(ctx, acc, platform, useMixed) {
|
||||
continue
|
||||
}
|
||||
if requestedModel != "" && !s.isModelSupportedByAccountWithContext(ctx, acc, requestedModel) {
|
||||
if requestedModel != "" && !s.gatewaySchedulingModelSupported(ctx, acc, requestedModel) {
|
||||
continue
|
||||
}
|
||||
if isChannelRestricted(acc) {
|
||||
@@ -975,54 +979,68 @@ func (s *GatewayService) checkClaudeCodeRestriction(ctx context.Context, groupID
|
||||
return group, resolvedID, nil
|
||||
}
|
||||
|
||||
func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, group *Group, requestedModel string) (string, bool, error) {
|
||||
// resolvePlatform 解析本次请求的调度平台。返回值携带可能被池决策写回的 ctx:
|
||||
// composite account_pool 决策在此把 immutable 候选池写入 ctx(供 listSchedulableAccounts
|
||||
// 与 sticky/模型门使用),平台返回 composite 哨兵(仅用于日志/诊断);单平台请求
|
||||
// 保持原语义,不写任何池值。
|
||||
func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, group *Group, requestedModel string) (context.Context, string, bool, error) {
|
||||
forcePlatform, hasForcePlatform := ctx.Value(ctxkey.ForcePlatform).(string)
|
||||
if hasForcePlatform && forcePlatform != "" {
|
||||
return forcePlatform, true, nil
|
||||
return ctx, forcePlatform, true, nil
|
||||
}
|
||||
if platform, ok := ResolvedTargetPlatformFromContext(ctx); ok {
|
||||
return platform, false, nil
|
||||
return ctx, platform, false, nil
|
||||
}
|
||||
if group != nil {
|
||||
if group.Platform == PlatformComposite {
|
||||
decision, ok, err := s.resolveCompositeRouteDecision(ctx, group, requestedModel, CompositeRouteEndpointAny)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
return ctx, "", false, err
|
||||
}
|
||||
if !ok {
|
||||
return "", false, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel)
|
||||
return ctx, "", false, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel)
|
||||
}
|
||||
if isCompositePoolDecision(decision) {
|
||||
return "", false, fmt.Errorf("%w supporting model: %s (composite candidate pool %s)", ErrNoAvailableAccounts, requestedModel, strings.Join(decision.CandidatePlatforms, ","))
|
||||
// 池决策写回 ctx(immutable 候选池),平台保持 composite 哨兵用于日志。
|
||||
return WithCompositeRouteDecision(ctx, decision), PlatformComposite, false, nil
|
||||
}
|
||||
return decision.TargetPlatform, false, nil
|
||||
return ctx, decision.TargetPlatform, false, nil
|
||||
}
|
||||
return group.Platform, false, nil
|
||||
return ctx, group.Platform, false, nil
|
||||
}
|
||||
if groupID != nil {
|
||||
group, err := s.resolveGroupByID(ctx, *groupID)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
return ctx, "", false, err
|
||||
}
|
||||
if group.Platform == PlatformComposite {
|
||||
decision, ok, err := s.resolveCompositeRouteDecision(ctx, group, requestedModel, CompositeRouteEndpointAny)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
return ctx, "", false, err
|
||||
}
|
||||
if !ok {
|
||||
return "", false, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel)
|
||||
return ctx, "", false, fmt.Errorf("%w supporting model: %s (composite target platform unknown)", ErrNoAvailableAccounts, requestedModel)
|
||||
}
|
||||
if isCompositePoolDecision(decision) {
|
||||
return "", false, fmt.Errorf("%w supporting model: %s (composite candidate pool %s)", ErrNoAvailableAccounts, requestedModel, strings.Join(decision.CandidatePlatforms, ","))
|
||||
// 池决策写回 ctx(immutable 候选池),平台保持 composite 哨兵用于日志。
|
||||
return WithCompositeRouteDecision(ctx, decision), PlatformComposite, false, nil
|
||||
}
|
||||
return decision.TargetPlatform, false, nil
|
||||
return ctx, decision.TargetPlatform, false, nil
|
||||
}
|
||||
return group.Platform, false, nil
|
||||
return ctx, group.Platform, false, nil
|
||||
}
|
||||
return PlatformAnthropic, false, nil
|
||||
return ctx, PlatformAnthropic, false, nil
|
||||
}
|
||||
|
||||
func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) ([]Account, bool, error) {
|
||||
// composite account_pool:跨候选平台逐平台查询合并去重(镜像 OpenAI 族
|
||||
// listSchedulableAccountsForCompositePool)。池请求不走 composite 哨兵平台的
|
||||
// snapshot/repo 查询(该桶不存在);池请求不做混合调度展开,候选平台各自的
|
||||
// 账号经独立桶进入既有选号算法。
|
||||
if GenericCompositePoolActive(ctx) {
|
||||
accounts, err := s.listSchedulableAccountsForCompositePool(ctx, groupID, CompositeCandidatePlatformsFromContext(ctx))
|
||||
return accounts, false, err
|
||||
}
|
||||
if s.schedulerSnapshot != nil {
|
||||
accounts, useMixed, err := s.schedulerSnapshot.ListSchedulableAccounts(ctx, groupID, platform, hasForcePlatform)
|
||||
if err == nil {
|
||||
@@ -1094,16 +1112,7 @@ func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *i
|
||||
return s.filterAccountsBySchedulingThreshold(ctx, filtered), useMixed, nil
|
||||
}
|
||||
|
||||
var accounts []Account
|
||||
var err error
|
||||
if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple {
|
||||
accounts, err = s.accountRepo.ListSchedulableByPlatform(ctx, platform)
|
||||
} else if groupID != nil {
|
||||
accounts, err = s.accountRepo.ListSchedulableByGroupIDAndPlatform(ctx, *groupID, platform)
|
||||
// 分组内无账号则返回空列表,由上层处理错误,不再回退到全平台查询
|
||||
} else {
|
||||
accounts, err = s.accountRepo.ListSchedulableUngroupedByPlatform(ctx, platform)
|
||||
}
|
||||
accounts, err := s.listSchedulableAccountsSinglePlatform(ctx, groupID, platform, hasForcePlatform)
|
||||
if err != nil {
|
||||
slog.Debug("account_scheduling_list_failed",
|
||||
"group_id", derefGroupID(groupID),
|
||||
@@ -1126,11 +1135,74 @@ func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *i
|
||||
"tls_fingerprint", acc.IsTLSFingerprintEnabled())
|
||||
}
|
||||
}
|
||||
return accounts, useMixed, nil
|
||||
}
|
||||
|
||||
// listSchedulableAccountsForCompositePool 逐候选 platform 读取既有单平台桶并把结果
|
||||
// 复制进新 slice、按账号 ID 去重(镜像 OpenAI 族同名做法)。每个桶经独立的
|
||||
// snapshot→DB fallback 链路,语义与单平台完全等价;池 immutable,这里不就地修改
|
||||
// 任何共享缓存元素,也不对桶做排序(priority/load/LRU 排序留给下游既有选号算法)。
|
||||
// excludedIDs 由调用方按账号 ID 传递,跨平台天然通用;所有候选健康但均不合格时
|
||||
// 由下游 filter 产出无容量错误(ErrNoAvailableAccounts)。
|
||||
func (s *GatewayService) listSchedulableAccountsForCompositePool(ctx context.Context, groupID *int64, platforms []string) ([]Account, error) {
|
||||
merged := make([]Account, 0, len(platforms)*4)
|
||||
seen := make(map[int64]struct{}, len(platforms)*4)
|
||||
for _, platform := range platforms {
|
||||
// 本次请求被策略 deny 的平台:整平台跳过(候选池本身不变)。
|
||||
if compositePoolPlatformDenied(ctx, platform) {
|
||||
continue
|
||||
}
|
||||
// 池桶强制单平台语义(hasForcePlatform=true):避免 snapshot 把 anthropic
|
||||
// 候选桶展开成 mixed 桶、混入非候选平台的 antigravity 账号。
|
||||
bucket, err := s.listSchedulableAccountsSinglePlatform(ctx, groupID, platform, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range bucket {
|
||||
if _, duplicate := seen[bucket[i].ID]; duplicate {
|
||||
continue
|
||||
}
|
||||
seen[bucket[i].ID] = struct{}{}
|
||||
merged = append(merged, bucket[i])
|
||||
}
|
||||
}
|
||||
return merged, nil
|
||||
}
|
||||
|
||||
// listSchedulableAccountsSinglePlatform 单平台可调度桶:snapshot → DB fallback,
|
||||
// 附调度阈值过滤与 grok 免费配额过滤。与 listSchedulableAccounts 的非混合分支
|
||||
// 同源,供其与 composite 池桶(listSchedulableAccountsForCompositePool)复用。
|
||||
func (s *GatewayService) listSchedulableAccountsSinglePlatform(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) ([]Account, error) {
|
||||
if s.schedulerSnapshot != nil {
|
||||
accounts, _, err := s.schedulerSnapshot.ListSchedulableAccounts(ctx, groupID, platform, hasForcePlatform)
|
||||
if err != nil {
|
||||
return accounts, err
|
||||
}
|
||||
accounts = s.filterAccountsBySchedulingThreshold(ctx, accounts)
|
||||
if platform == PlatformGrok || strings.EqualFold(platform, PlatformGrok) {
|
||||
accounts = s.filterGrokFreeQuotaAccountsForGateway(ctx, accounts)
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
var accounts []Account
|
||||
var err error
|
||||
if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple {
|
||||
accounts, err = s.accountRepo.ListSchedulableByPlatform(ctx, platform)
|
||||
} else if groupID != nil {
|
||||
accounts, err = s.accountRepo.ListSchedulableByGroupIDAndPlatform(ctx, *groupID, platform)
|
||||
// 分组内无账号则返回空列表,由上层处理错误,不再回退到全平台查询
|
||||
} else {
|
||||
accounts, err = s.accountRepo.ListSchedulableUngroupedByPlatform(ctx, platform)
|
||||
}
|
||||
if err != nil {
|
||||
// 保持原样返回原始错误(调用方按 debug 日志记录),不额外包装。
|
||||
return nil, err
|
||||
}
|
||||
accounts = s.filterAccountsBySchedulingThreshold(ctx, accounts)
|
||||
if platform == PlatformGrok || strings.EqualFold(platform, PlatformGrok) {
|
||||
accounts = s.filterGrokFreeQuotaAccountsForGateway(ctx, accounts)
|
||||
}
|
||||
return accounts, useMixed, nil
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
// IsSingleAntigravityAccountGroup 检查指定分组是否只有一个 antigravity 平台的可调度账号。
|
||||
@@ -1157,6 +1229,31 @@ func (s *GatewayService) isAccountAllowedForPlatform(account *Account, platform
|
||||
return account.Platform == platform
|
||||
}
|
||||
|
||||
// gatewaySchedulingPlatformMatchesAccount 是 generic 调度选号/sticky/抢槽后复检的
|
||||
// 账号平台门:composite account_pool 激活时改用候选池成员校验(池 immutable,
|
||||
// 防止 sticky 命中池外账号导致池塌缩),单平台请求保持
|
||||
// isAccountAllowedForPlatform 原语义(含混合调度展开)。
|
||||
func (s *GatewayService) gatewaySchedulingPlatformMatchesAccount(ctx context.Context, account *Account, platform string, useMixed bool) bool {
|
||||
if GenericCompositePoolActive(ctx) {
|
||||
return genericCompositePoolAllowsAccount(ctx, account)
|
||||
}
|
||||
return s.isAccountAllowedForPlatform(account, platform, useMixed)
|
||||
}
|
||||
|
||||
// gatewaySchedulingModelSupported 是 generic 调度选号/sticky 的模型能力门:
|
||||
// 池请求使用契约共享谓词 CompositeAccountClaimsModel(与构池一致,任意强度命中
|
||||
// 均算,防 IsModelSupported 的 allow-all 语义冒领其他平台模型),单平台请求保持
|
||||
// isModelSupportedByAccountWithContext 原语义不变。
|
||||
func (s *GatewayService) gatewaySchedulingModelSupported(ctx context.Context, account *Account, requestedModel string) bool {
|
||||
if account == nil || requestedModel == "" {
|
||||
return true
|
||||
}
|
||||
if GenericCompositePoolActive(ctx) {
|
||||
return CompositeAccountClaimsModel(account, requestedModel)
|
||||
}
|
||||
return s.isModelSupportedByAccountWithContext(ctx, account, requestedModel)
|
||||
}
|
||||
|
||||
func (s *GatewayService) isAccountSchedulableForSelection(account *Account) bool {
|
||||
if account == nil {
|
||||
return false
|
||||
@@ -1933,7 +2030,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context,
|
||||
if clearSticky {
|
||||
_ = s.cache.DeleteSessionAccountID(ctx, derefGroupID(groupID), sessionHash)
|
||||
}
|
||||
if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && account.Platform == platform && (requestedModel == "" || s.isModelSupportedByAccountWithContext(ctx, account, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) && !s.isStickyAccountUpstreamRestricted(ctx, groupID, account, requestedModel) {
|
||||
if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && s.gatewaySchedulingPlatformMatchesAccount(ctx, account, platform, false) && (requestedModel == "" || s.gatewaySchedulingModelSupported(ctx, account, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) && !s.isStickyAccountUpstreamRestricted(ctx, groupID, account, requestedModel) {
|
||||
if s.debugModelRoutingEnabled() {
|
||||
logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] legacy routed sticky hit: group_id=%v model=%s session=%s account=%d", derefGroupID(groupID), requestedModel, shortSessionHash(sessionHash), accountID)
|
||||
}
|
||||
@@ -1990,7 +2087,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context,
|
||||
fmt.Sprintf("Privacy not set, required by group [%s]", schedGroup.Name))
|
||||
continue
|
||||
}
|
||||
if requestedModel != "" && !s.isModelSupportedByAccountWithContext(ctx, acc, requestedModel) {
|
||||
if requestedModel != "" && !s.gatewaySchedulingModelSupported(ctx, acc, requestedModel) {
|
||||
continue
|
||||
}
|
||||
if !s.isAccountSchedulableForModelSelection(ctx, acc, requestedModel) {
|
||||
@@ -2055,7 +2152,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context,
|
||||
if clearSticky {
|
||||
_ = s.cache.DeleteSessionAccountID(ctx, derefGroupID(groupID), sessionHash)
|
||||
}
|
||||
if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && account.Platform == platform && (requestedModel == "" || s.isModelSupportedByAccountWithContext(ctx, account, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) {
|
||||
if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && s.gatewaySchedulingPlatformMatchesAccount(ctx, account, platform, false) && (requestedModel == "" || s.gatewaySchedulingModelSupported(ctx, account, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) {
|
||||
return account, nil
|
||||
}
|
||||
}
|
||||
@@ -2104,7 +2201,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context,
|
||||
fmt.Sprintf("Privacy not set, required by group [%s]", schedGroup.Name))
|
||||
continue
|
||||
}
|
||||
if requestedModel != "" && !s.isModelSupportedByAccountWithContext(ctx, acc, requestedModel) {
|
||||
if requestedModel != "" && !s.gatewaySchedulingModelSupported(ctx, acc, requestedModel) {
|
||||
continue
|
||||
}
|
||||
if needsUpstreamCheck && s.isUpstreamModelRestrictedByChannel(ctx, *groupID, acc, requestedModel) {
|
||||
|
||||
@@ -25,16 +25,21 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex
|
||||
return req, body, err
|
||||
}
|
||||
|
||||
// 确定目标URL
|
||||
// 确定目标URL。Anthropic 上游 base 协议化(仅 APIKey 账号有自定义 base 语义):
|
||||
// CN/多协议账号(api_protocol=anthropic/adaptive)用 GetAnthropicProtocolBaseURL
|
||||
// 拼 {base}/v1/messages,不带 ?beta=true(第三方端点不接受该参数,与 OpenAI 族
|
||||
// nativeAnthropicTargetURL 对齐);classic anthropic 账号保持
|
||||
// GetBaseURL()+"/v1/messages?beta=true" 现状。认证 / max_tokens clamp 与本次
|
||||
// 实际选用的 base 同源(anthropicUpstreamBaseForAuth)。
|
||||
targetURL := claudeAPIURL
|
||||
anthropicBase := anthropicUpstreamBaseForAuth(account)
|
||||
if account.Type == AccountTypeAPIKey {
|
||||
baseURL := account.GetBaseURL()
|
||||
if baseURL != "" {
|
||||
validatedURL, err := s.validateUpstreamBaseURL(baseURL)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
targetURL = validatedURL + "/v1/messages?beta=true"
|
||||
protocolTargetURL, err := s.anthropicUpstreamTargetURL(account, "/v1/messages")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if protocolTargetURL != "" {
|
||||
targetURL = protocolTargetURL
|
||||
}
|
||||
} else if account.IsCustomBaseURLEnabled() {
|
||||
customURL := account.GetCustomBaseURL()
|
||||
@@ -124,9 +129,9 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex
|
||||
}
|
||||
|
||||
// Ollama Cloud DeepSeek 出站 max_tokens clamp:判定与上方 targetURL 的
|
||||
// base 取值同源(GetBaseURL),仅实际上游为 ollama.com 且映射后出站模型
|
||||
// 为 DeepSeek 系时压到 cap,详见 helper 注释。
|
||||
body = clampOllamaCloudAnthropicMessagesMaxTokens(account, account.GetBaseURL(), body)
|
||||
// base 取值同源(GetAnthropicProtocolBaseURL / GetBaseURL 协议化解析),仅
|
||||
// 实际上游为 ollama.com 且映射后出站模型为 DeepSeek 系时压到 cap,详见 helper 注释。
|
||||
body = clampOllamaCloudAnthropicMessagesMaxTokens(account, anthropicBase, body)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", targetURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
@@ -138,8 +143,8 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex
|
||||
setHeaderRaw(req.Header, "authorization", "Bearer "+token)
|
||||
} else {
|
||||
// Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方
|
||||
// targetURL 的 base 取值),其余保持 extra/default 行为。
|
||||
setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL())
|
||||
// targetURL 的协议化 base 取值),其余保持 extra/default 行为。
|
||||
setAnthropicAPIKeyAuthHeader(req.Header, account, token, anthropicBase)
|
||||
}
|
||||
|
||||
// 白名单透传 headers
|
||||
@@ -993,3 +998,42 @@ func (s *GatewayService) validateUpstreamBaseURL(raw string) (string, error) {
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
// anthropicUpstreamBaseForAuth 返回账号本次实际选用的 Anthropic 上游 base(与出站
|
||||
// URL 组装、认证强制 Bearer 判定、max_tokens clamp 判定同源):CN/多协议账号
|
||||
// (api_protocol=anthropic/adaptive)取 GetAnthropicProtocolBaseURL(含
|
||||
// api_base_urls.anthropic 与供应商×模式默认端点),classic anthropic / 官方默认
|
||||
// 账号取 GetBaseURL(OAuth 等无 base 语义时为空串)。认证与 clamp 必须使用本
|
||||
// 返回值而非各自再取 base,保证与真实出站 URL 判定一致。
|
||||
func anthropicUpstreamBaseForAuth(account *Account) string {
|
||||
if base := strings.TrimSpace(account.GetAnthropicProtocolBaseURL()); base != "" {
|
||||
return base
|
||||
}
|
||||
return account.GetBaseURL()
|
||||
}
|
||||
|
||||
// anthropicUpstreamTargetURL 组装 Anthropic 上游端点(path 以 "/" 开头,如
|
||||
// "/v1/messages"、"/v1/messages/count_tokens")。CN/多协议账号(
|
||||
// GetAnthropicProtocolBaseURL 非空)按 {base}{path} 朴素拼接、不附加 ?beta=true
|
||||
// (第三方端点不接受该参数,与 OpenAI 族 nativeAnthropicTargetURL 对齐);
|
||||
// classic anthropic 账号保持 {base}{path}?beta=true 现状。返回空串表示无自定义
|
||||
// base(走官方默认 claudeAPIURL / claudeAPICountTokensURL),由调用方保持默认。
|
||||
func (s *GatewayService) anthropicUpstreamTargetURL(account *Account, path string) (string, error) {
|
||||
protocolBase := strings.TrimSpace(account.GetAnthropicProtocolBaseURL())
|
||||
if protocolBase != "" {
|
||||
validatedURL, err := s.validateUpstreamBaseURL(protocolBase)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimRight(validatedURL, "/") + path, nil
|
||||
}
|
||||
baseURL := account.GetBaseURL()
|
||||
if baseURL == "" {
|
||||
return "", nil
|
||||
}
|
||||
validatedURL, err := s.validateUpstreamBaseURL(baseURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return validatedURL + path + "?beta=true", nil
|
||||
}
|
||||
Reference in new issue
Block a user