mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 08:06:50 +00:00
Merge pull request #7114 from alfadb/feature/composite-ollama-unified
feat(composite, ollama): 统一 Ollama Cloud 平台与跨平台账号池
This commit is contained in:
245 files changed
+22345
-880
No files matched your search
@@ -197,7 +197,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache)
|
||||
proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig)
|
||||
proxyLatencyCache := repository.NewProxyLatencyCache(redisClient)
|
||||
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService, serviceUserPlatformQuotaRepository)
|
||||
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService, billingService, serviceUserPlatformQuotaRepository)
|
||||
adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache, totpService, userService, settingService)
|
||||
groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache)
|
||||
groupHandler := admin.NewGroupHandlerWithConfig(adminService, dashboardService, groupCapacityService, configConfig)
|
||||
@@ -304,8 +304,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
coordinator := securityaudit.NewCoordinator(legacyEngine, promptService)
|
||||
geminiCachedContentRepository := repository.NewGeminiCachedContentRepository(db)
|
||||
geminiCachedContentService := service.ProvideGeminiCachedContentService(geminiCachedContentRepository, geminiMessagesCompatService, configConfig)
|
||||
gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator, geminiCachedContentService)
|
||||
openAIGatewayHandler := handler.ProvideOpenAIGatewayHandler(openAIGatewayService, pluginManager, concurrencyService, billingCacheService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, opsService, grokQuotaService, configConfig, coordinator, compositeRouteResolver)
|
||||
gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator, geminiCachedContentService, openAIGatewayHandler)
|
||||
handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo, notificationEmailService)
|
||||
totpHandler := handler.NewTotpHandler(totpService)
|
||||
passkeyRepository := repository.NewPasskeyRepository(db)
|
||||
|
||||
@@ -184,6 +184,7 @@ const (
|
||||
ProviderDeepseek Provider = "deepseek"
|
||||
ProviderMinimax Provider = "minimax"
|
||||
ProviderOpencodeGo Provider = "opencode_go"
|
||||
ProviderOllamaCloud Provider = "ollama_cloud"
|
||||
)
|
||||
|
||||
func (pr Provider) String() string {
|
||||
@@ -193,7 +194,7 @@ func (pr Provider) String() string {
|
||||
// ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save.
|
||||
func ProviderValidator(pr Provider) error {
|
||||
switch pr {
|
||||
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo:
|
||||
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo, ProviderOllamaCloud:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("channelmonitor: invalid enum value for provider field: %q", pr)
|
||||
|
||||
@@ -110,6 +110,7 @@ const (
|
||||
ProviderDeepseek Provider = "deepseek"
|
||||
ProviderMinimax Provider = "minimax"
|
||||
ProviderOpencodeGo Provider = "opencode_go"
|
||||
ProviderOllamaCloud Provider = "ollama_cloud"
|
||||
)
|
||||
|
||||
func (pr Provider) String() string {
|
||||
@@ -119,7 +120,7 @@ func (pr Provider) String() string {
|
||||
// ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save.
|
||||
func ProviderValidator(pr Provider) error {
|
||||
switch pr {
|
||||
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo:
|
||||
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo, ProviderOllamaCloud:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("channelmonitorrequesttemplate: invalid enum value for provider field: %q", pr)
|
||||
|
||||
@@ -623,7 +623,7 @@ var (
|
||||
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
|
||||
{Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
|
||||
{Name: "name", Type: field.TypeString, Size: 100},
|
||||
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}},
|
||||
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"}},
|
||||
{Name: "check_mode", Type: field.TypeString, Size: 32, Default: "probe"},
|
||||
{Name: "account_id", Type: field.TypeInt64, Nullable: true},
|
||||
{Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"},
|
||||
@@ -776,7 +776,7 @@ var (
|
||||
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
|
||||
{Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
|
||||
{Name: "name", Type: field.TypeString, Size: 100},
|
||||
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}},
|
||||
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"}},
|
||||
{Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"},
|
||||
{Name: "description", Type: field.TypeString, Nullable: true, Size: 500, Default: ""},
|
||||
{Name: "extra_headers", Type: field.TypeJSON},
|
||||
|
||||
@@ -36,7 +36,7 @@ func (ChannelMonitor) Fields() []ent.Field {
|
||||
MaxLen(100),
|
||||
field.Enum("provider").
|
||||
Values("openai", "anthropic", "gemini", "grok",
|
||||
"antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"),
|
||||
"antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"),
|
||||
// check_mode: 'probe' | 'quota' | 'quota_probe'
|
||||
// probe - LLM 探活(默认,原有行为)
|
||||
// quota - 仅查关联账号的用量/余额(零 LLM 成本;endpoint/api_key 可空)
|
||||
|
||||
@@ -40,7 +40,7 @@ func (ChannelMonitorRequestTemplate) Fields() []ent.Field {
|
||||
MaxLen(100),
|
||||
field.Enum("provider").
|
||||
Values("openai", "anthropic", "gemini", "grok",
|
||||
"antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"),
|
||||
"antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"),
|
||||
field.String("api_mode").
|
||||
Default("chat_completions").
|
||||
MaxLen(32).
|
||||
|
||||
@@ -2216,6 +2216,8 @@ func setDefaults() {
|
||||
"api.minimaxi.com", // MiniMax CN quota + inference
|
||||
"api.minimax.io", // MiniMax intl; frozen allowlists must add this host to use the intl site
|
||||
"opencode.ai",
|
||||
"ollama.com",
|
||||
"www.ollama.com",
|
||||
"generativelanguage.googleapis.com",
|
||||
"cloudcode-pa.googleapis.com",
|
||||
"*.openai.azure.com",
|
||||
|
||||
@@ -997,6 +997,8 @@ func TestLoadDefaultSecurityToggles(t *testing.T) {
|
||||
"api.kimi.ai",
|
||||
"api.moonshot.ai",
|
||||
"api.moonshot.cn",
|
||||
"ollama.com",
|
||||
"www.ollama.com",
|
||||
}
|
||||
hostSet := make(map[string]struct{}, len(cfg.Security.URLAllowlist.UpstreamHosts))
|
||||
for _, h := range cfg.Security.URLAllowlist.UpstreamHosts {
|
||||
@@ -1012,7 +1014,7 @@ func TestLoadDefaultSecurityToggles(t *testing.T) {
|
||||
RequireAllowlist: true,
|
||||
AllowPrivate: cfg.Security.URLAllowlist.AllowPrivateHosts,
|
||||
}
|
||||
for _, host := range []string{"api.kimi.com", "api.kimi.ai"} {
|
||||
for _, host := range []string{"api.kimi.com", "api.kimi.ai", "ollama.com", "www.ollama.com"} {
|
||||
target := "https://" + host + "/coding/v1/usages"
|
||||
normalized, err := urlvalidator.ValidateHTTPSURL(target, opts)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -37,17 +37,25 @@ const (
|
||||
PlatformCommandCode = "command_code"
|
||||
// PlatformCline 是 Cline API(多模型聚合,OpenAI 兼容 Chat Completions;按量积分计费,
|
||||
// 另有 ClinePass 订阅)。
|
||||
PlatformCline = "cline"
|
||||
PlatformComposite = "composite"
|
||||
PlatformCline = "cline"
|
||||
// PlatformOllamaCloud 是 Ollama Cloud 订阅制聚合上游(多协议 API Key 网关)。
|
||||
PlatformOllamaCloud = "ollama_cloud"
|
||||
PlatformComposite = "composite"
|
||||
)
|
||||
|
||||
// Account mode constants 区分国产供应商的「按量付费(余额)」与「Coding Plan」两种接入方式。
|
||||
// 存储于 credentials["account_mode"],决定 base_url 预设与额度监控方式。
|
||||
// ollama_cloud 的两代额度语义同存于此键:legacy 是 5h/7d 滚动窗口(与 Go 订阅同类,
|
||||
// 受阈值停调保护);credits 是 2026-08-31 新定价后的月度美元信用池(无滚动窗口,
|
||||
// 用完不硬停,不走阈值停调)。
|
||||
const (
|
||||
AccountModePayG = "payg" // 按量付费:消耗余额,做余额检测冷却
|
||||
AccountModeCoding = "coding" // Coding Plan:滚动用量窗口冷却(5h / weekly)
|
||||
AccountModeZen = "zen" // OpenCode Zen:按量付费,https://opencode.ai/zen/v1
|
||||
AccountModeGo = "go" // OpenCode Go:订阅额度窗口,https://opencode.ai/zen/go/v1
|
||||
|
||||
AccountModeOllamaLegacy = "ollama_legacy" // Ollama Cloud legacy:5h / 7d 滚动窗口
|
||||
AccountModeOllamaCredits = "ollama_credits" // Ollama Cloud 月度美元信用池
|
||||
)
|
||||
|
||||
// API protocol constants 国产供应商的上游 API 协议维度。存储于
|
||||
|
||||
@@ -48,6 +48,8 @@ var platformList = []PlatformSpec{
|
||||
{ID: PlatformTypeSafe, DisplayName: "TypeSafe / Jev", Gateway: PlatformGatewayAnthropic, LiteLLMProvider: "typesafe"},
|
||||
{ID: PlatformCommandCode, DisplayName: "Command Code", Gateway: PlatformGatewayOpenAI},
|
||||
{ID: PlatformCline, DisplayName: "Cline", Gateway: PlatformGatewayOpenAI},
|
||||
// Ollama Cloud 定价目录没有 ollama 条目,LiteLLMProvider 留空(不支持从定价目录同步模型)。
|
||||
{ID: PlatformOllamaCloud, DisplayName: "Ollama Cloud", Gateway: PlatformGatewayOpenAI},
|
||||
}
|
||||
|
||||
var platformIndex = func() map[string]int {
|
||||
|
||||
@@ -7,31 +7,34 @@ import (
|
||||
)
|
||||
|
||||
// 重构前各处手写的平台列表,作为平台清单派生结果的等价基准;重构后新登记的平台
|
||||
// (Command Code、Cline)按同类平台(OpenCode)的位置补入。
|
||||
// (Command Code、Cline、Ollama Cloud)按同类平台(OpenCode)的位置补入。
|
||||
var (
|
||||
legacyDisplayOrder = []string{
|
||||
PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
|
||||
PlatformCommandCode,
|
||||
PlatformCline,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
legacyCompositePrecedence = []string{
|
||||
PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
|
||||
PlatformCommandCode,
|
||||
PlatformCline,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
legacyOpenAIGateway = []string{
|
||||
PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo,
|
||||
PlatformCommandCode,
|
||||
PlatformCline,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
legacyCNProviders = []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax}
|
||||
legacyLiteLLMByPlatf = map[string]string{
|
||||
PlatformAnthropic: "anthropic", PlatformOpenAI: "openai", PlatformGemini: "gemini",
|
||||
PlatformAntigravity: "anthropic", PlatformGrok: "xai", PlatformKimi: "moonshot",
|
||||
PlatformZhipu: "zhipu", PlatformDeepseek: "deepseek", PlatformMiniMax: "minimax",
|
||||
PlatformOpenCodeGo: "opencode-go", PlatformTypeSafe: "typesafe", PlatformCommandCode: "", PlatformCline: "",
|
||||
PlatformOpenCodeGo: "opencode-go", PlatformTypeSafe: "typesafe", PlatformCommandCode: "", PlatformCline: "", PlatformOllamaCloud: "",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -1228,7 +1228,8 @@ func (h *AccountHandler) Update(c *gin.Context) {
|
||||
|
||||
// scheduleOpenAIResponsesProbe 异步触发 OpenAI APIKey 账号的 Responses API 能力探测。
|
||||
//
|
||||
// 仅对 platform=openai && type=apikey 账号生效;其他账号无操作。
|
||||
// 仅对 platform=openai / 国产供应商 / ollama_cloud && type=apikey 账号生效;其他账号
|
||||
// 无操作(国产与 ollama_cloud 在探针内按协议直接落标,不发网络请求)。
|
||||
// 探测本身在 goroutine 中执行(会发一次 HTTP 请求到上游),不会阻塞
|
||||
// 当前请求。探测错误仅记录日志,不向上下文传播:探测失败时标记保持缺失,
|
||||
// 网关会按"现状即证据"默认走 Responses。
|
||||
@@ -2975,6 +2976,19 @@ func (h *AccountHandler) respondAvailableModels(c *gin.Context, account *service
|
||||
return
|
||||
}
|
||||
|
||||
if account.IsOllamaCloud() && len(account.GetModelMapping()) == 0 {
|
||||
allowed := account.GetOllamaCloudOutboundModels()
|
||||
if len(allowed) == 0 {
|
||||
allowed = service.DefaultOllamaCloudModelIDs()
|
||||
}
|
||||
models := make([]claude.Model, 0, len(allowed))
|
||||
for _, id := range allowed {
|
||||
models = append(models, claude.Model{ID: id, Type: "model", DisplayName: id})
|
||||
}
|
||||
response.Success(c, models)
|
||||
return
|
||||
}
|
||||
|
||||
// Handle Claude/Anthropic accounts
|
||||
// For OAuth and Setup-Token accounts: return default models
|
||||
if account.IsOAuth() {
|
||||
|
||||
@@ -606,6 +606,35 @@ func TestSyncPricingModels_ValidPlatform_EmptyService(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// C24:ollama_cloud 故意不进 platformToLiteLLMProvider(LiteLLM 目录无 ollama
|
||||
// 条目,加映射只会返回空列表 = 静默空池),必须保持 400 UNSUPPORTED_PLATFORM;
|
||||
// 其余平台不受影响。
|
||||
func TestSyncPricingModels_OllamaCloudUnsupported(t *testing.T) {
|
||||
svc := service.NewPricingService(nil, nil)
|
||||
router := setupSyncPricingModelsRouter(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/channels/pricing/sync-models?platform="+service.PlatformOllamaCloud, nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, w.Code)
|
||||
var body struct {
|
||||
Code int `json:"code"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
|
||||
require.Equal(t, http.StatusBadRequest, body.Code)
|
||||
require.Equal(t, "UNSUPPORTED_PLATFORM", body.Reason)
|
||||
|
||||
// 非回归:其它平台照常 200。
|
||||
for _, platform := range []string{"anthropic", "openai", service.PlatformOpenCodeGo} {
|
||||
req := httptest.NewRequest(http.MethodGet, "/channels/pricing/sync-models?platform="+platform, nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code, "platform=%s", platform)
|
||||
}
|
||||
}
|
||||
|
||||
func setupModelDefaultPricingRouter() *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
|
||||
@@ -40,7 +40,7 @@ func NewChannelMonitorHandler(monitorService *service.ChannelMonitorService) *Ch
|
||||
|
||||
type channelMonitorCreateRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"`
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go ollama_cloud"`
|
||||
APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
|
||||
Endpoint string `json:"endpoint" binding:"omitempty,max=500"`
|
||||
APIKey string `json:"api_key" binding:"omitempty,max=2000"`
|
||||
@@ -64,7 +64,7 @@ type channelMonitorCreateRequest struct {
|
||||
|
||||
type channelMonitorUpdateRequest struct {
|
||||
Name *string `json:"name" binding:"omitempty,max=100"`
|
||||
Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"`
|
||||
Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go ollama_cloud"`
|
||||
APIMode *string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
|
||||
Endpoint *string `json:"endpoint" binding:"omitempty,max=500"`
|
||||
APIKey *string `json:"api_key" binding:"omitempty,max=2000"`
|
||||
|
||||
@@ -25,8 +25,10 @@ func NewChannelMonitorRequestTemplateHandler(templateService *service.ChannelMon
|
||||
// --- DTO ---
|
||||
|
||||
type channelMonitorTemplateCreateRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok"`
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
// Provider 为历史短列表:CN 5 平台缺失属历史债(本批不扩),仅补 ollama_cloud
|
||||
// 与监控/模板的 service 层放行对齐。模板按 provider 与监控匹配(应用时校验一致)。
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok ollama_cloud"`
|
||||
APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
|
||||
Description string `json:"description" binding:"max=500"`
|
||||
ExtraHeaders map[string]string `json:"extra_headers"`
|
||||
|
||||
@@ -12,9 +12,9 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 回归分组平台枚举:kimi/zhipu/deepseek/opencode_go 必须能通过 Create/Update 的
|
||||
// binding 校验(历史 bug:调度/路由链路已支持这些平台,但 oneof 白名单漏加,
|
||||
// 导致平台分组无法创建、账号"无可用分组");非法值仍须被拒。
|
||||
// 回归分组平台枚举:kimi/zhipu/deepseek/opencode_go/ollama_cloud 必须能通过
|
||||
// Create/Update 的 binding 校验(历史 bug:调度/路由链路已支持这些平台,但 oneof
|
||||
// 白名单漏加,导致平台分组无法创建、账号"无可用分组");非法值仍须被拒。
|
||||
func bindGroupPlatformJSON(t *testing.T, target any, body string) error {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
@@ -29,7 +29,7 @@ func TestGroupPlatformBinding_AllowedPlatforms(t *testing.T) {
|
||||
"anthropic", "openai", "gemini", "antigravity", "grok",
|
||||
"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "composite",
|
||||
"typesafe",
|
||||
"command_code", "cline",
|
||||
"command_code", "cline", "ollama_cloud",
|
||||
}
|
||||
for _, platform := range allowed {
|
||||
t.Run("create_"+platform, func(t *testing.T) {
|
||||
@@ -74,7 +74,7 @@ func TestGroupPlatformBinding_RejectsInvalidPlatforms(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCompositeRouteTargetPlatform_AllowsConcreteProviders(t *testing.T) {
|
||||
for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe", "command_code", "cline"} {
|
||||
for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe", "command_code", "cline", "ollama_cloud"} {
|
||||
var req CompositeRouteRequest
|
||||
body := fmt.Sprintf(`{"public_model":"m","target_platform":%q}`, platform)
|
||||
require.NoError(t, bindGroupPlatformJSON(t, &req, body))
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
//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
|
||||
}
|
||||
|
||||
// platformScopedSchedulerCache 按桶平台返回快照,与生产调度快照的单平台桶语义一致
|
||||
// (池按候选平台逐桶取号,被 deny 的平台整桶跳过)。
|
||||
type platformScopedSchedulerCache struct {
|
||||
fakeSchedulerCache
|
||||
}
|
||||
|
||||
func (f *platformScopedSchedulerCache) GetSnapshot(_ context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) {
|
||||
out := make([]*service.Account, 0, len(f.accounts))
|
||||
for _, account := range f.accounts {
|
||||
if account != nil && account.Platform == bucket.Platform {
|
||||
out = append(out, account)
|
||||
}
|
||||
}
|
||||
return out, true, nil
|
||||
}
|
||||
|
||||
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 := &platformScopedSchedulerCache{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,
|
||||
usageRepo, // usageLogRepo:委派链结果按 OpenAI 计费链入账
|
||||
nil, nil, nil, nil, nil,
|
||||
cfg,
|
||||
nil, nil,
|
||||
billingService,
|
||||
nil, nil,
|
||||
openAIUpstream, // httpUpstream:委派链假上游
|
||||
service.NewDeferredService(nil, nil, 0), // deferredService:SIMPLE 模式入账后登记 last_used
|
||||
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,
|
||||
openAIHandler: &OpenAIGatewayHandler{gatewayService: openAIGatewayService},
|
||||
}
|
||||
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 池请求选中 adaptive 多协议账号(国产厂商 / Ollama Cloud):其 Anthropic
|
||||
// 兼容层无 count_tokens 端点,与 OpenAI 族链同口径本地估算,不转发上游。
|
||||
func TestCompositePoolCountTokensMultiProtocolAccountEstimatesLocally(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolAdaptiveKimiAccount(41451, 41011, 0)})
|
||||
|
||||
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.Positive(t, gjson.GetBytes(rec.Body.Bytes(), "input_tokens").Int())
|
||||
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)
|
||||
}
|
||||
|
||||
// 委派链结果必须按 OpenAI 口径入账:OpenAI usage 的 prompt_tokens 含缓存读取,
|
||||
// 入账输入 = prompt_tokens - cached_tokens。转成 ForwardResult 走 generic 计费会把
|
||||
// 缓存 token 同时记为输入与缓存读取(双计费)。
|
||||
func TestCompositePoolMessagesDelegatedUsageExcludesCachedInputTokens(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(41151, 41011, 0)})
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
body := `{"id":"chatcmpl-pool-cache","object":"chat.completion","created":1,"model":"kimi-k3","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":100,"completion_tokens":7,"prompt_tokens_details":{"cached_tokens":80}}}`
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"req-cc-pool-cache"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.Messages(c)
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1)
|
||||
require.Equal(t, 20, logs[0].InputTokens, "缓存读取不得再计入输入 token")
|
||||
require.Equal(t, 80, logs[0].CacheReadTokens)
|
||||
require.Equal(t, 7, logs[0].OutputTokens)
|
||||
}
|
||||
|
||||
// 跨族 Messages 池与 OpenAI handler 同语义:分组关闭 allow_messages_dispatch 时 openai
|
||||
// 账号整平台屏蔽、由其余平台承接;开启时 openai 账号可被委派。
|
||||
func TestCompositePoolMessagesRespectsAllowMessagesDispatch(t *testing.T) {
|
||||
t.Run("disabled masks openai", func(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{
|
||||
poolOpenAIAccount(41301, 41011, 0),
|
||||
poolAnthropicAccount(41302, 41011, 10),
|
||||
})
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return anthropicMessagesOKResponse()
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
h.handler.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Empty(t, h.openAIUpstream.snapshot(), "开关关闭时 openai 账号不得承接 /v1/messages")
|
||||
require.Len(t, h.gwUpstream.snapshot(), 1)
|
||||
})
|
||||
|
||||
t.Run("enabled delegates openai", func(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(41304, 41011, 0)})
|
||||
h.group.AllowMessagesDispatch = true
|
||||
|
||||
c, _ := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
h.handler.Messages(c)
|
||||
|
||||
calls := h.openAIUpstream.snapshot()
|
||||
require.NotEmpty(t, calls)
|
||||
require.Contains(t, calls[0].Authorization, "openai-key")
|
||||
require.Empty(t, h.gwUpstream.snapshot())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/iotest"
|
||||
|
||||
"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)
|
||||
}
|
||||
|
||||
// 委派链流中断(已向客户端写出内容、无法 failover):与 OpenAI handler 同语义,
|
||||
// 上游已计量的部分 usage 照常入账(#5148),不得静默漏记。
|
||||
func TestCompositePoolChatCompletionsDelegatedStreamTruncationRecordsPartialUsage(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiAccount(42405, 41011, 0)})
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
stream := "data: {\"id\":\"chatcmpl-cut\",\"object\":\"chat.completion.chunk\",\"model\":\"kimi-k3\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"partial\"}}]}\n\n"
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(io.MultiReader(strings.NewReader(stream), iotest.ErrReader(io.ErrUnexpectedEOF))),
|
||||
}
|
||||
}
|
||||
|
||||
body := `{"model":"my-model","stream":true,"messages":[{"role":"user","content":"hello"}]}`
|
||||
c, _ := h.newRequest(t, "/v1/chat/completions", body, service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.ChatCompletions(c)
|
||||
|
||||
require.Len(t, h.openAIUpstream.snapshot(), 1)
|
||||
logs := h.usageRepo.snapshot()
|
||||
require.Len(t, logs, 1, "流中断的委派结果必须入账")
|
||||
require.EqualValues(t, 42405, logs[0].AccountID)
|
||||
}
|
||||
|
||||
// 池选中 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)),
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,45 @@ import (
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// compositeAccountPoolCandidates 返回当前 composite 请求的账号池候选集合;
|
||||
// 非池请求返回 false。与 service pool 语义一致:已有明确 resolved endpoint
|
||||
// pin(如 Gemini fallback)时按 single 处理——候选数据保留在 ctx 但不作为
|
||||
// 活跃池,handler/route 准入均以 pin 优先。
|
||||
func compositeAccountPoolCandidates(c *gin.Context) ([]string, bool) {
|
||||
if c == nil || c.Request == nil {
|
||||
return nil, false
|
||||
}
|
||||
if _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()); resolved {
|
||||
return nil, false
|
||||
}
|
||||
candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context())
|
||||
if len(candidates) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
return candidates, true
|
||||
}
|
||||
|
||||
// compositeCandidatesWithinAllowed 报告账号池候选是否被允许集完整包含;
|
||||
// 池不折叠为单一平台,任一候选越界即不允许。
|
||||
func compositeCandidatesWithinAllowed(candidates, allowed []string) bool {
|
||||
if len(candidates) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
found := false
|
||||
for _, allowedPlatform := range allowed {
|
||||
if candidate == allowedPlatform {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func ensureCompositeTargetPlatform(c *gin.Context, apiKey *service.APIKey, model string) {
|
||||
if c == nil || c.Request == nil || apiKey == nil || apiKey.Group == nil || apiKey.Group.Platform != service.PlatformComposite {
|
||||
return
|
||||
@@ -17,6 +56,11 @@ func ensureCompositeTargetPlatform(c *gin.Context, apiKey *service.APIKey, model
|
||||
if _, ok := service.ResolvedTargetPlatformFromContext(c.Request.Context()); ok {
|
||||
return
|
||||
}
|
||||
// 账号池请求已由路由层写入完整池决策:不在这里做单平台 detector,
|
||||
// 避免把池折叠成一个平台或产生与 selector 不一致的二次解析。
|
||||
if _, ok := compositeAccountPoolCandidates(c); ok {
|
||||
return
|
||||
}
|
||||
if platform, ok := service.DetectModelPlatform(model); ok {
|
||||
c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), platform))
|
||||
}
|
||||
@@ -27,6 +71,9 @@ func compositeTargetPlatformAllowed(c *gin.Context, apiKey *service.APIKey, mode
|
||||
return true
|
||||
}
|
||||
ensureCompositeTargetPlatform(c, apiKey, model)
|
||||
if candidates, ok := compositeAccountPoolCandidates(c); ok {
|
||||
return compositeCandidatesWithinAllowed(candidates, allowed)
|
||||
}
|
||||
platform, ok := service.ResolvedTargetPlatformFromContext(c.Request.Context())
|
||||
if !ok {
|
||||
return false
|
||||
@@ -44,6 +91,11 @@ func compositeTargetPlatformResolved(c *gin.Context, apiKey *service.APIKey, mod
|
||||
return true
|
||||
}
|
||||
ensureCompositeTargetPlatform(c, apiKey, model)
|
||||
// 账号池是已解析的完整决策(候选集合非空且已落 ctx),不因缺少单一
|
||||
// ResolvedTargetPlatform 而视为未解析。
|
||||
if _, ok := compositeAccountPoolCandidates(c); ok {
|
||||
return true
|
||||
}
|
||||
_, ok := service.ResolvedTargetPlatformFromContext(c.Request.Context())
|
||||
return ok
|
||||
}
|
||||
@@ -197,7 +249,13 @@ func bindOpenAIReasoningEffortPolicyForMessagesRequest(c *gin.Context, apiKey *s
|
||||
}
|
||||
maxEffort, mappings, overLimit, ok := openAIReasoningEffortPolicyForRequest(c, apiKey)
|
||||
if !ok {
|
||||
return
|
||||
// composite 账号池请求没有单一目标平台,准入期判不出策略族;Forward
|
||||
// 服务侧按选中账号是否 openai 决定是否应用(与 single-openai 目标同
|
||||
// 语义),因此这里直接绑定组策略,其余平台的选中结果服务侧会跳过。
|
||||
if _, isPool := compositeAccountPoolCandidates(c); !isPool {
|
||||
return
|
||||
}
|
||||
maxEffort, mappings, overLimit = apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings, apiKey.Group.MaxReasoningEffortOverLimit
|
||||
}
|
||||
if isCNTarget {
|
||||
c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicy(c.Request.Context(), maxEffort, mappings, overLimit))
|
||||
@@ -205,3 +263,63 @@ func bindOpenAIReasoningEffortPolicyForMessagesRequest(c *gin.Context, apiKey *s
|
||||
}
|
||||
c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicyForMessages(c.Request.Context(), body, maxEffort, mappings, overLimit))
|
||||
}
|
||||
|
||||
// compositePoolResponseStateGuardApplies 报告当前请求是否为 composite 账号池
|
||||
// 请求(无单一目标 pin)。previous_response_id 状态归属守卫仅适用池请求;
|
||||
// 单目标请求保留既有转发语义。
|
||||
func compositePoolResponseStateGuardApplies(c *gin.Context, apiKey *service.APIKey) bool {
|
||||
if c == nil || c.Request == nil || apiKey == nil || apiKey.Group == nil || apiKey.Group.Platform != service.PlatformComposite {
|
||||
return false
|
||||
}
|
||||
_, isPool := compositeAccountPoolCandidates(c)
|
||||
return isPool
|
||||
}
|
||||
|
||||
// releaseCompositePoolSelection 在选号之后、handler 抢槽之前的守卫早退路径上
|
||||
// 释放 selector 已持有的账号槽位(Acquired=true 时 ReleaseFunc 非空)。置空
|
||||
// ReleaseFunc 保证恰一次释放,不与后续 acquire/release 路径重复。
|
||||
func releaseCompositePoolSelection(selection *service.AccountSelectionResult) {
|
||||
if selection != nil && selection.ReleaseFunc != nil {
|
||||
selection.ReleaseFunc()
|
||||
selection.ReleaseFunc = nil
|
||||
}
|
||||
}
|
||||
|
||||
// applyCompositePoolAnthropicReasoningEffortPolicy 为 composite 账号池 /v1/messages
|
||||
// 选中 anthropic 账号的 attempt 补齐分组推理强度策略:池请求准入期有效平台为
|
||||
// composite,applyAnthropicReasoningEffortPolicyForRequest 不生效;选中 anthropic
|
||||
// 账号时与单目标 anthropic 同语义,其余平台由各自转发链处理。
|
||||
func applyCompositePoolAnthropicReasoningEffortPolicy(apiKey *service.APIKey, account *service.Account, body []byte) ([]byte, bool, error) {
|
||||
if apiKey == nil || apiKey.Group == nil || account == nil || account.Platform != service.PlatformAnthropic {
|
||||
return body, false, nil
|
||||
}
|
||||
maxEffort, mappings := anthropicCompatibleReasoningEffortPolicy(apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings)
|
||||
return service.ApplyReasoningEffortPolicy(body, maxEffort, mappings, apiKey.Group.MaxReasoningEffortOverLimit)
|
||||
}
|
||||
|
||||
// applyCompositePoolReasoningEffortPolicyForSelectedAccount 在账号选定后为
|
||||
// composite 账号池请求补齐组 reasoning-effort 策略(CC/Responses 直转路径:
|
||||
// 服务侧 forward 不再应用组策略)。池请求准入期没有单一目标平台,无法预判
|
||||
// 策略族;选中 openai 账号时与 single-openai 同语义应用组上限/映射,选中
|
||||
// grok/CN/OpenCode Go 时维持这些平台独立分组「不套用」的既有语义。单目标
|
||||
// 请求已在准入期应用,这里跳过。err 非 nil 表示 deny/over-limit,调用方须以
|
||||
// respondOpenAIReasoningEffortPolicyError 终止请求。
|
||||
func applyCompositePoolReasoningEffortPolicyForSelectedAccount(c *gin.Context, apiKey *service.APIKey, account *service.Account, body []byte) ([]byte, bool, error) {
|
||||
if c == nil || c.Request == nil || apiKey == nil || apiKey.Group == nil || apiKey.Group.Platform != service.PlatformComposite || account == nil {
|
||||
return body, false, nil
|
||||
}
|
||||
if _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()); resolved {
|
||||
return body, false, nil
|
||||
}
|
||||
if _, isPool := compositeAccountPoolCandidates(c); !isPool {
|
||||
return body, false, nil
|
||||
}
|
||||
if account.Platform != service.PlatformOpenAI && account.Platform != service.PlatformAnthropic {
|
||||
return body, false, nil
|
||||
}
|
||||
maxEffort, mappings := apiKey.Group.MaxReasoningEffort, apiKey.Group.ReasoningEffortMappings
|
||||
if account.Platform == service.PlatformAnthropic {
|
||||
maxEffort, mappings = anthropicCompatibleReasoningEffortPolicy(maxEffort, mappings)
|
||||
}
|
||||
return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, apiKey.Group.MaxReasoningEffortOverLimit)
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newCompositePoolTestContext(t *testing.T, path string, platforms ...string) (*gin.Context, *service.APIKey) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest("POST", path, nil)
|
||||
if len(platforms) > 0 {
|
||||
c.Request = c.Request.WithContext(service.WithCompositeCandidatePlatforms(c.Request.Context(), platforms))
|
||||
}
|
||||
apiKey := &service.APIKey{Group: &service.Group{Platform: service.PlatformComposite}}
|
||||
return c, apiKey
|
||||
}
|
||||
|
||||
// 账号池请求不得在 handler 侧再做单平台 detector 解析:池保持未折叠,
|
||||
// ResolvedTargetPlatform 不被写入,候选集合原样保留。
|
||||
func TestEnsureCompositeTargetPlatformKeepsPoolUnfolded(t *testing.T) {
|
||||
c, apiKey := newCompositePoolTestContext(t, "/v1/chat/completions",
|
||||
service.PlatformDeepseek, service.PlatformZhipu)
|
||||
|
||||
ensureCompositeTargetPlatform(c, apiKey, "deepseek-chat")
|
||||
|
||||
_, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context())
|
||||
require.False(t, resolved, "pool request must not gain a single resolved platform from the detector")
|
||||
candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context())
|
||||
require.Equal(t, []string{service.PlatformDeepseek, service.PlatformZhipu}, candidates)
|
||||
}
|
||||
|
||||
// 兼容族文本端点准入:全部候选属于 7 类兼容族的池放行,任一候选越界拒绝;
|
||||
// 池不被折叠成单一平台后单独判断。
|
||||
func TestOpenAICompatibleTextTargetAllowedPoolSemantics(t *testing.T) {
|
||||
family := []string{
|
||||
service.PlatformOpenAI, service.PlatformGrok,
|
||||
service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek,
|
||||
service.PlatformMiniMax, service.PlatformOpenCodeGo,
|
||||
}
|
||||
|
||||
// 全族整体(7 候选)与任意真子集(此处抽 3 个代表)都放行。
|
||||
for _, subset := range [][]string{family, {service.PlatformDeepseek, service.PlatformOpenCodeGo}, {service.PlatformGrok}, {service.PlatformMiniMax, service.PlatformZhipu, service.PlatformKimi}} {
|
||||
c, apiKey := newCompositePoolTestContext(t, "/v1/messages", subset...)
|
||||
require.Truef(t, openAICompatibleTextTargetAllowed(c, apiKey, "deepseek-flash"), "subset=%v", subset)
|
||||
}
|
||||
|
||||
for _, subset := range [][]string{
|
||||
{service.PlatformAnthropic, service.PlatformDeepseek},
|
||||
{service.PlatformOpenAI, service.PlatformGemini},
|
||||
{service.PlatformAntigravity},
|
||||
} {
|
||||
c, apiKey := newCompositePoolTestContext(t, "/v1/messages", subset...)
|
||||
require.Falsef(t, openAICompatibleTextTargetAllowed(c, apiKey, "deepseek-flash"), "subset=%v", subset)
|
||||
}
|
||||
}
|
||||
|
||||
// openai-only 端点(live/alpha search/embeddings 既有准入):池收窄为合法
|
||||
// single(仅 {openai})才放行,更宽的池清晰拒绝。
|
||||
func TestCompositeTargetPlatformAllowedPoolNarrowsOpenAIOnlyEndpoints(t *testing.T) {
|
||||
c, apiKey := newCompositePoolTestContext(t, "/v1/live", service.PlatformOpenAI)
|
||||
require.True(t, compositeTargetPlatformAllowed(c, apiKey, "gpt-realtime", service.PlatformOpenAI))
|
||||
|
||||
c, apiKey = newCompositePoolTestContext(t, "/v1/live", service.PlatformOpenAI, service.PlatformGrok)
|
||||
require.False(t, compositeTargetPlatformAllowed(c, apiKey, "gpt-realtime", service.PlatformOpenAI))
|
||||
c, apiKey = newCompositePoolTestContext(t, "/alpha/search", service.PlatformGrok)
|
||||
require.False(t, compositeTargetPlatformAllowed(c, apiKey, "gpt-5", service.PlatformOpenAI))
|
||||
}
|
||||
|
||||
// 池是已解析的完整决策:compositeTargetPlatformResolved 不得因缺少单一
|
||||
// ResolvedTargetPlatform 把池请求判为未解析。
|
||||
func TestCompositeTargetPlatformResolvedPoolCountsAsResolved(t *testing.T) {
|
||||
c, apiKey := newCompositePoolTestContext(t, "/v1/messages",
|
||||
service.PlatformDeepseek, service.PlatformOpenCodeGo)
|
||||
require.True(t, compositeTargetPlatformResolved(c, apiKey, "deepseek-flash"))
|
||||
_, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context())
|
||||
require.False(t, resolved)
|
||||
}
|
||||
|
||||
// messages dispatch 豁免与单目标同语义:候选全部为 grok/CN/OpenCode Go 时
|
||||
// 豁免分组开关;混有 openai 候选时仍受开关控制。
|
||||
func TestAllowOpenAICompatibleMessagesDispatchPoolExemptions(t *testing.T) {
|
||||
newKey := func(allow bool) *service.APIKey {
|
||||
return &service.APIKey{Group: &service.Group{
|
||||
Platform: service.PlatformComposite,
|
||||
AllowMessagesDispatch: allow,
|
||||
}}
|
||||
}
|
||||
|
||||
// 全 CN/grok 池:与对应独立分组同语义豁免。
|
||||
c, _ := newCompositePoolTestContext(t, "/v1/messages", service.PlatformDeepseek, service.PlatformGrok, service.PlatformKimi)
|
||||
require.True(t, allowOpenAICompatibleMessagesDispatch(c, newKey(false)))
|
||||
|
||||
// 混有 openai 候选:受分组开关控制。
|
||||
c, _ = newCompositePoolTestContext(t, "/v1/messages", service.PlatformOpenAI, service.PlatformDeepseek)
|
||||
require.False(t, allowOpenAICompatibleMessagesDispatch(c, newKey(false)))
|
||||
require.True(t, allowOpenAICompatibleMessagesDispatch(c, newKey(true)))
|
||||
|
||||
// 纯 openai 池:受分组开关控制。
|
||||
c, _ = newCompositePoolTestContext(t, "/v1/messages", service.PlatformOpenAI)
|
||||
require.False(t, allowOpenAICompatibleMessagesDispatch(c, newKey(false)))
|
||||
|
||||
// 非 composite 分组不读池上下文。
|
||||
c, _ = newCompositePoolTestContext(t, "/v1/messages", service.PlatformDeepseek)
|
||||
anthropicKey := &service.APIKey{Group: &service.Group{Platform: service.PlatformAnthropic}}
|
||||
require.False(t, allowOpenAICompatibleMessagesDispatch(c, anthropicKey))
|
||||
}
|
||||
|
||||
// effectiveAPIKeyPlatform 在池请求上保持组平台回退语义(不猜单平台)。
|
||||
func TestEffectiveAPIKeyPlatformWithPoolKeepsGroupFallback(t *testing.T) {
|
||||
c, apiKey := newCompositePoolTestContext(t, "/v1/messages", service.PlatformDeepseek, service.PlatformKimi)
|
||||
require.Equal(t, service.PlatformComposite, effectiveAPIKeyPlatform(c, apiKey))
|
||||
}
|
||||
|
||||
// 池请求的组 effort 策略在账号选定后补齐:选中 openai 账号 → 与
|
||||
// single-openai 同语义应用组上限;选中 grok/CN 账号 → 维持不套用语义;
|
||||
// 单目标请求不重复应用。
|
||||
func TestApplyCompositePoolReasoningEffortPolicyForSelectedAccount(t *testing.T) {
|
||||
overCeiling := []byte(`{"model":"gpt-5.6","reasoning":{"effort":"xhigh"}}`)
|
||||
|
||||
// 池 + openai 账号:超限 effort 被压到组上限。
|
||||
c, apiKey := newCompositePoolTestContext(t, "/v1/responses", service.PlatformOpenAI, service.PlatformDeepseek)
|
||||
apiKey.Group.MaxReasoningEffort = "medium"
|
||||
capped, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount(
|
||||
c, apiKey, &service.Account{Platform: service.PlatformOpenAI}, overCeiling)
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
require.Contains(t, string(capped), `"effort":"medium"`)
|
||||
|
||||
// 池 + grok 账号:维持 grok 独立分组不套用语义。
|
||||
c, apiKey = newCompositePoolTestContext(t, "/v1/responses", service.PlatformOpenAI, service.PlatformDeepseek)
|
||||
_, changed, err = applyCompositePoolReasoningEffortPolicyForSelectedAccount(
|
||||
c, apiKey, &service.Account{Platform: service.PlatformGrok}, overCeiling)
|
||||
require.NoError(t, err)
|
||||
require.False(t, changed)
|
||||
|
||||
// 池 + CN 账号:同上。
|
||||
c, apiKey = newCompositePoolTestContext(t, "/v1/responses", service.PlatformDeepseek)
|
||||
_, changed, err = applyCompositePoolReasoningEffortPolicyForSelectedAccount(
|
||||
c, apiKey, &service.Account{Platform: service.PlatformDeepseek}, overCeiling)
|
||||
require.NoError(t, err)
|
||||
require.False(t, changed)
|
||||
|
||||
// 单目标请求已在准入期应用,选后不重复。
|
||||
c, apiKey = newCompositePoolTestContext(t, "/v1/responses")
|
||||
c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformOpenAI))
|
||||
_, changed, err = applyCompositePoolReasoningEffortPolicyForSelectedAccount(
|
||||
c, apiKey, &service.Account{Platform: service.PlatformOpenAI}, overCeiling)
|
||||
require.NoError(t, err)
|
||||
require.False(t, changed)
|
||||
|
||||
// 非 composite 分组不适用。
|
||||
plainKey := &service.APIKey{Group: &service.Group{Platform: service.PlatformOpenAI, MaxReasoningEffort: "medium"}}
|
||||
c2, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c2.Request = httptest.NewRequest("POST", "/v1/responses", nil)
|
||||
_, changed, err = applyCompositePoolReasoningEffortPolicyForSelectedAccount(
|
||||
c2, plainKey, &service.Account{Platform: service.PlatformOpenAI}, overCeiling)
|
||||
require.NoError(t, err)
|
||||
require.False(t, changed)
|
||||
}
|
||||
|
||||
// 池请求在 messages 桥准入期绑定组策略 ctx:服务侧 ForwardAsAnthropic 按选中
|
||||
// 账号是否 openai 决定是否应用;显式 effort 缺省时不绑定(保桥默认值语义)。
|
||||
func TestBindOpenAIReasoningEffortPolicyForMessagesRequestPool(t *testing.T) {
|
||||
explicit := []byte(`{"model":"deepseek-flash","output_config":{"effort":"xhigh"}}`)
|
||||
defaulted := []byte(`{"model":"deepseek-flash"}`)
|
||||
|
||||
// 池 + 显式 effort:绑定组策略。
|
||||
c, apiKey := newCompositePoolTestContext(t, "/v1/messages", service.PlatformDeepseek, service.PlatformOpenCodeGo)
|
||||
apiKey.Group.MaxReasoningEffort = "medium"
|
||||
bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, explicit)
|
||||
capped, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(c.Request.Context(), explicit)
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed, "pool messages bind must carry the group policy for the bridge to apply")
|
||||
require.Contains(t, string(capped), `"effort":"medium"`, "xhigh must be clamped to the group ceiling")
|
||||
|
||||
// 池 + 无显式 effort:不绑定(桥默认 effort 不受上限改写)。
|
||||
c, apiKey = newCompositePoolTestContext(t, "/v1/messages", service.PlatformDeepseek, service.PlatformOpenCodeGo)
|
||||
bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, defaulted)
|
||||
_, changed, err = service.ApplyOpenAIReasoningEffortPolicyFromContext(c.Request.Context(), defaulted)
|
||||
require.NoError(t, err)
|
||||
require.False(t, changed)
|
||||
}
|
||||
|
||||
// pool 判定与 service 一致:已有 resolved endpoint pin(Gemini fallback)时按
|
||||
// single 语义——候选数据保留但不作为活跃池;allowed/dispatch 以 pin 优先。
|
||||
func TestCompositePoolDetectionDefersToResolvedPin(t *testing.T) {
|
||||
c, apiKey := newCompositePoolTestContext(t, "/v1beta/models/gemini-2.5-pro:generateContent",
|
||||
service.PlatformGemini, service.PlatformDeepseek)
|
||||
c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformGemini))
|
||||
|
||||
// pin 存在时不按活跃池判定:gemini pin 被允许集完整包含。
|
||||
require.True(t, compositeTargetPlatformAllowed(c, apiKey, "gemini-2.5-pro", service.PlatformGemini))
|
||||
require.True(t, compositeTargetPlatformResolved(c, apiKey, "gemini-2.5-pro"))
|
||||
_, isPool := compositeAccountPoolCandidates(c)
|
||||
require.False(t, isPool, "resolved pin must deactivate the pool for admission semantics")
|
||||
|
||||
// pin 存在时按 pin 作为生效平台(single 语义)。
|
||||
require.Equal(t, service.PlatformGemini, effectiveAPIKeyPlatform(c, apiKey))
|
||||
}
|
||||
@@ -51,6 +51,22 @@ func TestOpenAICompatibleTextTargetAllowsCompositeProviders(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// ollama_cloud 目标不会经 DetectModelPlatform 的模型名前缀产生(无 ollama 前缀,
|
||||
// fail closed),只能来自 composite 路由已解析的 context;这里预置解析结果后
|
||||
// 断言文本目标白名单放行 ollama_cloud。
|
||||
func TestOpenAICompatibleTextTargetAllowsOllamaCloudResolvedRoute(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
for _, path := range []string{"/v1/messages", "/v1/chat/completions", "/v1/responses", "/v1/responses/input_tokens", "/v1/messages/count_tokens"} {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest("POST", path, nil)
|
||||
c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformOllamaCloud))
|
||||
apiKey := &service.APIKey{Group: &service.Group{Platform: service.PlatformComposite}}
|
||||
|
||||
require.True(t, openAICompatibleTextTargetAllowed(c, apiKey, "gpt-oss:20b"), "path=%s", path)
|
||||
}
|
||||
}
|
||||
|
||||
// WS ingress 对 CN 账号既过不了 transport 过滤、HTTP 桥也没有 Responses 转换,
|
||||
// 放行只会把明确的策略拒绝换成 "no available account",因此 WS 白名单保持 openai+grok。
|
||||
func TestResponsesWebSocketCompositePlatformGuardKeepsOpenAIAndGrokOnly(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,473 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ip"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// composite 账号池 per-attempt 平台策略(审查修复增量4)。
|
||||
//
|
||||
// 设计C契约:7 兼容族池请求进入原 OpenAIGatewayHandler/selector;池请求的公开
|
||||
// request context / 公开 body 保持 immutable(不把选中平台写回 c.Request)。账号
|
||||
// 选定后,本文件为该 attempt 构造局部 ctx(WithResolvedTargetPlatform,仅作用于
|
||||
// 该次渠道/计费/forward),并对实际平台补做 user×platform 配额预检与渠道限制检
|
||||
// 查——准入 CheckBillingEligibility 时池没有 resolved 平台,这两个维度都被跳过,
|
||||
// 不得只后扣不预检。
|
||||
//
|
||||
// 业务限制的平台级 deny 通过 compositePoolPlatformDenials 记录,再选时以「filtered
|
||||
// candidate ctx」传 selector 做整平台 mask(不把兄弟账号逐个试穿 maxAccountSwitches,
|
||||
// 不写 selector 的原 ctx)。所有候选被业务限制时按原 billingErrorDetails / 渠道
|
||||
// 限制错误语义明确终止,不误报 model unsupported。本文件全部为纯读检查,不写任何
|
||||
// 生产持久状态、不新增 RPM 计数。
|
||||
|
||||
// compositePoolAttemptPolicyApplies 报告当前请求是否按 composite 账号池做
|
||||
// per-attempt 平台策略检查:composite 分组 + ctx 携带候选池 + 无 resolved 单目标。
|
||||
// 显式 pin / single / 普通分组保持旧行为,不做 per-attempt 补检。
|
||||
func compositePoolAttemptPolicyApplies(c *gin.Context, apiKey *service.APIKey) bool {
|
||||
if c == nil || c.Request == nil || apiKey == nil || apiKey.Group == nil || apiKey.Group.Platform != service.PlatformComposite {
|
||||
return false
|
||||
}
|
||||
if _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()); resolved {
|
||||
return false
|
||||
}
|
||||
_, isPool := compositeAccountPoolCandidates(c)
|
||||
return isPool
|
||||
}
|
||||
|
||||
// compositePoolAttemptContext 为选中账号派生 attempt 局部 ctx:在原请求 ctx 之上
|
||||
// 携带 ResolvedTargetPlatform=account.Platform,仅供该 attempt 的渠道作用域、配额
|
||||
// 预检、forward 与计费使用。base(c.Request.Context())不被修改;下一次 selector
|
||||
// 仍看原候选池。已带 resolved 目标的 ctx 原样返回(单目标请求不走池语义)。
|
||||
func compositePoolAttemptContext(base context.Context, account *service.Account) context.Context {
|
||||
if base == nil || account == nil || account.Platform == "" {
|
||||
return base
|
||||
}
|
||||
if _, resolved := service.ResolvedTargetPlatformFromContext(base); resolved {
|
||||
return base
|
||||
}
|
||||
return service.WithResolvedTargetPlatform(base, account.Platform)
|
||||
}
|
||||
|
||||
// syncSelectionEffectiveGroup 在选号发生 ClaudeCodeOnly 跨分组降级切换时,同步当前
|
||||
// 调度分组、请求上下文、渠道映射与池状态(不改写最终计费归属 apiKey)。
|
||||
func (h *GatewayHandler) syncSelectionEffectiveGroup(
|
||||
c *gin.Context,
|
||||
baseAPIKey *service.APIKey,
|
||||
schedAPIKey *service.APIKey,
|
||||
baseCtx context.Context,
|
||||
channelMapping service.ChannelMappingResult,
|
||||
reqModel string,
|
||||
isPoolRequest bool,
|
||||
poolDenials *compositePoolPlatformDenials,
|
||||
selection *service.AccountSelectionResult,
|
||||
) (*service.APIKey, context.Context, service.ChannelMappingResult, bool, *compositePoolPlatformDenials, bool) {
|
||||
if selection == nil || selection.EffectiveGroup == nil || schedAPIKey == nil ||
|
||||
selection.EffectiveGroup.ID == derefGroupID(schedAPIKey.GroupID) {
|
||||
return schedAPIKey, baseCtx, channelMapping, isPoolRequest, poolDenials, false
|
||||
}
|
||||
nextKey := cloneAPIKeyWithGroup(baseAPIKey, selection.EffectiveGroup)
|
||||
nextCtx := baseCtx
|
||||
if selection.SelectionCtx != nil {
|
||||
nextCtx = selection.SelectionCtx
|
||||
}
|
||||
if c != nil && c.Request != nil {
|
||||
c.Request = c.Request.WithContext(nextCtx)
|
||||
}
|
||||
nextPool := service.GenericCompositePoolActive(nextCtx)
|
||||
nextModel := reqModel
|
||||
if !nextPool {
|
||||
if upstreamModel, ok := service.ResolvedUpstreamModelFromContext(nextCtx); ok && upstreamModel != "" {
|
||||
nextModel = upstreamModel
|
||||
}
|
||||
}
|
||||
nextMapping := service.ChannelMappingResult{MappedModel: nextModel, Mapped: nextModel != reqModel}
|
||||
if !nextPool && h != nil && h.gatewayService != nil {
|
||||
resolvedMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(nextCtx, nextKey.GroupID, nextModel)
|
||||
if resolvedMapping.Mapped {
|
||||
nextMapping = resolvedMapping
|
||||
}
|
||||
}
|
||||
return nextKey, nextCtx, nextMapping, nextPool, newCompositePoolPlatformDenials(), true
|
||||
}
|
||||
|
||||
func compositeOrPoolDispatchActive(isPoolRequest bool, schedAPIKey *service.APIKey) bool {
|
||||
return isPoolRequest || (schedAPIKey != nil && schedAPIKey.Group != nil && schedAPIKey.Group.Platform == service.PlatformComposite)
|
||||
}
|
||||
|
||||
// compositePoolPlatformDenials 记录一次请求内被业务限制(配额/渠道限制)的平台,
|
||||
// 供 failover 再选时做整平台 mask。每个请求一个实例,仅在 handler 的顺序 failover
|
||||
// 循环里读写,无并发访问。
|
||||
type compositePoolPlatformDenials struct {
|
||||
denied map[string]struct{}
|
||||
}
|
||||
|
||||
func newCompositePoolPlatformDenials() *compositePoolPlatformDenials {
|
||||
return &compositePoolPlatformDenials{denied: make(map[string]struct{})}
|
||||
}
|
||||
|
||||
func (d *compositePoolPlatformDenials) deny(platform string) {
|
||||
if d == nil || platform == "" {
|
||||
return
|
||||
}
|
||||
if d.denied == nil {
|
||||
d.denied = make(map[string]struct{})
|
||||
}
|
||||
d.denied[platform] = struct{}{}
|
||||
}
|
||||
|
||||
// filterCandidates 返回剔除被 deny 平台后的候选副本;入参不被修改。
|
||||
func (d *compositePoolPlatformDenials) filterCandidates(candidates []string) []string {
|
||||
if d == nil || len(d.denied) == 0 {
|
||||
return append([]string(nil), candidates...)
|
||||
}
|
||||
remaining := make([]string, 0, len(candidates))
|
||||
for _, platform := range candidates {
|
||||
if _, blocked := d.denied[platform]; blocked {
|
||||
continue
|
||||
}
|
||||
remaining = append(remaining, platform)
|
||||
}
|
||||
return remaining
|
||||
}
|
||||
|
||||
// list 返回已 deny 平台的排序副本(写入 ctx 前归一化由 service 侧完成)。
|
||||
func (d *compositePoolPlatformDenials) list() []string {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
platforms := make([]string, 0, len(d.denied))
|
||||
for platform := range d.denied {
|
||||
platforms = append(platforms, platform)
|
||||
}
|
||||
return platforms
|
||||
}
|
||||
|
||||
// compositePoolSelectionRetryContext 返回下一次选号使用的 ctx:候选池保持
|
||||
// immutable(原样保留,不收缩),只叠加请求局部的 deniedPlatforms 列表——
|
||||
// selector 在 list/sticky 门按该列表过滤,sticky 账号因 denied 暂时排除时按
|
||||
// excluded 语义提前返回、不清粘性绑定(改由后续成功请求的正常 Set 改绑)。
|
||||
// 返回 false 表示候选已全部被业务限制,调用方应终止请求而非再选号。未 deny
|
||||
// 任何平台时原样返回 base。
|
||||
func compositePoolSelectionRetryContext(base context.Context, denials *compositePoolPlatformDenials) (context.Context, bool) {
|
||||
if base == nil {
|
||||
return nil, false
|
||||
}
|
||||
candidates := service.CompositeCandidatePlatformsFromContext(base)
|
||||
if len(candidates) == 0 {
|
||||
return base, true
|
||||
}
|
||||
if denials == nil || len(denials.denied) == 0 {
|
||||
return base, true
|
||||
}
|
||||
// 候选已全部被业务限制:终止而不是再选号。
|
||||
if len(denials.filterCandidates(candidates)) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
return service.WithCompositePoolDeniedPlatforms(base, denials.list()), true
|
||||
}
|
||||
|
||||
// compositePoolAttemptPolicyFailure 描述选中账号未通过 per-attempt 平台策略的
|
||||
// 原因。两者互斥评估,但结构上可同时存在(先 quota 后渠道都拒绝时以 quota 为准)。
|
||||
type compositePoolAttemptPolicyFailure struct {
|
||||
// QuotaErr 非 nil 表示 user×platform 日/周/月配额耗尽
|
||||
//(ErrUserPlatform{Daily,Weekly,Monthly}QuotaExhausted,带 window_resets_at
|
||||
// metadata),按 billingErrorDetails 语义终止。
|
||||
QuotaErr error
|
||||
// ChannelRestricted 表示该模型在选中平台作用域下被渠道定价限制拒绝,按调度
|
||||
// 阶段渠道限制同语义终止(账号存在且模型受支持,仅当前平台被限制)。
|
||||
ChannelRestricted bool
|
||||
// AccountChannelRestricted 表示限制仅来自当前账号映射后的 upstream 模型,
|
||||
// 重选时只排除该账号,不整平台屏蔽同平台其它账号。
|
||||
AccountChannelRestricted bool
|
||||
// MessagesDispatchForbidden 表示分组关闭了 AllowMessagesDispatch,禁止 openai 账号
|
||||
// 承接 /v1/messages(终止时须返回 403 permission_error,不能误报 503)。
|
||||
MessagesDispatchForbidden bool
|
||||
}
|
||||
|
||||
func (f compositePoolAttemptPolicyFailure) denied() bool {
|
||||
return f.QuotaErr != nil || f.ChannelRestricted || f.MessagesDispatchForbidden
|
||||
}
|
||||
|
||||
func (f compositePoolAttemptPolicyFailure) deniesPlatform() bool {
|
||||
return f.QuotaErr != nil || f.MessagesDispatchForbidden || (f.ChannelRestricted && !f.AccountChannelRestricted)
|
||||
}
|
||||
|
||||
// compositePoolAttemptPolicy 汇总一次 attempt 的策略检查结果。
|
||||
type compositePoolAttemptPolicy struct {
|
||||
// AttemptCtx 仅供该 attempt 的渠道/计费/forward 使用;不写回 c.Request。
|
||||
AttemptCtx context.Context
|
||||
// Mapping 是选中平台作用域的渠道映射;公开 body immutable,channel-mapped
|
||||
// body 由调用方从 canonical body 派生。
|
||||
Mapping service.ChannelMappingResult
|
||||
// Failure 非 denied 时才允许 forward。
|
||||
Failure compositePoolAttemptPolicyFailure
|
||||
}
|
||||
|
||||
// evaluateCompositePoolAttemptPolicy 对选中账号做 attempt 级平台策略检查:
|
||||
// 1. user×platform 配额预检(纯检查 + cache 回填,不写 RPM、不扣费、不再调用
|
||||
// CheckBillingEligibility——那会二次计数);
|
||||
// 2. 平台作用域渠道限制(requested/channel_mapped/response 计费基准 + upstream
|
||||
// 基准的逐账号检查,与调度阶段同语义、仅作用域为选中平台)。
|
||||
//
|
||||
// requireCompact 须与本次选号调用一致(/responses/compact 路径为 true)。
|
||||
func evaluateCompositePoolAttemptPolicy(
|
||||
baseCtx context.Context,
|
||||
billing *service.BillingCacheService,
|
||||
gateway *service.OpenAIGatewayService,
|
||||
apiKey *service.APIKey,
|
||||
subscription *service.UserSubscription,
|
||||
account *service.Account,
|
||||
requestedModel string,
|
||||
requireCompact bool,
|
||||
) compositePoolAttemptPolicy {
|
||||
result := compositePoolAttemptPolicy{AttemptCtx: baseCtx}
|
||||
if baseCtx == nil || account == nil || account.Platform == "" {
|
||||
return result
|
||||
}
|
||||
result.AttemptCtx = compositePoolAttemptContext(baseCtx, account)
|
||||
result.Failure.QuotaErr = compositePoolAttemptQuotaError(billing, result.AttemptCtx, apiKey, subscription, account.Platform)
|
||||
if result.Failure.QuotaErr != nil {
|
||||
// 平台配额已耗尽:渠道映射仍按平台作用域解析,但请求不再外发。
|
||||
if gateway != nil && apiKey != nil && apiKey.GroupID != nil {
|
||||
result.Mapping = gateway.CompositePoolAttemptChannelMapping(result.AttemptCtx, apiKey.GroupID, requestedModel)
|
||||
}
|
||||
return result
|
||||
}
|
||||
if gateway != nil && apiKey != nil && apiKey.GroupID != nil {
|
||||
result.Mapping = gateway.CompositePoolAttemptChannelMapping(result.AttemptCtx, apiKey.GroupID, requestedModel)
|
||||
platformRestricted, accountRestricted := gateway.CompositePoolAttemptChannelRestriction(result.AttemptCtx, apiKey.GroupID, account, requestedModel, requireCompact)
|
||||
result.Failure.ChannelRestricted = platformRestricted || accountRestricted
|
||||
result.Failure.AccountChannelRestricted = accountRestricted && !platformRestricted
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// compositePoolAttemptQuotaError 是 service 纯配额预检的 handler 侧薄入口。
|
||||
func compositePoolAttemptQuotaError(billing *service.BillingCacheService, attemptCtx context.Context, apiKey *service.APIKey, subscription *service.UserSubscription, platform string) error {
|
||||
if billing == nil || apiKey == nil || platform == "" {
|
||||
return nil
|
||||
}
|
||||
return billing.CheckUserPlatformQuotaEligibilityForRequest(attemptCtx, apiKey.User, apiKey.Group, subscription, platform)
|
||||
}
|
||||
|
||||
// respondCompositePoolAttemptPolicyFailure 按 deny 原因以既有错误语义明确终止请求:
|
||||
// - 配额耗尽 → billingErrorDetails(429 rate_limit_exceeded + Retry-After);
|
||||
// - 渠道限制 → 503 api_error(与调度阶段渠道限制的分类一致;账号与模型持久
|
||||
// 配置都存在,不误报 model_not_found / model unsupported)。
|
||||
//
|
||||
// write 由调用方按入站端点选择(OpenAI 信封 handleStreamingAwareError / Anthropic
|
||||
// 信封 anthropicStreamingAwareError),并自行闭包 streamStarted。
|
||||
func respondCompositePoolAttemptPolicyFailure(c *gin.Context, failure compositePoolAttemptPolicyFailure, write func(*gin.Context, int, string, string)) {
|
||||
if write == nil || !failure.denied() {
|
||||
return
|
||||
}
|
||||
if failure.QuotaErr != nil {
|
||||
status, code, message, retryAfter := billingErrorDetails(failure.QuotaErr)
|
||||
if retryAfter > 0 {
|
||||
c.Header("Retry-After", strconv.Itoa(retryAfter))
|
||||
}
|
||||
write(c, status, code, message)
|
||||
return
|
||||
}
|
||||
if failure.MessagesDispatchForbidden {
|
||||
write(c, http.StatusForbidden, "permission_error", "This group does not allow /v1/messages dispatch")
|
||||
return
|
||||
}
|
||||
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.RequiresOpenAIProtocolChain() {
|
||||
// 按模型分流的聚合平台与无 Anthropic 原生端点的供应商:只有 OpenAI 网关链
|
||||
// 能按模型选协议或完成协议转换。
|
||||
return true
|
||||
}
|
||||
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 handler 的 ForwardResult,仅供 failover / ops 指标等非计费用途。
|
||||
// 两者的 usage 口径不同(OpenAI input_tokens 含缓存读取,Anthropic 口径不含),且
|
||||
// ForwardResult 不携带 BillingModel 等 OpenAI 计费字段:委派结果必须经
|
||||
// submitDelegatedOpenAIUsage 走 OpenAI 计费链,不得用本函数的结果入账。
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
// delegatedOpenAIUsage 是池委派结果入账所需的请求级信息(handler 在请求 ctx 内算定)。
|
||||
type delegatedOpenAIUsage struct {
|
||||
Result *service.OpenAIForwardResult
|
||||
APIKey *service.APIKey
|
||||
Account *service.Account
|
||||
Subscription *service.UserSubscription
|
||||
QuotaPlatform string
|
||||
PricingAt time.Time
|
||||
RequestPayloadHash string
|
||||
ChannelUsageFields service.ChannelUsageFields
|
||||
LogComponent string
|
||||
}
|
||||
|
||||
// rejectCompositePoolCyberSessionBlocked 在账号池选号前按 OpenAI handler 同语义拒绝
|
||||
// 已被 cyber 封禁的会话:池可能委派 OpenAI 网关链,封禁正是为了阻止该会话继续
|
||||
// 发往 OpenAI 上游。返回 true 表示已写出 403。非池请求不调用,路径零变化。
|
||||
func (h *GatewayHandler) rejectCompositePoolCyberSessionBlocked(c *gin.Context, apiKey *service.APIKey, body []byte, model string, format cyberSessionBlockFormat) bool {
|
||||
if h == nil || h.openAIHandler == nil {
|
||||
return false
|
||||
}
|
||||
return h.openAIHandler.rejectIfCyberSessionBlocked(c, apiKey, body, model, format)
|
||||
}
|
||||
|
||||
// recordDelegatedCyberPolicyIfMarked 在池委派 OpenAI 网关链的 attempt 返回后做 cyber
|
||||
// 事后记录(会话封禁、风控事件、forward 出错时的用量行),与 OpenAI handler 各入口
|
||||
// forward 之后的 recordCyberPolicyIfMarked 同口径。无 cyber 标记时为空操作。
|
||||
func (h *GatewayHandler) recordDelegatedCyberPolicyIfMarked(c *gin.Context, apiKey *service.APIKey, account *service.Account, subscription *service.UserSubscription, model string, forwardErrored bool, body []byte, channelFields service.ChannelUsageFields) {
|
||||
if h == nil || h.openAIHandler == nil || service.GetOpsCyberPolicy(c) == nil {
|
||||
return
|
||||
}
|
||||
h.openAIHandler.recordCyberPolicyIfMarked(c, apiKey, account, subscription, model, forwardErrored, body, channelFields, service.HashUsageRequestPayload(body))
|
||||
}
|
||||
|
||||
// compositePoolDelegatedForwardErrorAlreadyCommunicated 按 attempt 实际走的转发链判定
|
||||
// 错误是否已告知客户端:委派 OpenAI 网关链时用该链的判定(上游 response.failed /
|
||||
// cyber 原始错误体已透传),避免 generic 判定把流式响应当作未告知再追加错误帧。
|
||||
func compositePoolDelegatedForwardErrorAlreadyCommunicated(c *gin.Context, delegated bool, writerSizeBeforeForward int, err error) bool {
|
||||
if delegated {
|
||||
return openAIForwardErrorAlreadyCommunicated(c, writerSizeBeforeForward, err)
|
||||
}
|
||||
return gatewayForwardErrorAlreadyCommunicated(c, writerSizeBeforeForward, err)
|
||||
}
|
||||
|
||||
// submitDelegatedOpenAIUsage 用 OpenAI 网关计费链记录池委派结果:委派链产出的是
|
||||
// OpenAI 口径 usage(input_tokens 含缓存读取、BillingModel、生图/搜索附加计费等),
|
||||
// 必须与该账号在 OpenAI 网关上被直接服务时同一口径入账。转成 ForwardResult 走
|
||||
// generic 计费会把缓存 token 重复计费并按公开别名计价。
|
||||
func (h *GatewayHandler) submitDelegatedOpenAIUsage(c *gin.Context, in delegatedOpenAIUsage) {
|
||||
res := in.Result
|
||||
if res == nil || in.APIKey == nil || in.Account == nil || h.openAIGatewayService == nil {
|
||||
return
|
||||
}
|
||||
stampOpenAIRequestedReasoningEffort(res, c)
|
||||
input := &service.OpenAIRecordUsageInput{
|
||||
Result: res,
|
||||
APIKey: in.APIKey,
|
||||
User: in.APIKey.User,
|
||||
Account: in.Account,
|
||||
Subscription: in.Subscription,
|
||||
InboundEndpoint: GetInboundEndpoint(c),
|
||||
UpstreamEndpoint: resolveOpenAIUpstreamEndpoint(c, in.Account, res),
|
||||
UserAgent: c.GetHeader("User-Agent"),
|
||||
IPAddress: ip.GetClientIP(c),
|
||||
SessionID: service.ExtractClientSessionID(c),
|
||||
RequestPayloadHash: in.RequestPayloadHash,
|
||||
APIKeyService: h.apiKeyService,
|
||||
QuotaPlatform: in.QuotaPlatform,
|
||||
PricingAt: in.PricingAt,
|
||||
ChannelUsageFields: in.ChannelUsageFields,
|
||||
CyberBlocked: service.GetOpsCyberPolicy(c) != nil,
|
||||
}
|
||||
task := func(ctx context.Context) {
|
||||
if err := h.openAIGatewayService.RecordUsage(ctx, input); err != nil {
|
||||
logger.L().With(
|
||||
zap.String("component", in.LogComponent),
|
||||
zap.Int64("api_key_id", in.APIKey.ID),
|
||||
zap.Any("group_id", in.APIKey.GroupID),
|
||||
zap.Int64("account_id", in.Account.ID),
|
||||
).Error("gateway.composite_pool.delegated_record_usage_failed", zap.Error(err))
|
||||
}
|
||||
}
|
||||
// 与 OpenAI handler 同口径:生图、搜索附加费、语音等不可在溢出时丢弃。
|
||||
if res.ImageCount > 0 || res.VideoCount > 0 || res.SearchCount > 0 || res.WebSearchCalls > 0 || res.AudioUsage != nil {
|
||||
h.submitMandatoryUsageRecordTask(c.Request.Context(), task)
|
||||
return
|
||||
}
|
||||
h.submitUsageRecordTask(c.Request.Context(), task)
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
package handler
|
||||
|
||||
// composite 账号池 per-attempt 平台策略(handler 侧辅助文件)的单元测试:
|
||||
// attempt 局部 ctx 纯度、被拒平台的整平台 mask 与重选 ctx、配额/渠道限制的终止
|
||||
// 错误语义。池完整链路(选号→策略→forward→计费)的行为测试在
|
||||
// internal/server/routes/gateway_composite_pool_attempt_policy_test.go(待 2B
|
||||
// handler 文件移交接线后补齐)。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// ── fakes:只覆盖测试涉及的缓存/仓储入口,其余方法内嵌接口零值 ────────────────
|
||||
|
||||
type poolAttemptFakeQuotaCache struct {
|
||||
service.BillingCache
|
||||
entry *service.UserPlatformQuotaCacheEntry
|
||||
}
|
||||
|
||||
func (f *poolAttemptFakeQuotaCache) GetUserPlatformQuotaCache(context.Context, int64, string) (*service.UserPlatformQuotaCacheEntry, bool, error) {
|
||||
if f.entry == nil {
|
||||
return nil, false, nil
|
||||
}
|
||||
return f.entry, true, nil
|
||||
}
|
||||
|
||||
func (f *poolAttemptFakeQuotaCache) SetUserPlatformQuotaCache(context.Context, int64, string, *service.UserPlatformQuotaCacheEntry, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type poolAttemptFakeQuotaRepo struct {
|
||||
service.UserPlatformQuotaRepository
|
||||
rec *service.UserPlatformQuotaRecord
|
||||
}
|
||||
|
||||
func (f *poolAttemptFakeQuotaRepo) GetByUserPlatform(context.Context, int64, string) (*service.UserPlatformQuotaRecord, error) {
|
||||
return f.rec, nil
|
||||
}
|
||||
|
||||
type poolAttemptFakeChannelRepo struct {
|
||||
service.ChannelRepository
|
||||
channels []service.Channel
|
||||
platforms map[int64]string
|
||||
listAllCnt int
|
||||
}
|
||||
|
||||
func (f *poolAttemptFakeChannelRepo) ListAll(context.Context) ([]service.Channel, error) {
|
||||
f.listAllCnt++
|
||||
return f.channels, nil
|
||||
}
|
||||
|
||||
func (f *poolAttemptFakeChannelRepo) GetGroupPlatforms(context.Context, []int64) (map[int64]string, error) {
|
||||
return f.platforms, nil
|
||||
}
|
||||
|
||||
func newPoolAttemptBilling(t *testing.T, entry *service.UserPlatformQuotaCacheEntry) *service.BillingCacheService {
|
||||
t.Helper()
|
||||
cfg := &config.Config{RunMode: config.RunModeStandard}
|
||||
cfg.Billing.UserPlatformQuotaCacheTTLSeconds = 60
|
||||
return service.NewBillingCacheService(
|
||||
&poolAttemptFakeQuotaCache{entry: entry}, nil, nil, nil, nil, nil, cfg,
|
||||
&poolAttemptFakeQuotaRepo{})
|
||||
}
|
||||
|
||||
// ── compositePoolAttemptContext ──────────────────────────────────────────────
|
||||
|
||||
func TestCompositePoolAttemptContextIsolatesPlatform(t *testing.T) {
|
||||
base := service.WithCompositeCandidatePlatforms(context.Background(), []string{"deepseek", "openai"})
|
||||
|
||||
attemptCtx := compositePoolAttemptContext(base, &service.Account{Platform: "deepseek"})
|
||||
|
||||
// attempt ctx 携带选中平台,base 候选池保持 immutable 且不携带 resolved。
|
||||
platform, ok := service.ResolvedTargetPlatformFromContext(attemptCtx)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "deepseek", platform)
|
||||
require.Equal(t, []string{"deepseek", "openai"}, service.CompositeCandidatePlatformsFromContext(attemptCtx))
|
||||
|
||||
_, resolved := service.ResolvedTargetPlatformFromContext(base)
|
||||
require.False(t, resolved, "original request ctx must stay pool-shaped (no resolved target)")
|
||||
require.Equal(t, []string{"deepseek", "openai"}, service.CompositeCandidatePlatformsFromContext(base))
|
||||
}
|
||||
|
||||
func TestCompositePoolAttemptContextGuards(t *testing.T) {
|
||||
var nilCtx context.Context
|
||||
require.Nil(t, compositePoolAttemptContext(nilCtx, &service.Account{Platform: "openai"}))
|
||||
|
||||
base := context.Background()
|
||||
require.Equal(t, base, compositePoolAttemptContext(base, nil))
|
||||
require.Equal(t, base, compositePoolAttemptContext(base, &service.Account{Platform: ""}))
|
||||
|
||||
alreadyResolved := service.WithResolvedTargetPlatform(base, "grok")
|
||||
require.Equal(t, alreadyResolved, compositePoolAttemptContext(alreadyResolved, &service.Account{Platform: "openai"}),
|
||||
"resolved single-target requests must not be overridden by pool attempt semantics")
|
||||
}
|
||||
|
||||
// ── compositePoolPlatformDenials / compositePoolSelectionRetryContext ────────
|
||||
|
||||
func TestCompositePoolPlatformDenialsMaskWholePlatform(t *testing.T) {
|
||||
denials := newCompositePoolPlatformDenials()
|
||||
denials.deny("openai")
|
||||
denials.deny("openai") // 幂等
|
||||
|
||||
remaining := denials.filterCandidates([]string{"deepseek", "grok", "openai"})
|
||||
require.Equal(t, []string{"deepseek", "grok"}, remaining)
|
||||
require.Len(t, denials.filterCandidates([]string{"deepseek", "openai"}), 1)
|
||||
}
|
||||
|
||||
func TestCompositePoolSelectionRetryContextMasksCandidates(t *testing.T) {
|
||||
base := service.WithCompositeCandidatePlatforms(context.Background(), []string{"deepseek", "openai"})
|
||||
denials := newCompositePoolPlatformDenials()
|
||||
|
||||
// 无 deny:原样返回 base(候选池不变)。
|
||||
retryCtx, ok := compositePoolSelectionRetryContext(base, denials)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, base, retryCtx)
|
||||
|
||||
denials.deny("openai")
|
||||
retryCtx, ok = compositePoolSelectionRetryContext(base, denials)
|
||||
require.True(t, ok)
|
||||
// 候选池保持 immutable(不收缩),仅叠加请求局部 deniedPlatforms 列表。
|
||||
require.Equal(t, []string{"deepseek", "openai"}, service.CompositeCandidatePlatformsFromContext(retryCtx))
|
||||
require.Equal(t, []string{"openai"}, service.CompositePoolDeniedPlatformsFromContext(retryCtx))
|
||||
require.Equal(t, []string{"deepseek", "openai"}, service.CompositeCandidatePlatformsFromContext(base),
|
||||
"original request ctx candidates must stay immutable")
|
||||
require.Nil(t, service.CompositePoolDeniedPlatformsFromContext(base),
|
||||
"base request ctx must not carry the denied overlay")
|
||||
_, resolved := service.ResolvedTargetPlatformFromContext(retryCtx)
|
||||
require.False(t, resolved, "retry ctx must not collapse into the last attempted account's platform")
|
||||
|
||||
denials.deny("deepseek")
|
||||
_, ok = compositePoolSelectionRetryContext(base, denials)
|
||||
require.False(t, ok, "all candidates business-limited → terminate instead of re-selecting")
|
||||
}
|
||||
|
||||
// ── respondCompositePoolAttemptPolicyFailure ─────────────────────────────────
|
||||
|
||||
func TestRespondCompositePoolAttemptPolicyFailure_QuotaMapsToBillingErrorDetails(t *testing.T) {
|
||||
var gotStatus int
|
||||
var gotCode string
|
||||
write := func(c *gin.Context, status int, code, message string) {
|
||||
gotStatus = status
|
||||
gotCode = code
|
||||
}
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
|
||||
respondCompositePoolAttemptPolicyFailure(c, compositePoolAttemptPolicyFailure{
|
||||
QuotaErr: service.ErrUserPlatformDailyQuotaExhausted,
|
||||
}, write)
|
||||
|
||||
require.Equal(t, http.StatusTooManyRequests, gotStatus)
|
||||
require.Equal(t, "rate_limit_exceeded", gotCode)
|
||||
require.NotEmpty(t, c.Writer.Header().Get("Retry-After"), "quota denial must keep the Retry-After semantics of billingErrorDetails")
|
||||
}
|
||||
|
||||
func TestRespondCompositePoolAttemptPolicyFailure_ChannelRestrictionStays503(t *testing.T) {
|
||||
var gotStatus int
|
||||
var gotErrType string
|
||||
write := func(c *gin.Context, status int, code, message string) {
|
||||
gotStatus = status
|
||||
gotErrType = code
|
||||
}
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
|
||||
respondCompositePoolAttemptPolicyFailure(c, compositePoolAttemptPolicyFailure{ChannelRestricted: true}, write)
|
||||
|
||||
require.Equal(t, http.StatusServiceUnavailable, gotStatus,
|
||||
"channel restriction must keep the selection-stage channel-restriction classification")
|
||||
require.Equal(t, "api_error", gotErrType)
|
||||
require.Empty(t, c.Writer.Header().Get("Retry-After"))
|
||||
}
|
||||
|
||||
func TestRespondCompositePoolAttemptPolicyFailure_NotDeniedDoesNotWrite(t *testing.T) {
|
||||
called := false
|
||||
write := func(c *gin.Context, status int, code, message string) { called = true }
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
|
||||
respondCompositePoolAttemptPolicyFailure(c, compositePoolAttemptPolicyFailure{}, write)
|
||||
require.False(t, called)
|
||||
}
|
||||
|
||||
// ── compositePoolAttemptPolicyApplies ────────────────────────────────────────
|
||||
|
||||
func poolAttemptGinContext(base context.Context) *gin.Context {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil).WithContext(base)
|
||||
return c
|
||||
}
|
||||
|
||||
func TestCompositePoolAttemptPolicyAppliesOnlyToActivePools(t *testing.T) {
|
||||
compositeKey := &service.APIKey{Group: &service.Group{ID: 1, Platform: service.PlatformComposite}}
|
||||
|
||||
pool := poolAttemptGinContext(service.WithCompositeCandidatePlatforms(context.Background(), []string{"openai"}))
|
||||
require.True(t, compositePoolAttemptPolicyApplies(pool, compositeKey))
|
||||
|
||||
// 显式 resolved 单目标(pin/detector)与普通分组保持旧行为。
|
||||
resolved := poolAttemptGinContext(service.WithCompositeCandidatePlatforms(
|
||||
service.WithResolvedTargetPlatform(context.Background(), "openai"), []string{"openai"}))
|
||||
require.False(t, compositePoolAttemptPolicyApplies(resolved, compositeKey))
|
||||
|
||||
plain := poolAttemptGinContext(context.Background())
|
||||
require.False(t, compositePoolAttemptPolicyApplies(plain, compositeKey))
|
||||
|
||||
openAIKey := &service.APIKey{Group: &service.Group{ID: 2, Platform: service.PlatformOpenAI}}
|
||||
require.False(t, compositePoolAttemptPolicyApplies(pool, openAIKey))
|
||||
}
|
||||
|
||||
// ── evaluateCompositePoolAttemptPolicy ───────────────────────────────────────
|
||||
|
||||
func TestEvaluateCompositePoolAttemptPolicy_QuotaDeniedBlocksBeforeForward(t *testing.T) {
|
||||
zero := 0.0
|
||||
now := time.Now().UTC()
|
||||
billing := newPoolAttemptBilling(t, &service.UserPlatformQuotaCacheEntry{
|
||||
DailyUsageUSD: 0,
|
||||
DailyLimitUSD: &zero,
|
||||
DailyWindowStart: &now,
|
||||
SchemaVersion: service.UserPlatformQuotaCacheSchemaV1,
|
||||
})
|
||||
base := service.WithCompositeCandidatePlatforms(context.Background(), []string{"openai", "deepseek"})
|
||||
apiKey := &service.APIKey{GroupID: &[]int64{1}[0], Group: &service.Group{ID: 1, Platform: service.PlatformComposite}, User: &service.User{ID: 42}}
|
||||
|
||||
attempt := evaluateCompositePoolAttemptPolicy(
|
||||
base, billing, nil, apiKey, nil, &service.Account{Platform: "openai"}, "gpt-4", false)
|
||||
|
||||
require.ErrorIs(t, attempt.Failure.QuotaErr, service.ErrUserPlatformDailyQuotaExhausted)
|
||||
require.True(t, attempt.Failure.denied())
|
||||
_, resolved := service.ResolvedTargetPlatformFromContext(attempt.AttemptCtx)
|
||||
require.True(t, resolved)
|
||||
_, baseResolved := service.ResolvedTargetPlatformFromContext(base)
|
||||
require.False(t, baseResolved, "base request ctx must stay untouched")
|
||||
}
|
||||
|
||||
func TestEvaluateCompositePoolAttemptPolicy_ChannelRestrictionDeniesSelectedPlatform(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
billing := newPoolAttemptBilling(t, &service.UserPlatformQuotaCacheEntry{
|
||||
DailyWindowStart: &now,
|
||||
SchemaVersion: service.UserPlatformQuotaCacheSchemaV1, // limits 全 nil → 配额放行
|
||||
})
|
||||
channelSvc := service.NewChannelService(&poolAttemptFakeChannelRepo{
|
||||
channels: []service.Channel{{
|
||||
ID: 1,
|
||||
Status: service.StatusActive,
|
||||
GroupIDs: []int64{4311},
|
||||
RestrictModels: true,
|
||||
BillingModelSource: service.BillingModelSourceRequested,
|
||||
ModelPricing: []service.ChannelModelPricing{
|
||||
{Platform: service.PlatformOpenAI, Models: []string{"gpt-*"}},
|
||||
},
|
||||
}},
|
||||
platforms: map[int64]string{4311: service.PlatformComposite},
|
||||
}, nil, nil, nil, nil)
|
||||
gateway := service.NewOpenAIGatewayService(
|
||||
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
nil, nil, nil, nil, nil, channelSvc, nil, nil, nil,
|
||||
)
|
||||
groupID := int64(4311)
|
||||
apiKey := &service.APIKey{GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: service.PlatformComposite}}
|
||||
base := service.WithCompositeCandidatePlatforms(context.Background(), []string{"openai", "deepseek"})
|
||||
|
||||
// openai 账号 + openai 作用域内的模型 → 放行且映射直通。
|
||||
allowed := evaluateCompositePoolAttemptPolicy(
|
||||
base, billing, gateway, apiKey, nil, &service.Account{Platform: service.PlatformOpenAI}, "gpt-4", false)
|
||||
require.False(t, allowed.Failure.denied())
|
||||
|
||||
// deepseek 账号:gpt-4 不在 deepseek 作用域定价内 → 渠道限制拒绝该平台,
|
||||
// 且不能把 openai 行跨平台扫进来误放行。
|
||||
denied := evaluateCompositePoolAttemptPolicy(
|
||||
base, billing, gateway, apiKey, nil, &service.Account{Platform: service.PlatformDeepseek}, "gpt-4", false)
|
||||
require.NoError(t, denied.Failure.QuotaErr)
|
||||
require.True(t, denied.Failure.ChannelRestricted)
|
||||
require.False(t, denied.Mapping.Mapped,
|
||||
"channel mapping must be scoped to the selected platform, not resolved across pool platforms")
|
||||
}
|
||||
|
||||
// TestCompositePoolAttemptChannelPolicyIsPureAndLazy 复核渠道策略 helper 的纯度:
|
||||
// 只做纯读 + lazy cache 加载——重复评估结论稳定;cache 只在首次查询时从仓储构建
|
||||
// 一次,后续评估走进程内快照,不产生仓储重复读、不写任何状态(无计数、无扣费
|
||||
// 入口可触达)。
|
||||
func TestCompositePoolAttemptChannelPolicyIsPureAndLazy(t *testing.T) {
|
||||
repo := &poolAttemptFakeChannelRepo{
|
||||
channels: []service.Channel{{
|
||||
ID: 1,
|
||||
Status: service.StatusActive,
|
||||
GroupIDs: []int64{4312},
|
||||
RestrictModels: true,
|
||||
BillingModelSource: service.BillingModelSourceRequested,
|
||||
ModelPricing: []service.ChannelModelPricing{
|
||||
{Platform: service.PlatformOpenAI, Models: []string{"gpt-*"}},
|
||||
},
|
||||
}},
|
||||
platforms: map[int64]string{4312: service.PlatformComposite},
|
||||
}
|
||||
channelSvc := service.NewChannelService(repo, nil, nil, nil, nil)
|
||||
gateway := service.NewOpenAIGatewayService(
|
||||
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
nil, nil, nil, nil, nil, channelSvc, nil, nil, nil,
|
||||
)
|
||||
groupID := int64(4312)
|
||||
attemptCtx := service.WithResolvedTargetPlatform(context.Background(), service.PlatformDeepseek)
|
||||
account := &service.Account{Platform: service.PlatformDeepseek}
|
||||
|
||||
first := gateway.CompositePoolAttemptChannelRestricted(attemptCtx, &groupID, account, "gpt-4", false)
|
||||
second := gateway.CompositePoolAttemptChannelRestricted(attemptCtx, &groupID, account, "gpt-4", false)
|
||||
mapping := gateway.CompositePoolAttemptChannelMapping(attemptCtx, &groupID, "gpt-4")
|
||||
|
||||
require.True(t, first)
|
||||
require.True(t, second, "repeated evaluation must be stable (pure read, no state change)")
|
||||
require.False(t, mapping.Mapped)
|
||||
require.LessOrEqual(t, repo.listAllCnt, 1,
|
||||
"channel cache must be built lazily once; repeat checks must read the in-process snapshot")
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
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"
|
||||
)
|
||||
|
||||
type multiGroupStubRepo struct {
|
||||
fakeGroupRepo
|
||||
byID map[int64]*service.Group
|
||||
}
|
||||
|
||||
func (r *multiGroupStubRepo) GetByID(_ context.Context, id int64) (*service.Group, error) {
|
||||
if g, ok := r.byID[id]; ok {
|
||||
return g, nil
|
||||
}
|
||||
return nil, service.ErrGroupNotFound
|
||||
}
|
||||
|
||||
func (r *multiGroupStubRepo) GetByIDLite(ctx context.Context, id int64) (*service.Group, error) {
|
||||
return r.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// C3 正向:anthropic 分组开启 ClaudeCodeOnly 并降级到 composite 池分组时,选中 OpenAI
|
||||
// 账号必须经 OpenAI 兼容链转发,绝不能误入 GatewayService.Forward 把 API Key 发往 api.anthropic.com。
|
||||
func TestClaudeCodeOnlyFallback_AnthropicToCompositePoolDelegatesOpenAIWithoutLeak(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
primaryID := int64(5101)
|
||||
fallbackID := int64(5102)
|
||||
primaryGroup := &service.Group{
|
||||
ID: primaryID,
|
||||
Name: "ant-cc-only",
|
||||
Platform: service.PlatformAnthropic,
|
||||
Status: service.StatusActive,
|
||||
Hydrated: true,
|
||||
ClaudeCodeOnly: true,
|
||||
FallbackGroupID: &fallbackID,
|
||||
AllowMessagesDispatch: true,
|
||||
}
|
||||
fallbackGroup := &service.Group{
|
||||
ID: fallbackID,
|
||||
Name: "comp-fallback-pool",
|
||||
Platform: service.PlatformComposite,
|
||||
Status: service.StatusActive,
|
||||
Hydrated: true,
|
||||
AllowMessagesDispatch: true,
|
||||
}
|
||||
|
||||
openAIAcc := &service.Account{
|
||||
ID: 8101,
|
||||
Name: "oa-pool-member",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 1,
|
||||
GroupIDs: []int64{fallbackID},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-openai-secret-never-send-to-anthropic",
|
||||
"base_url": "https://openai-mock.example/v1",
|
||||
"model_mapping": map[string]any{"shared-model": "gpt-5.4"},
|
||||
},
|
||||
Extra: map[string]any{
|
||||
"openai_responses_mode": "force_chat_completions",
|
||||
"openai_responses_supported": false,
|
||||
},
|
||||
}
|
||||
antAcc := &service.Account{
|
||||
ID: 8102,
|
||||
Name: "ant-pool-member",
|
||||
Platform: service.PlatformAnthropic,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 10,
|
||||
GroupIDs: []int64{fallbackID},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-ant",
|
||||
"base_url": "https://anthropic-mock.example",
|
||||
"model_mapping": map[string]any{"shared-model": "claude-sonnet-4-5"},
|
||||
},
|
||||
}
|
||||
accounts := []*service.Account{openAIAcc, antAcc}
|
||||
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
cfg.Security = config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}
|
||||
|
||||
openAIUpstream := &compositePoolFakeUpstream{
|
||||
respond: func(_ compositePoolUpstreamCall, _ int) *http.Response {
|
||||
return chatCompletionsOKResponse("gpt-5.4", 10, 5)
|
||||
},
|
||||
}
|
||||
gwUpstream := &compositePoolFakeUpstream{}
|
||||
groupRepo := &multiGroupStubRepo{byID: map[int64]*service.Group{
|
||||
primaryID: primaryGroup,
|
||||
fallbackID: fallbackGroup,
|
||||
}}
|
||||
schedCache := &platformScopedSchedulerCache{fakeSchedulerCache{accounts: accounts}}
|
||||
snap := service.NewSchedulerSnapshotService(schedCache, nil, nil, nil, nil)
|
||||
bs := service.NewBillingService(cfg, nil)
|
||||
usageRepo := &compositePoolUsageLogRepo{}
|
||||
|
||||
compositeResolver := service.NewCompositeRouteResolver(nil)
|
||||
gwSvc := service.NewGatewayService(
|
||||
nil, groupRepo, usageRepo, nil, nil, nil, nil, nil, cfg, snap, nil, bs, nil, nil, nil,
|
||||
gwUpstream, nil, nil, nil, nil, nil, nil, nil, nil, nil, compositeResolver, nil, nil,
|
||||
)
|
||||
compositeResolver.SetModelOwnershipResolver(func(context.Context, int64, string) (service.CompositeModelOwnership, error) {
|
||||
return service.CompositeModelOwnership{
|
||||
Matched: true,
|
||||
CandidatePlatforms: []string{service.PlatformAnthropic, service.PlatformOpenAI},
|
||||
RequiredClaimStrength: service.CompositeClaimExplicit,
|
||||
}, nil
|
||||
})
|
||||
oaSvc := service.NewOpenAIGatewayService(
|
||||
nil, usageRepo, nil, nil, nil, nil, nil, cfg, nil, nil, bs, nil, nil,
|
||||
openAIUpstream, service.NewDeferredService(nil, nil, 0), nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCache.Stop)
|
||||
|
||||
h := &GatewayHandler{
|
||||
gatewayService: gwSvc,
|
||||
openAIGatewayService: oaSvc,
|
||||
billingCacheService: billingCache,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
|
||||
maxAccountSwitches: 3,
|
||||
cfg: cfg,
|
||||
openAIHandler: &OpenAIGatewayHandler{gatewayService: oaSvc},
|
||||
}
|
||||
|
||||
body := `{"model":"shared-model","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}`
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Request.Header.Set("User-Agent", "curl/8.0") // 非 Claude Code 客户端,触发 FallbackGroupID
|
||||
apiKey := &service.APIKey{
|
||||
ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup,
|
||||
User: &service.User{ID: 1, Concurrency: 5},
|
||||
}
|
||||
ctx := context.WithValue(c.Request.Context(), ctxkey.Group, primaryGroup)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 1, Concurrency: 5})
|
||||
|
||||
h.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
require.Empty(t, gwUpstream.snapshot(), "OpenAI APIKey must NEVER enter generic Anthropic HTTP upstream")
|
||||
require.Len(t, openAIUpstream.snapshot(), 1, "OpenAI pool account must be delegated to OpenAIGatewayService")
|
||||
}
|
||||
|
||||
// H8:通用池委派 OpenAI 链因组推理强度策略 deny 返回 403 JSON 时,不得在尾部追加 SSE 错误帧。
|
||||
func TestCompositePoolDelegatedReasoningDeny_PureJSONWithoutTrailingSSE(t *testing.T) {
|
||||
openAIAcc := &service.Account{
|
||||
ID: 8201,
|
||||
Name: "oa-deny",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 1,
|
||||
GroupIDs: []int64{41011},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-oa",
|
||||
"base_url": "https://openai-mock.example/v1",
|
||||
"model_mapping": map[string]any{"shared-effort": "gpt-5.4"},
|
||||
},
|
||||
}
|
||||
antAcc := &service.Account{
|
||||
ID: 8202,
|
||||
Name: "ant-peer",
|
||||
Platform: service.PlatformAnthropic,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 10,
|
||||
GroupIDs: []int64{41011},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-ant",
|
||||
"model_mapping": map[string]any{"shared-effort": "claude-sonnet-4-5"},
|
||||
},
|
||||
}
|
||||
harness := newCompositePoolMessagesHarness(t, []*service.Account{openAIAcc, antAcc})
|
||||
harness.group.AllowMessagesDispatch = true
|
||||
harness.group.MaxReasoningEffort = "medium"
|
||||
harness.group.MaxReasoningEffortOverLimit = service.ReasoningEffortOverLimitDeny
|
||||
|
||||
c, rec := harness.newRequest(t, "/v1/messages",
|
||||
`{"model":"shared-effort","max_tokens":64,"output_config":{"effort":"max"},"messages":[{"role":"user","content":"hi"}]}`,
|
||||
service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
harness.handler.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
|
||||
require.NotContains(t, rec.Body.String(), "event: error", "403 JSON body must not be corrupted with trailing SSE frames")
|
||||
var parsed map[string]any
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &parsed),
|
||||
"response body must remain valid single JSON document: %s", rec.Body.String())
|
||||
}
|
||||
|
||||
// C3 反向:composite 池分组开启 ClaudeCodeOnly(且未开启 AllowMessagesDispatch 或受原组策略限制)
|
||||
// 降级到普通 anthropic 分组时,不得套用原分组的池策略把降级分组账号逐个踢进 502。
|
||||
func TestClaudeCodeOnlyFallback_CompositePoolToAnthropicServesFallbackGroup(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
primaryID := int64(5201)
|
||||
fallbackID := int64(5202)
|
||||
primaryGroup := &service.Group{
|
||||
ID: primaryID,
|
||||
Name: "comp-cc-only",
|
||||
Platform: service.PlatformComposite,
|
||||
Status: service.StatusActive,
|
||||
Hydrated: true,
|
||||
ClaudeCodeOnly: true,
|
||||
FallbackGroupID: &fallbackID,
|
||||
}
|
||||
fallbackGroup := &service.Group{
|
||||
ID: fallbackID,
|
||||
Name: "ant-fallback",
|
||||
Platform: service.PlatformAnthropic,
|
||||
Status: service.StatusActive,
|
||||
Hydrated: true,
|
||||
}
|
||||
antAcc := &service.Account{
|
||||
ID: 8301,
|
||||
Name: "ant-fallback-acc",
|
||||
Platform: service.PlatformAnthropic,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 1,
|
||||
GroupIDs: []int64{fallbackID},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-ant-fallback",
|
||||
"base_url": "https://anthropic-fallback.example",
|
||||
},
|
||||
}
|
||||
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
cfg.Security = config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}
|
||||
gwUpstream := &compositePoolFakeUpstream{
|
||||
respond: func(_ compositePoolUpstreamCall, _ int) *http.Response {
|
||||
return anthropicMessagesOKResponse()
|
||||
},
|
||||
}
|
||||
groupRepo := &multiGroupStubRepo{byID: map[int64]*service.Group{
|
||||
primaryID: primaryGroup,
|
||||
fallbackID: fallbackGroup,
|
||||
}}
|
||||
schedCache := &platformScopedSchedulerCache{fakeSchedulerCache{accounts: []*service.Account{antAcc}}}
|
||||
snap := service.NewSchedulerSnapshotService(schedCache, nil, nil, nil, nil)
|
||||
bs := service.NewBillingService(cfg, nil)
|
||||
usageRepo := &compositePoolUsageLogRepo{}
|
||||
gwSvc := service.NewGatewayService(
|
||||
nil, groupRepo, usageRepo, nil, nil, nil, nil, nil, cfg, snap, nil, bs, nil, nil, nil,
|
||||
gwUpstream, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
oaSvc := service.NewOpenAIGatewayService(
|
||||
nil, usageRepo, nil, nil, nil, nil, nil, cfg, nil, nil, bs, nil, nil,
|
||||
&compositePoolFakeUpstream{}, service.NewDeferredService(nil, nil, 0), nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCache.Stop)
|
||||
|
||||
h := &GatewayHandler{
|
||||
gatewayService: gwSvc,
|
||||
openAIGatewayService: oaSvc,
|
||||
billingCacheService: billingCache,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
|
||||
maxAccountSwitches: 3,
|
||||
cfg: cfg,
|
||||
openAIHandler: &OpenAIGatewayHandler{gatewayService: oaSvc},
|
||||
}
|
||||
|
||||
body := `{"model":"claude-sonnet-4-5","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}`
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Request.Header.Set("User-Agent", "curl/8.0")
|
||||
ctx := service.WithCompositeRouteDecision(c.Request.Context(), service.CompositeRouteDecision{
|
||||
Matched: true,
|
||||
Source: service.CompositeRouteSourceAccountPool,
|
||||
GroupID: primaryID,
|
||||
PublicModel: "claude-sonnet-4-5",
|
||||
CandidatePlatforms: []string{service.PlatformDeepseek, service.PlatformOpenAI},
|
||||
RequiredClaimStrength: service.CompositeClaimExplicit,
|
||||
})
|
||||
ctx = context.WithValue(ctx, ctxkey.Group, primaryGroup)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
apiKey := &service.APIKey{
|
||||
ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup,
|
||||
User: &service.User{ID: 1, Concurrency: 5},
|
||||
}
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 1, Concurrency: 5})
|
||||
|
||||
h.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
require.Len(t, gwUpstream.snapshot(), 1)
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
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"
|
||||
)
|
||||
|
||||
func buildClaudeCodeFallbackCompositeHandler(
|
||||
t *testing.T,
|
||||
allowMessagesDispatch bool,
|
||||
ownership service.CompositeModelOwnership,
|
||||
accounts []*service.Account,
|
||||
) (*GatewayHandler, *service.Group, *compositePoolFakeUpstream, *compositePoolFakeUpstream) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
primaryID := int64(7101)
|
||||
fallbackID := int64(7102)
|
||||
primaryGroup := &service.Group{
|
||||
ID: primaryID,
|
||||
Name: "ant-cc-only",
|
||||
Platform: service.PlatformAnthropic,
|
||||
Status: service.StatusActive,
|
||||
Hydrated: true,
|
||||
ClaudeCodeOnly: true,
|
||||
FallbackGroupID: &fallbackID,
|
||||
AllowMessagesDispatch: true,
|
||||
}
|
||||
fallbackGroup := &service.Group{
|
||||
ID: fallbackID,
|
||||
Name: "comp-fallback",
|
||||
Platform: service.PlatformComposite,
|
||||
Status: service.StatusActive,
|
||||
Hydrated: true,
|
||||
AllowMessagesDispatch: allowMessagesDispatch,
|
||||
}
|
||||
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
cfg.Security = config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}}
|
||||
|
||||
openAIUpstream := &compositePoolFakeUpstream{
|
||||
respond: func(_ compositePoolUpstreamCall, _ int) *http.Response {
|
||||
return chatCompletionsOKResponse("gpt-5.4", 10, 5)
|
||||
},
|
||||
}
|
||||
gwUpstream := &compositePoolFakeUpstream{}
|
||||
groupRepo := &multiGroupStubRepo{byID: map[int64]*service.Group{
|
||||
primaryID: primaryGroup,
|
||||
fallbackID: fallbackGroup,
|
||||
}}
|
||||
schedCache := &platformScopedSchedulerCache{fakeSchedulerCache{accounts: accounts}}
|
||||
snap := service.NewSchedulerSnapshotService(schedCache, nil, nil, nil, nil)
|
||||
bs := service.NewBillingService(cfg, nil)
|
||||
usageRepo := &compositePoolUsageLogRepo{}
|
||||
|
||||
compositeResolver := service.NewCompositeRouteResolver(nil)
|
||||
gwSvc := service.NewGatewayService(
|
||||
nil, groupRepo, usageRepo, nil, nil, nil, nil, nil, cfg, snap, nil, bs, nil, nil, nil,
|
||||
gwUpstream, nil, nil, nil, nil, nil, nil, nil, nil, nil, compositeResolver, nil, nil,
|
||||
)
|
||||
compositeResolver.SetModelOwnershipResolver(func(context.Context, int64, string) (service.CompositeModelOwnership, error) {
|
||||
return ownership, nil
|
||||
})
|
||||
oaSvc := service.NewOpenAIGatewayService(
|
||||
nil, usageRepo, nil, nil, nil, nil, nil, cfg, nil, nil, bs, nil, nil,
|
||||
openAIUpstream, service.NewDeferredService(nil, nil, 0), nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCache.Stop)
|
||||
|
||||
h := &GatewayHandler{
|
||||
gatewayService: gwSvc,
|
||||
openAIGatewayService: oaSvc,
|
||||
billingCacheService: billingCache,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
|
||||
maxAccountSwitches: 3,
|
||||
cfg: cfg,
|
||||
openAIHandler: &OpenAIGatewayHandler{gatewayService: oaSvc},
|
||||
}
|
||||
return h, primaryGroup, openAIUpstream, gwUpstream
|
||||
}
|
||||
|
||||
// P0 回归:ClaudeCodeOnly 分组降级到 composite 分组时,携带 previous_response_id 的
|
||||
// /v1/responses 请求绝不能绕过租户归属校验被委派给共享 OpenAI 账号。
|
||||
func TestClaudeCodeOnlyFallback_ResponsesRejectsPreviousResponseID(t *testing.T) {
|
||||
openAIAcc := &service.Account{
|
||||
ID: 7201,
|
||||
Name: "oa-shared",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 1,
|
||||
GroupIDs: []int64{7102},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-oa-shared",
|
||||
"base_url": "https://openai-mock.example/v1",
|
||||
"model_mapping": map[string]any{"gpt-5.4": "gpt-5.4"},
|
||||
},
|
||||
}
|
||||
h, primaryGroup, openAIUpstream, gwUpstream := buildClaudeCodeFallbackCompositeHandler(
|
||||
t,
|
||||
true,
|
||||
service.CompositeModelOwnership{
|
||||
Matched: true,
|
||||
TargetPlatform: service.PlatformOpenAI,
|
||||
RequiredClaimStrength: service.CompositeClaimExplicit,
|
||||
},
|
||||
[]*service.Account{openAIAcc},
|
||||
)
|
||||
|
||||
body := `{"model":"gpt-5.4","previous_response_id":"resp_victim_123","input":"steal state"}`
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Request.Header.Set("User-Agent", "curl/8.0")
|
||||
primaryID := primaryGroup.ID
|
||||
apiKey := &service.APIKey{ID: 2, UserID: 2, GroupID: &primaryID, Group: primaryGroup, User: &service.User{ID: 2, Concurrency: 5}}
|
||||
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, primaryGroup))
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 2, Concurrency: 5})
|
||||
|
||||
h.Responses(c)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
require.Contains(t, rec.Body.String(), "previous_response_id")
|
||||
require.Empty(t, openAIUpstream.snapshot(), "must not delegate unverified previous_response_id to shared OpenAI account")
|
||||
require.Empty(t, gwUpstream.snapshot())
|
||||
}
|
||||
|
||||
// 回归:ClaudeCodeOnly 分组降级到 AllowMessagesDispatch=false 的 composite 组(单目标与账号池)
|
||||
// 选中 openai 账号时均返回 403 permission_error,不得绕过或误报 503。
|
||||
func TestClaudeCodeOnlyFallback_MessagesAllowMessagesDispatchForbidden(t *testing.T) {
|
||||
openAIAcc := &service.Account{
|
||||
ID: 7301,
|
||||
Name: "oa-single",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 1,
|
||||
GroupIDs: []int64{7102},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-oa",
|
||||
"base_url": "https://openai-mock.example/v1",
|
||||
"model_mapping": map[string]any{"shared-model": "gpt-5.4"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ownership service.CompositeModelOwnership
|
||||
}{
|
||||
{
|
||||
name: "single_target_openai",
|
||||
ownership: service.CompositeModelOwnership{
|
||||
Matched: true,
|
||||
TargetPlatform: service.PlatformOpenAI,
|
||||
RequiredClaimStrength: service.CompositeClaimExplicit,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pool_only_openai_schedulable",
|
||||
ownership: service.CompositeModelOwnership{
|
||||
Matched: true,
|
||||
CandidatePlatforms: []string{service.PlatformAnthropic, service.PlatformOpenAI},
|
||||
RequiredClaimStrength: service.CompositeClaimExplicit,
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h, primaryGroup, openAIUpstream, gwUpstream := buildClaudeCodeFallbackCompositeHandler(
|
||||
t, false, tc.ownership, []*service.Account{openAIAcc},
|
||||
)
|
||||
body := `{"model":"shared-model","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}`
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Request.Header.Set("User-Agent", "curl/8.0")
|
||||
primaryID := primaryGroup.ID
|
||||
apiKey := &service.APIKey{ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup, User: &service.User{ID: 1, Concurrency: 5}}
|
||||
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, primaryGroup))
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 1, Concurrency: 5})
|
||||
|
||||
h.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
|
||||
require.Contains(t, rec.Body.String(), "permission_error")
|
||||
require.Empty(t, openAIUpstream.snapshot())
|
||||
require.Empty(t, gwUpstream.snapshot())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 回归:CountTokens 降级选中不可计数的 OpenAI 账号时返回 404,绝不把 OpenAI Key 发往 Anthropic count_tokens。
|
||||
func TestClaudeCodeOnlyFallback_CountTokensRejectsUncountableOpenAIAccount(t *testing.T) {
|
||||
openAIAcc := &service.Account{
|
||||
ID: 7401,
|
||||
Name: "oa-uncountable",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 1,
|
||||
GroupIDs: []int64{7102},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-oa-never-send-to-count-tokens",
|
||||
"base_url": "https://openai-mock.example/v1",
|
||||
"model_mapping": map[string]any{"shared-model": "gpt-5.4"},
|
||||
},
|
||||
}
|
||||
h, primaryGroup, openAIUpstream, gwUpstream := buildClaudeCodeFallbackCompositeHandler(
|
||||
t,
|
||||
true,
|
||||
service.CompositeModelOwnership{
|
||||
Matched: true,
|
||||
TargetPlatform: service.PlatformOpenAI,
|
||||
RequiredClaimStrength: service.CompositeClaimExplicit,
|
||||
},
|
||||
[]*service.Account{openAIAcc},
|
||||
)
|
||||
|
||||
body := `{"model":"shared-model","messages":[{"role":"user","content":"hi"}]}`
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Request.Header.Set("User-Agent", "curl/8.0")
|
||||
primaryID := primaryGroup.ID
|
||||
apiKey := &service.APIKey{ID: 1, UserID: 1, GroupID: &primaryID, Group: primaryGroup, User: &service.User{ID: 1, Concurrency: 5}}
|
||||
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, primaryGroup))
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 1, Concurrency: 5})
|
||||
|
||||
h.CountTokens(c)
|
||||
|
||||
require.Equal(t, http.StatusNotFound, rec.Code, rec.Body.String())
|
||||
require.Empty(t, gwUpstream.snapshot(), "must not forward OpenAI APIKey to Anthropic count_tokens")
|
||||
require.Empty(t, openAIUpstream.snapshot())
|
||||
}
|
||||
|
||||
// 回归:池首轮触发业务策略拒绝(429 平台配额),且次轮无其余可调度平台账号时,
|
||||
// 返回真实的 429 + Retry-After 而非 502。
|
||||
func TestCompositePool_PreservesPolicyFailureInsteadOf502WhenExhausted(t *testing.T) {
|
||||
openAIAcc := &service.Account{
|
||||
ID: 7501,
|
||||
Name: "oa-quota-hit",
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 2,
|
||||
Priority: 1,
|
||||
GroupIDs: []int64{41011},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-oa",
|
||||
"base_url": "https://openai-mock.example/v1",
|
||||
"model_mapping": map[string]any{"shared-model": "gpt-5.4"},
|
||||
},
|
||||
}
|
||||
// Candidate pool has [anthropic, openai], but only openai has a schedulable account.
|
||||
harness := newCompositePoolMessagesHarness(t, []*service.Account{openAIAcc})
|
||||
harness.group.AllowMessagesDispatch = true
|
||||
quotaLimit := 1.0
|
||||
now := time.Now()
|
||||
stdCfg := &config.Config{RunMode: config.RunModeStandard}
|
||||
billingCache := service.NewBillingCacheService(
|
||||
&r7QuotaBillingCache{
|
||||
poolAttemptFakeQuotaCache: poolAttemptFakeQuotaCache{
|
||||
entry: &service.UserPlatformQuotaCacheEntry{
|
||||
SchemaVersion: service.UserPlatformQuotaCacheSchemaV1,
|
||||
DailyLimitUSD: "aLimit,
|
||||
DailyUsageUSD: 2.0,
|
||||
DailyWindowStart: &now,
|
||||
},
|
||||
},
|
||||
},
|
||||
nil, nil, nil, nil, nil, stdCfg, &poolAttemptFakeQuotaRepo{},
|
||||
)
|
||||
t.Cleanup(billingCache.Stop)
|
||||
harness.handler.billingCacheService = billingCache
|
||||
|
||||
c, rec := harness.newRequest(t, "/v1/messages",
|
||||
`{"model":"shared-model","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}`,
|
||||
service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
harness.handler.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusTooManyRequests, rec.Code, rec.Body.String())
|
||||
require.NotEmpty(t, rec.Header().Get("Retry-After"))
|
||||
require.Empty(t, harness.openAIUpstream.snapshot())
|
||||
}
|
||||
|
||||
type r7QuotaBillingCache struct {
|
||||
poolAttemptFakeQuotaCache
|
||||
}
|
||||
|
||||
func (*r7QuotaBillingCache) GetUserBalance(context.Context, int64) (float64, error) {
|
||||
return 100.0, nil
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 跨族池委派 OpenAI 网关链时,上游 cyber_policy 拒绝须与 OpenAI handler 同口径做事后
|
||||
// 记录(会话封禁 / 风控事件 / 出错用量行),且透传的上游错误体不再被 generic 兜底
|
||||
// 追加错误帧。
|
||||
func TestCompositePoolResponsesDelegatedCyberPolicyIsRecorded(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolKimiResponsesAccount(41401, 41011, 0)})
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusBadRequest,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"code":"cyber_policy","message":"flagged","type":"invalid_request_error"}}`)),
|
||||
}
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.Responses(c)
|
||||
|
||||
require.NotNil(t, service.GetOpsCyberPolicy(c), "委派链必须标记 cyber 命中")
|
||||
require.True(t, c.GetBool(cyberPolicyRecordedKey), "generic 池委派路径必须执行 cyber 事后记录")
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
require.Equal(t, 1, strings.Count(rec.Body.String(), "cyber_policy"), "上游错误体原样透传一次,不追加兜底错误")
|
||||
}
|
||||
|
||||
// 委派 OpenAI 网关链的流式 response.failed 已由该链透传给客户端:generic handler 不得
|
||||
// 再追加一个终止错误帧(客户端会收到两个终止事件)。
|
||||
func TestCompositePoolResponsesDelegatedStreamFailureNotDoubleTerminated(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(41402, 41011, 0)})
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
// 先有语义输出再失败:已写出内容后不可 failover,委派链透传 response.failed。
|
||||
sse := `data: {"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"content_index":0,"delta":"partial"}` + "\n\n" +
|
||||
`data: {"type":"response.failed","response":{"id":"resp_pool_failed","object":"response","status":"failed","error":{"code":"server_error","message":"boom"}}}` + "\n\n"
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(sse)),
|
||||
}
|
||||
}
|
||||
|
||||
body := `{"model":"my-model","stream":true,"input":"hello"}`
|
||||
c, rec := h.newRequest(t, "/v1/responses", body, service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
h.handler.Responses(c)
|
||||
|
||||
require.Equal(t, 1, strings.Count(rec.Body.String(), "response.failed"),
|
||||
"response.failed 只能出现一次,body=%s", rec.Body.String())
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// poolGeminiAccount 是没有 base_url 的 Gemini API Key 账号:若误入 Anthropic 协议
|
||||
// 转发链,GetBaseURL 会回落 api.anthropic.com,Google 凭据被发往错误主机。
|
||||
func poolGeminiAccount(id int64, groupID int64, priority int) *service.Account {
|
||||
return &service.Account{
|
||||
ID: id, Name: fmt.Sprintf("gemini-%d", id), Platform: service.PlatformGemini,
|
||||
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": "google-secret-key",
|
||||
"model_mapping": map[string]any{"my-model": "gemini-3.1-pro"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func requireNoAnthropicUpstreamCall(t *testing.T, h *compositePoolMessagesHarness) {
|
||||
t.Helper()
|
||||
require.Empty(t, h.gwUpstream.snapshot(), "Gemini 凭据不得经 Anthropic 协议链发出")
|
||||
require.Empty(t, h.openAIUpstream.snapshot())
|
||||
}
|
||||
|
||||
// /v1/messages 池选中 Gemini 账号:交 Gemini 兼容链,不得走 generic Anthropic Forward。
|
||||
// 夹具未装配 Gemini 兼容服务,请求以错误结束,关键是没有任何 Anthropic 上游请求。
|
||||
func TestCompositePoolMessagesGeminiAccountNeverUsesAnthropicChain(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolGeminiAccount(43101, 41011, 0)})
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages", poolMessagesBody(), service.PlatformAnthropic, service.PlatformGemini)
|
||||
h.handler.Messages(c)
|
||||
|
||||
require.NotEqual(t, http.StatusOK, rec.Code)
|
||||
requireNoAnthropicUpstreamCall(t, h)
|
||||
}
|
||||
|
||||
// /v1/responses 没有 Gemini 转换链:池里只有 Gemini 账号时整平台屏蔽后无号可选,
|
||||
// 请求失败且没有任何上游请求。
|
||||
func TestCompositePoolResponsesNeverSendsGeminiCredentials(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolGeminiAccount(43201, 41011, 0)})
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformGemini)
|
||||
h.handler.Responses(c)
|
||||
|
||||
require.NotEqual(t, http.StatusOK, rec.Code)
|
||||
requireNoAnthropicUpstreamCall(t, h)
|
||||
}
|
||||
|
||||
// 候选平台全部是 Gemini(其余平台已被屏蔽)时明确拒绝,而不是报账号耗尽。
|
||||
func TestCompositePoolResponsesRejectsWhenOnlyGeminiCandidatesRemain(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolGeminiAccount(43251, 41011, 0)})
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformGemini)
|
||||
h.handler.Responses(c)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
require.Contains(t, rec.Body.String(), "/v1/responses")
|
||||
requireNoAnthropicUpstreamCall(t, h)
|
||||
}
|
||||
|
||||
// /v1/responses 池同时有 Gemini 与 Anthropic 账号:屏蔽 Gemini 后改选 Anthropic 账号。
|
||||
func TestCompositePoolResponsesSkipsGeminiAndUsesOtherPlatform(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{
|
||||
poolGeminiAccount(43301, 41011, 0),
|
||||
poolAnthropicAccount(43302, 41011, 1),
|
||||
})
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return anthropicMessagesSSEStreamResponse()
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/responses", poolResponsesBody(), service.PlatformAnthropic, service.PlatformGemini)
|
||||
h.handler.Responses(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
calls := h.gwUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.NotContains(t, calls[0].Authorization, "google-secret-key")
|
||||
selected, ok := c.Get(opsAccountIDKey)
|
||||
require.True(t, ok)
|
||||
require.EqualValues(t, 43302, selected)
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//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"
|
||||
)
|
||||
|
||||
func poolOpenAIAccount(id int64, groupID int64, priority int) *service.Account {
|
||||
return &service.Account{
|
||||
ID: id, Name: fmt.Sprintf("openai-%d", id), Platform: service.PlatformOpenAI,
|
||||
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": "openai-key",
|
||||
"base_url": "https://openai.example",
|
||||
"model_mapping": map[string]any{"my-model": "gpt-5.4"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// openAIResponsesSSEOKResponse 是最小的 Responses 流式成功响应(openai 平台委派链以流式访问上游)。
|
||||
func openAIResponsesSSEOKResponse(model string) *http.Response {
|
||||
body := "data: " + fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_pool_sse","object":"response","status":"completed","model":%q,"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}],"usage":{"input_tokens":5,"output_tokens":3}}}`, model) + "\n\n"
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}
|
||||
}
|
||||
|
||||
// 跨族账号池(generic handler)选中 openai 账号时同样受分组推理强度上限约束,
|
||||
// 与纯 OpenAI 族池 / 单目标 openai 同语义。
|
||||
func TestCompositeCrossFamilyPoolAppliesReasoningEffortCap(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, path, body, effortPath string
|
||||
respond func() *http.Response
|
||||
}{
|
||||
{
|
||||
name: "responses",
|
||||
path: "/v1/responses",
|
||||
body: `{"model":"my-model","stream":false,"input":"hello","reasoning":{"effort":"xhigh"}}`,
|
||||
effortPath: "reasoning.effort",
|
||||
respond: func() *http.Response { return openAIResponsesOKResponse("gpt-5.4", 5, 3) },
|
||||
},
|
||||
{
|
||||
name: "chat_completions",
|
||||
path: "/v1/chat/completions",
|
||||
body: `{"model":"my-model","stream":false,"messages":[{"role":"user","content":"hello"}],"reasoning_effort":"xhigh"}`,
|
||||
effortPath: "reasoning_effort",
|
||||
respond: func() *http.Response { return openAIResponsesSSEOKResponse("gpt-5.4") },
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44101, 41011, 0)})
|
||||
h.group.MaxReasoningEffort = "medium"
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response { return tc.respond() }
|
||||
|
||||
c, rec := h.newRequest(t, tc.path, tc.body, service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
if tc.path == "/v1/responses" {
|
||||
h.handler.Responses(c)
|
||||
} else {
|
||||
h.handler.ChatCompletions(c)
|
||||
}
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
calls := h.openAIUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
effort := gjson.GetBytes(calls[0].Body, "reasoning.effort").String()
|
||||
if effort == "" {
|
||||
effort = gjson.GetBytes(calls[0].Body, "reasoning_effort").String()
|
||||
}
|
||||
require.Equal(t, "medium", effort, "upstream body=%s", calls[0].Body)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Messages 入口:委派 OpenAI 网关链时按分组上限压低 output_config.effort。
|
||||
func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCap(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44201, 41011, 0)})
|
||||
h.group.MaxReasoningEffort = "medium"
|
||||
h.group.AllowMessagesDispatch = true
|
||||
h.openAIUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return openAIResponsesSSEOKResponse("gpt-5.4")
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages",
|
||||
`{"model":"my-model","max_tokens":64,"stream":false,"messages":[{"role":"user","content":"hello"}],"output_config":{"effort":"max"}}`,
|
||||
service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
h.handler.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
calls := h.openAIUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.Equal(t, "medium", gjson.GetBytes(calls[0].Body, "reasoning.effort").String(), "upstream body=%s", calls[0].Body)
|
||||
}
|
||||
|
||||
// 跨族 Messages 池选中 anthropic 账号:准入期有效平台为 composite,组推理强度上限须在
|
||||
// attempt 级补齐,与单目标 anthropic 同语义。
|
||||
func TestCompositeCrossFamilyPoolMessagesAppliesReasoningEffortCapToAnthropic(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolAnthropicAccount(44202, 41011, 0)})
|
||||
h.group.MaxReasoningEffort = "medium"
|
||||
h.gwUpstream.respond = func(compositePoolUpstreamCall, int) *http.Response {
|
||||
return anthropicMessagesOKResponse()
|
||||
}
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/messages",
|
||||
`{"model":"my-model","max_tokens":64,"stream":false,"messages":[{"role":"user","content":"hello"}],"output_config":{"effort":"max"}}`,
|
||||
service.PlatformAnthropic, service.PlatformKimi)
|
||||
h.handler.Messages(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
calls := h.gwUpstream.snapshot()
|
||||
require.Len(t, calls, 1)
|
||||
require.Equal(t, "medium", gjson.GetBytes(calls[0].Body, "output_config.effort").String(), "upstream body=%s", calls[0].Body)
|
||||
}
|
||||
|
||||
// 跨族池在 /v1/responses 与 /v1/chat/completions 选中 anthropic 账号时,同样须补齐
|
||||
// 分组推理强度策略(含 deny 拦截)。
|
||||
func TestCompositeCrossFamilyPoolTextEndpointsApplyReasoningEffortPolicyToAnthropic(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, path, body string
|
||||
}{
|
||||
{
|
||||
name: "responses",
|
||||
path: "/v1/responses",
|
||||
body: `{"model":"my-model","stream":false,"input":"hello","reasoning":{"effort":"high"}}`,
|
||||
},
|
||||
{
|
||||
name: "chat_completions",
|
||||
path: "/v1/chat/completions",
|
||||
body: `{"model":"my-model","stream":false,"messages":[{"role":"user","content":"hello"}],"reasoning_effort":"high"}`,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolAnthropicAccount(44203, 41011, 0)})
|
||||
h.group.MaxReasoningEffort = "low"
|
||||
h.group.MaxReasoningEffortOverLimit = "deny"
|
||||
|
||||
c, rec := h.newRequest(t, tc.path, tc.body, service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
if tc.path == "/v1/responses" {
|
||||
h.handler.Responses(c)
|
||||
} else {
|
||||
h.handler.ChatCompletions(c)
|
||||
}
|
||||
require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
|
||||
require.Empty(t, h.gwUpstream.snapshot())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 跨族池 /v1/responses 在分组禁用生图时,须拦截显式生图工具请求,不得经委派绕过。
|
||||
func TestCompositeCrossFamilyPoolResponsesEnforcesGroupImageGenerationGate(t *testing.T) {
|
||||
h := newCompositePoolMessagesHarness(t, []*service.Account{poolOpenAIAccount(44204, 41011, 0)})
|
||||
h.group.AllowImageGeneration = false
|
||||
|
||||
c, rec := h.newRequest(t, "/v1/responses",
|
||||
`{"model":"my-model","stream":false,"input":"draw a cat","tools":[{"type":"image_generation"}]}`,
|
||||
service.PlatformAnthropic, service.PlatformOpenAI)
|
||||
h.handler.Responses(c)
|
||||
|
||||
require.Equal(t, http.StatusForbidden, rec.Code, rec.Body.String())
|
||||
require.Contains(t, rec.Body.String(), service.ImageGenerationPermissionMessage())
|
||||
require.Empty(t, h.openAIUpstream.snapshot())
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
)
|
||||
|
||||
// ollama_cloud 平台账号无论合格与否都下发 ollama_cloud_usage state:不合格
|
||||
// 时管理端要靠 EligibleReason 解释「为什么没有窗口/余额」。legacy 宿主平台
|
||||
// (openai/kimi 等)无法与普通同平台账号区分,不合格时不挂 state。
|
||||
func TestAccountFromServiceShallow_OllamaCloudUsageAttachment(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ollamaCloud := func() *service.Account {
|
||||
return &service.Account{
|
||||
ID: 1,
|
||||
Platform: service.PlatformOllamaCloud,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"base_url": "https://ollama.example.test", // 反代 → 不合格
|
||||
"api_key": "key-1",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
ineligible := AccountFromServiceShallow(ollamaCloud())
|
||||
require.NotNil(t, ineligible.OllamaCloudUsage)
|
||||
require.False(t, ineligible.OllamaCloudUsage.Eligible)
|
||||
require.Equal(t, "unsupported_base_url", ineligible.OllamaCloudUsage.EligibleReason)
|
||||
|
||||
eligibleAccount := ollamaCloud()
|
||||
eligibleAccount.Credentials["base_url"] = "https://ollama.com"
|
||||
eligible := AccountFromServiceShallow(eligibleAccount)
|
||||
require.NotNil(t, eligible.OllamaCloudUsage)
|
||||
require.True(t, eligible.OllamaCloudUsage.Eligible)
|
||||
|
||||
// legacy 宿主平台不合格账号:不挂 state(普通 openai 账号不受影响)。
|
||||
cnHost := &service.Account{
|
||||
ID: 2,
|
||||
Platform: service.PlatformKimi,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"base_url": "https://api.kimi.com", "api_key": "key-2"},
|
||||
}
|
||||
require.Nil(t, AccountFromServiceShallow(cnHost).OllamaCloudUsage)
|
||||
|
||||
// 完全无关平台(如 gemini):照旧不挂 state。
|
||||
gemini := &service.Account{
|
||||
ID: 3,
|
||||
Platform: service.PlatformGemini,
|
||||
Type: service.AccountTypeOAuth,
|
||||
Credentials: map[string]any{},
|
||||
}
|
||||
require.Nil(t, AccountFromServiceShallow(gemini).OllamaCloudUsage)
|
||||
}
|
||||
@@ -241,7 +241,11 @@ func AccountFromServiceShallow(a *service.Account) *Account {
|
||||
redactedCreds, credsStatus := RedactCredentials(a.Credentials)
|
||||
extra := redactAccountManagedExtra(a.Extra)
|
||||
var ollamaCloudUsage *service.OllamaCloudUsageState
|
||||
if state := service.OllamaCloudUsageStateFromAccount(a); state.Eligible {
|
||||
// platform=ollama_cloud 一律下发 state:不合格账号(反代 base_url、oauth
|
||||
// 类型)也要把 EligibleReason 送到前端用量格做可解释提示。legacy 宿主
|
||||
// 平台(openai/anthropic/国产)无法与普通同平台账号区分,维持仅在
|
||||
// eligible 时下发,避免给正常 CN/OpenAI 账号挂上无意义的 ineligible 状态。
|
||||
if state := service.OllamaCloudUsageStateFromAccount(a); state.Eligible || a.Platform == service.PlatformOllamaCloud {
|
||||
ollamaCloudUsage = state
|
||||
}
|
||||
var openCodeGoUsage *service.OpenCodeGoUsageState
|
||||
|
||||
@@ -327,11 +327,24 @@ func GetInboundEndpoint(c *gin.Context) string {
|
||||
// GetUpstreamEndpoint derives the upstream endpoint from the context
|
||||
// and the account platform. Handlers call this after scheduling an
|
||||
// account, passing account.Platform.
|
||||
//
|
||||
// 优先级:真实出站记录 > 平台运行时端点 > 入站推导兜底。
|
||||
// 显式记录的端点(service.SetOpsUpstreamEndpoint,由实际 forwarder 在发送前
|
||||
// 写入)优先于任何 group/platform 推导——即使 group 平台是 composite;
|
||||
// 仅在没有任何实际出站记录时才回退到 DeriveUpstreamEndpoint,且推导值只是
|
||||
// 兜底,不代表真实出站。
|
||||
func GetUpstreamEndpoint(c *gin.Context, platform string) string {
|
||||
// 实际 forwarder 在发送前写入的端点拥有最高优先级,对所有平台生效
|
||||
// (含 composite 组与 api_protocol adaptive 的真实 path)。
|
||||
if endpoint := service.GetOpsUpstreamEndpoint(c); endpoint != "" {
|
||||
return endpoint
|
||||
}
|
||||
// OpenAI 转发服务维护独立的运行时端点上下文,覆盖普通入站推导。
|
||||
// 这对 force_chat_completions 的错误路径尤为重要:此时可能没有
|
||||
// ForwardResult,不能把入站 /v1/responses 误报成上游端点。
|
||||
if platform == service.PlatformOpenAI || platform == service.PlatformGrok || service.IsMultiProtocolAPIKeyProvider(platform) {
|
||||
// composite 组经 OpenAI handler 转发兼容池账号时同样适用:此时
|
||||
// group 平台是 composite,若不读取该记录会错误回退到入站推导。
|
||||
if platform == service.PlatformOpenAI || platform == service.PlatformGrok || platform == service.PlatformComposite || service.IsMultiProtocolAPIKeyProvider(platform) {
|
||||
if endpoint := service.GetActualOpenAIUpstreamEndpoint(c); endpoint != "" {
|
||||
return endpoint
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// composite 组 inbound=/v1/chat/completions、实际出站 /v1/messages:显式记录的
|
||||
// actual endpoint 必须优先于 group/platform 推导;无记录时 composite 缺
|
||||
// DeriveUpstreamEndpoint case,才回退入站(仅兜底,不代表真实出站)。
|
||||
func TestGetUpstreamEndpointPrefersActualOutboundRecordOverCompositeFallback(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, EndpointChatCompletions, nil)
|
||||
c.Set(ctxKeyInboundEndpoint, EndpointChatCompletions)
|
||||
|
||||
// 无任何实际出站记录:回退入站推导。
|
||||
require.Equal(t, EndpointChatCompletions, GetUpstreamEndpoint(c, service.PlatformComposite))
|
||||
|
||||
// generic forwarder 发送前记录真实出站 /v1/messages 后必须原样返回,
|
||||
// 且不因传入平台不同而被推导值覆盖。
|
||||
service.SetOpsUpstreamEndpoint(c, EndpointMessages)
|
||||
require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, service.PlatformComposite))
|
||||
require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, service.PlatformAnthropic))
|
||||
require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, service.PlatformOpenAI))
|
||||
|
||||
// 实际出站就是 CC 时保持 CC,不得被平台推导改写。
|
||||
service.SetOpsUpstreamEndpoint(c, EndpointChatCompletions)
|
||||
require.Equal(t, EndpointChatCompletions, GetUpstreamEndpoint(c, service.PlatformComposite))
|
||||
}
|
||||
|
||||
// composite 组经 OpenAI handler 转发兼容池账号:actualOpenAI 运行时记录对
|
||||
// composite 平台同样要生效,不能漏读后回退到入站推导。
|
||||
func TestGetUpstreamEndpointCompositeReadsOpenAIRuntimeOverride(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, EndpointChatCompletions, nil)
|
||||
c.Set(ctxKeyInboundEndpoint, EndpointChatCompletions)
|
||||
|
||||
service.SetActualOpenAIUpstreamEndpoint(c, EndpointChatCompletions)
|
||||
require.Equal(t, EndpointChatCompletions, GetUpstreamEndpoint(c, service.PlatformComposite))
|
||||
|
||||
service.SetActualOpenAIUpstreamEndpoint(c, EndpointResponses)
|
||||
require.Equal(t, EndpointResponses, GetUpstreamEndpoint(c, service.PlatformComposite))
|
||||
|
||||
// generic 记录优先级高于 OpenAI 运行时记录(同为最近一次出站尝试时,
|
||||
// generic 记录来自更底层发送点)。
|
||||
service.SetOpsUpstreamEndpoint(c, EndpointMessages)
|
||||
require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, service.PlatformComposite))
|
||||
}
|
||||
|
||||
// 每次账号重选(含 failover 重试)后,上一账号的尝试级元数据不得残留,
|
||||
// 否则失败日志会把旧账号的端点/模型安到新账号头上。
|
||||
func TestSetOpsSelectedAccountResetsAttemptScopedMetadata(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, EndpointMessages, nil)
|
||||
|
||||
service.SetOpsUpstreamEndpoint(c, EndpointMessages)
|
||||
service.SetActualOpenAIUpstreamEndpoint(c, EndpointResponses)
|
||||
service.SetOpsUpstreamModel(c, "gpt-5.2")
|
||||
service.SetOpsUpstreamEndpoint(c, "/v1/v1/messages")
|
||||
|
||||
setOpsSelectedAccount(c, 42, service.PlatformAnthropic)
|
||||
|
||||
require.Empty(t, service.GetOpsUpstreamEndpoint(c))
|
||||
require.Empty(t, service.GetActualOpenAIUpstreamEndpoint(c))
|
||||
require.Empty(t, c.GetString(opsUpstreamModelKey))
|
||||
require.Equal(t, int64(42), c.GetInt64(opsAccountIDKey))
|
||||
}
|
||||
|
||||
// GetUpstreamEndpoint 旧行为保持:无记录时 anthropic 推导 /v1/messages、
|
||||
// antigravity handler 记录优先于推导。
|
||||
func TestGetUpstreamEndpointFallbackBehaviorUnchanged(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, EndpointChatCompletions, nil)
|
||||
c.Set(ctxKeyInboundEndpoint, EndpointChatCompletions)
|
||||
|
||||
require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, service.PlatformAnthropic))
|
||||
|
||||
setActualUpstreamEndpoint(c, EndpointAntigravityGenerateContent)
|
||||
require.Equal(t, EndpointAntigravityGenerateContent, GetUpstreamEndpoint(c, service.PlatformAntigravity))
|
||||
}
|
||||
@@ -60,6 +60,9 @@ type GatewayHandler struct {
|
||||
maxAccountSwitchesGemini int
|
||||
cfg *config.Config
|
||||
settingService *service.SettingService
|
||||
// openAIHandler 供账号池委派 OpenAI 网关链时复用其 cyber 会话封禁与事后记录
|
||||
// (cyber_policy 只在该链标记,见 composite_pool_attempt_policy.go)。
|
||||
openAIHandler *OpenAIGatewayHandler
|
||||
}
|
||||
|
||||
// NewGatewayHandler creates a new GatewayHandler
|
||||
@@ -174,6 +177,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
reqStream := parsedReq.Stream
|
||||
bindRequestedReasoningEffort(c, body, reqModel)
|
||||
ensureCompositeTargetPlatform(c, apiKey, reqModel)
|
||||
// 账号池没有单一目标平台,准入期判不出策略族:绑定分组策略,委派 OpenAI 网关链选中
|
||||
// openai 账号时由 ForwardAsAnthropic 应用(与 OpenAI handler Messages 同语义)。
|
||||
if service.GenericCompositePoolActive(c.Request.Context()) {
|
||||
bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, body)
|
||||
}
|
||||
if policyBody, changed, err := applyAnthropicReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
|
||||
respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse)
|
||||
return
|
||||
@@ -644,6 +652,24 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
}
|
||||
fallbackUsed := false
|
||||
|
||||
// composite 账号池请求状态(B1:generic Messages 循环池化)。池激活判定与
|
||||
// generic 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求
|
||||
// poolDenials 恒为空、attempt 策略不生效,整条路径零变化。
|
||||
isPoolRequest := service.GenericCompositePoolActive(c.Request.Context())
|
||||
if isPoolRequest && h.rejectCompositePoolCyberSessionBlocked(c, apiKey, body, reqModel, cyberBlockFormatAnthropic) {
|
||||
return
|
||||
}
|
||||
poolDenials := newCompositePoolPlatformDenials()
|
||||
if isPoolRequest && !apiKey.Group.AllowMessagesDispatch {
|
||||
// 与 OpenAI handler 的 allowOpenAICompatibleMessagesDispatch 同语义:openai 账号承接
|
||||
// /v1/messages 受分组开关控制(grok / 多协议供应商豁免),关闭时整平台屏蔽 openai。
|
||||
poolDenials.deny(service.PlatformOpenAI)
|
||||
if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok {
|
||||
h.errorResponse(c, http.StatusForbidden, "permission_error", "This group does not allow /v1/messages dispatch")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 单账号分组首次 503 就不设模型限流标记,避免设 29s 限流导致后续请求连续快速失败;
|
||||
// 是否单账号分组在 antigravity 账号遇到 503 或模型限流预检查时才判定。
|
||||
c.Request = c.Request.WithContext(h.gatewayService.WithSingleAntigravityAccountGroupProbe(c.Request.Context(), currentAPIKey.GroupID))
|
||||
@@ -670,7 +696,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
|
||||
for {
|
||||
fs := NewFailoverState(h.maxAccountSwitches, hasBoundSession)
|
||||
var lastPolicyFailure compositePoolAttemptPolicyFailure
|
||||
retryWithFallback := false
|
||||
schedAPIKey := currentAPIKey
|
||||
|
||||
for {
|
||||
attemptParsedReq, err := parsedReq.CloneForBody(body)
|
||||
@@ -686,7 +714,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, schedAPIKey.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))
|
||||
@@ -724,6 +761,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
default: // FailoverExhausted
|
||||
if fs.LastFailoverErr != nil {
|
||||
h.handleFailoverExhausted(c, fs.LastFailoverErr, platform, streamStarted)
|
||||
} else if lastPolicyFailure.denied() {
|
||||
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
|
||||
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
|
||||
}
|
||||
respondCompositePoolAttemptPolicyFailure(c, lastPolicyFailure, streamAwareWrite)
|
||||
} else {
|
||||
h.handleFailoverExhaustedSimple(c, 502, streamStarted)
|
||||
}
|
||||
@@ -734,6 +776,23 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) {
|
||||
return
|
||||
}
|
||||
var switchedGroup bool
|
||||
schedAPIKey, _, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
|
||||
c, currentAPIKey, schedAPIKey, c.Request.Context(), channelMapping, reqModel, isPoolRequest, poolDenials, selection)
|
||||
if switchedGroup && compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) {
|
||||
bindOpenAIReasoningEffortPolicyForMessagesRequest(c, schedAPIKey, body)
|
||||
if !schedAPIKey.Group.AllowMessagesDispatch {
|
||||
if !isPoolRequest && account.Platform == service.PlatformOpenAI {
|
||||
releaseCompositePoolSelection(selection)
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey)
|
||||
h.handleStreamingAwareError(c, http.StatusForbidden, "permission_error", "This group does not allow /v1/messages dispatch", streamStarted)
|
||||
return
|
||||
}
|
||||
if isPoolRequest {
|
||||
poolDenials.deny(service.PlatformOpenAI)
|
||||
}
|
||||
}
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// [DEBUG-STICKY] 打印账号选择结果
|
||||
@@ -746,6 +805,63 @@ 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, schedAPIKey) {
|
||||
attemptPolicy = evaluateCompositePoolAttemptPolicy(
|
||||
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, schedAPIKey, currentSubscription, account, reqModel, false)
|
||||
isPoolAttempt = true
|
||||
if isPoolRequest && !schedAPIKey.Group.AllowMessagesDispatch && account.Platform == service.PlatformOpenAI {
|
||||
attemptPolicy.Failure.MessagesDispatchForbidden = true
|
||||
}
|
||||
if attemptPolicy.Failure.denied() {
|
||||
releaseCompositePoolSelection(selection)
|
||||
// 选号链可能已为该账号注册会话槽:排除前释放,镜像 profit-veto 分支。
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey)
|
||||
if attemptPolicy.Failure.deniesPlatform() {
|
||||
poolDenials.deny(account.Platform)
|
||||
}
|
||||
lastPolicyFailure = attemptPolicy.Failure
|
||||
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
|
||||
}
|
||||
}
|
||||
// 账号池选中 anthropic 账号:按单目标 anthropic 语义补齐分组推理强度策略(放在槽位获取前)。
|
||||
if isPoolRequest {
|
||||
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
|
||||
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
|
||||
}
|
||||
cappedBody, changed, policyErr := applyCompositePoolAnthropicReasoningEffortPolicy(schedAPIKey, account, attemptParsedReq.Body.Bytes())
|
||||
if policyErr != nil {
|
||||
releaseCompositePoolSelection(selection)
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey)
|
||||
respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite)
|
||||
return
|
||||
}
|
||||
if changed {
|
||||
if err := attemptParsedReq.ReplaceBody(cappedBody); err != nil {
|
||||
releaseCompositePoolSelection(selection)
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionKey)
|
||||
streamAwareWrite(c, http.StatusBadRequest, "invalid_request_error", "Failed to apply reasoning effort policy")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 检查请求拦截(预热请求、SUGGESTION MODE等)
|
||||
if account.IsInterceptWarmupEnabled() {
|
||||
interceptType := detectInterceptType(body, reqModel, parsedReq.MaxTokens, isClaudeCodeClient)
|
||||
@@ -900,9 +1016,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
|
||||
}
|
||||
@@ -917,6 +1039,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
// 转发请求 - 根据账号平台分流
|
||||
c.Set("parsed_request", attemptParsedReq)
|
||||
var result *service.ForwardResult
|
||||
// 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。
|
||||
var delegatedResult *service.OpenAIForwardResult
|
||||
delegated := false
|
||||
requestCtx := c.Request.Context()
|
||||
if fs.SwitchCount > 0 {
|
||||
requestCtx = service.WithAccountSwitchCount(requestCtx, fs.SwitchCount, h.metadataBridgeEnabled())
|
||||
@@ -924,7 +1049,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
if fs.ForceCacheBilling {
|
||||
requestCtx = service.WithForceCacheBilling(requestCtx)
|
||||
}
|
||||
if channelMapping.Mapped {
|
||||
// 池请求的 attempt 局部 ctx 携带选中平台(不写回 c.Request):forward 内的
|
||||
// 渠道定价作用域与计费 QuotaPlatform 跟随实际平台,对齐 OpenAI 池 attempt 语义。
|
||||
if isPoolRequest {
|
||||
requestCtx = compositePoolAttemptContext(requestCtx, account)
|
||||
}
|
||||
if attemptChannelMapping.Mapped {
|
||||
// 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。
|
||||
requestCtx = service.WithGatewaySchedulingModel(requestCtx, reqModel)
|
||||
}
|
||||
@@ -933,10 +1063,32 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
if selection.ProfitGateActive() {
|
||||
attemptedAccountIDs = append(attemptedAccountIDs, account.ID)
|
||||
}
|
||||
canCrossFamilyDispatch := compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey)
|
||||
// 记录 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 canCrossFamilyDispatch && account.Platform == service.PlatformGemini {
|
||||
// Gemini 账号经 Gemini 兼容链转换(与非池 gemini 分支同一实现);generic
|
||||
// Forward 只能发往 Anthropic 协议上游,会把 Google 凭据发错主机。
|
||||
if h.geminiCompatService == nil {
|
||||
err = errors.New("gemini compatibility service is not configured")
|
||||
} else {
|
||||
result, err = h.geminiCompatService.Forward(requestCtx, c, account, attemptBody)
|
||||
}
|
||||
} else if canCrossFamilyDispatch && compositePoolAccountDelegatesToOpenAI(account) {
|
||||
// 纯 OpenAI 族账号(无 Anthropic 协议能力)在池激活或跨组切入 composite 时委派 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, schedAPIKey, reqModel)))
|
||||
delegated = true
|
||||
delegatedResult = openAIResult
|
||||
result = adaptOpenAIForwardResultToForwardResult(openAIResult)
|
||||
err = delegateErr
|
||||
} else {
|
||||
result, err = h.gatewayService.Forward(requestCtx, c, account, attemptParsedReq)
|
||||
}
|
||||
@@ -951,10 +1103,31 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
if delegated {
|
||||
h.recordDelegatedCyberPolicyIfMarked(c, currentAPIKey, account, currentSubscription, reqModel, err != nil, attemptBody, clientRequestedUsageFields(c, attemptChannelMapping, reqModel, ""))
|
||||
}
|
||||
|
||||
// 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果"
|
||||
// 错误路径共用:后者若不入账,上游已计量的请求会完全漏记漏计费(#5148)。
|
||||
submitForwardUsage := func(result *service.ForwardResult) {
|
||||
if delegatedResult != nil {
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey)
|
||||
if isPoolAttempt {
|
||||
quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, currentAPIKey)
|
||||
}
|
||||
h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{
|
||||
Result: delegatedResult,
|
||||
APIKey: currentAPIKey,
|
||||
Account: account,
|
||||
Subscription: currentSubscription,
|
||||
QuotaPlatform: quotaPlatform,
|
||||
PricingAt: pricingAt,
|
||||
RequestPayloadHash: service.HashUsageRequestPayload(attemptBody),
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel),
|
||||
LogComponent: "handler.gateway.messages",
|
||||
})
|
||||
return
|
||||
}
|
||||
// 捕获请求信息(用于异步记录,避免在 goroutine 中访问 gin.Context)
|
||||
userAgent := c.GetHeader("User-Agent")
|
||||
clientIP := ip.GetClientIP(c)
|
||||
@@ -979,9 +1152,14 @@ 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)
|
||||
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel)
|
||||
channelUsageFields := clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel)
|
||||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
|
||||
Result: result,
|
||||
@@ -1056,11 +1234,14 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
h.handleStreamingAwareError(c, status, code, message, streamStarted)
|
||||
return
|
||||
}
|
||||
// 兜底重试按"直接请求兜底分组"处理:清除强制平台,允许按分组平台调度
|
||||
ctx := context.WithValue(c.Request.Context(), ctxkey.ForcePlatform, "")
|
||||
// 兜底重试按"直接请求兜底分组"处理:清除强制平台与原分组的 composite 路由/池上下文,允许按兜底分组调度
|
||||
ctx := service.WithoutCompositeRouteContext(context.WithValue(c.Request.Context(), ctxkey.ForcePlatform, ""))
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
currentAPIKey = fallbackAPIKey
|
||||
currentSubscription = nil
|
||||
isPoolRequest = false
|
||||
poolDenials = newCompositePoolPlatformDenials()
|
||||
channelMapping, _ = h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), currentAPIKey.GroupID, reqModel)
|
||||
fallbackUsed = true
|
||||
retryWithFallback = true
|
||||
// 原分组账号已确定性失败(prompt too long),先释放其会话注册再走兜底分组
|
||||
@@ -1095,7 +1276,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
upstreamErrorAlreadyCommunicated := gatewayForwardErrorAlreadyCommunicated(c, writerSizeBeforeForward, err)
|
||||
upstreamErrorAlreadyCommunicated := compositePoolDelegatedForwardErrorAlreadyCommunicated(c, delegated, writerSizeBeforeForward, err)
|
||||
wroteFallback := false
|
||||
if !upstreamErrorAlreadyCommunicated {
|
||||
wroteFallback = h.ensureForwardErrorResponse(c, streamStarted)
|
||||
@@ -1263,6 +1444,13 @@ func (h *GatewayHandler) Models(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// ollama_cloud 账号侧清单缺失时回落实测默认目录(DefaultOllamaCloudModelIDs),
|
||||
// 不得回落 Claude 默认模型。
|
||||
if platform == service.PlatformOllamaCloud {
|
||||
writeModelsList(c, platform, service.DefaultOllamaCloudModelIDs())
|
||||
return
|
||||
}
|
||||
|
||||
writeModelsListResponse(c, claude.DefaultModels)
|
||||
}
|
||||
|
||||
@@ -1551,6 +1739,8 @@ func defaultModelIDsForPlatform(platform string) []string {
|
||||
return service.DefaultOpenCodeGoModelIDs()
|
||||
case service.PlatformTypeSafe:
|
||||
return []string{"jev-latest"}
|
||||
case service.PlatformOllamaCloud:
|
||||
return service.DefaultOllamaCloudModelIDs()
|
||||
case service.PlatformComposite:
|
||||
ids := make([]string, 0)
|
||||
seen := make(map[string]struct{})
|
||||
@@ -2274,16 +2464,43 @@ 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 service.GenericCompositePoolCountableAccount(account) {
|
||||
break
|
||||
}
|
||||
if !isPoolRequest {
|
||||
// ClaudeCodeOnly 等跨组降级选到不可计数的外平台账号时,不得把其凭据送进
|
||||
// Anthropic /v1/messages/count_tokens 链路。
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash)
|
||||
h.errorResponse(c, http.StatusNotFound, "not_found_error", "count_tokens endpoint is not supported for this platform")
|
||||
return
|
||||
}
|
||||
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)
|
||||
|
||||
|
||||
@@ -192,17 +192,42 @@ 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())
|
||||
if isPoolRequest && h.rejectCompositePoolCyberSessionBlocked(c, apiKey, body, reqModel, cyberBlockFormatChat) {
|
||||
return
|
||||
}
|
||||
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 {
|
||||
fs = NewFailoverState(h.maxAccountSwitchesGemini, false)
|
||||
}
|
||||
var lastPolicyFailure compositePoolAttemptPolicyFailure
|
||||
schedAPIKey := apiKey
|
||||
|
||||
for {
|
||||
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, schedAPIKey.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))
|
||||
@@ -231,6 +256,17 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
default:
|
||||
if fs.LastFailoverErr != nil {
|
||||
h.handleCCFailoverExhausted(c, fs.LastFailoverErr, streamStarted)
|
||||
} else if lastPolicyFailure.denied() {
|
||||
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, lastPolicyFailure, streamAwareWrite)
|
||||
} else if streamStarted {
|
||||
h.handleStreamingAwareError(c, http.StatusBadGateway, "server_error", "All available accounts exhausted", true)
|
||||
} else {
|
||||
h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "server_error", "All available accounts exhausted")
|
||||
}
|
||||
@@ -241,8 +277,52 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
|
||||
return
|
||||
}
|
||||
var switchedGroup bool
|
||||
schedAPIKey, _, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
|
||||
c, apiKey, schedAPIKey, c.Request.Context(), channelMapping, reqModel, isPoolRequest, poolDenials, selection)
|
||||
if switchedGroup && compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && poolPromptCacheKey == "" && h.openAIGatewayService != nil {
|
||||
poolPromptCacheKey = h.openAIGatewayService.ExtractSessionID(c, body)
|
||||
}
|
||||
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, schedAPIKey) {
|
||||
attemptPolicy = evaluateCompositePoolAttemptPolicy(
|
||||
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, schedAPIKey, subscription, account, reqModel, false)
|
||||
isPoolAttempt = true
|
||||
if attemptPolicy.Failure.denied() {
|
||||
releaseCompositePoolSelection(selection)
|
||||
// 选号链可能已为该账号注册会话槽(键与选号一致):排除前释放
|
||||
//(镜像 Messages 池分支)。
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, selectionSessionHash)
|
||||
if attemptPolicy.Failure.deniesPlatform() {
|
||||
poolDenials.deny(account.Platform)
|
||||
}
|
||||
lastPolicyFailure = attemptPolicy.Failure
|
||||
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 {
|
||||
@@ -299,12 +379,48 @@ 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)
|
||||
}
|
||||
// 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。
|
||||
if isPoolRequest {
|
||||
cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, schedAPIKey, account, forwardBody)
|
||||
if policyErr != nil {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
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)
|
||||
}
|
||||
respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite)
|
||||
return
|
||||
}
|
||||
if changed {
|
||||
forwardBody = cappedBody
|
||||
}
|
||||
}
|
||||
var result *service.ForwardResult
|
||||
// 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。
|
||||
var delegatedResult *service.OpenAIForwardResult
|
||||
delegated := false
|
||||
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")
|
||||
@@ -313,7 +429,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")
|
||||
@@ -323,14 +439,47 @@ 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 compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && compositePoolAccountDelegatesChatCompletionsToOpenAI(account) {
|
||||
// OpenAI 兼容族账号在池激活时委派 OpenAI 网关 CC 链:入站同族优先
|
||||
//(零转换,adaptive 账号由该链直转供应商原生 CC 端点),响应写回与
|
||||
// failover 错误信封都由该链完成,错误信封已是 OpenAI CC 风格,不再二次
|
||||
// 包装。defaultMappedModel 传 "",与 OpenAI handler CC 路径一致。
|
||||
openAIResult, delegateErr := h.openAIGatewayService.ForwardAsChatCompletions(
|
||||
attemptCtx, c, account, forwardBody, poolPromptCacheKey, "")
|
||||
delegated = true
|
||||
delegatedResult = openAIResult
|
||||
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 {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
if delegated {
|
||||
h.recordDelegatedCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, body, clientRequestedUsageFields(c, attemptChannelMapping, reqModel, ""))
|
||||
}
|
||||
|
||||
// 池委派 OpenAI 网关链的结果按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。
|
||||
submitDelegatedUsage := func() {
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
if isPoolAttempt {
|
||||
quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey)
|
||||
}
|
||||
h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{
|
||||
Result: delegatedResult,
|
||||
APIKey: apiKey,
|
||||
Account: account,
|
||||
Subscription: subscription,
|
||||
QuotaPlatform: quotaPlatform,
|
||||
PricingAt: pricingAt,
|
||||
RequestPayloadHash: service.HashUsageRequestPayload(body),
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel),
|
||||
LogComponent: "handler.gateway.chat_completions",
|
||||
})
|
||||
}
|
||||
|
||||
// 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果"
|
||||
// 错误路径共用;failover 错误恒定 result=nil,不会重复计费。
|
||||
@@ -342,9 +491,14 @@ 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()))
|
||||
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel)
|
||||
channelUsageFields := clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel)
|
||||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
|
||||
Result: result,
|
||||
@@ -390,7 +544,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
upstreamErrorAlreadyCommunicated := gatewayForwardErrorAlreadyCommunicated(c, writerSizeBeforeForward, err)
|
||||
upstreamErrorAlreadyCommunicated := compositePoolDelegatedForwardErrorAlreadyCommunicated(c, delegated, writerSizeBeforeForward, err)
|
||||
wroteFallback := false
|
||||
if !upstreamErrorAlreadyCommunicated {
|
||||
wroteFallback = h.ensureForwardErrorResponse(c, streamStarted)
|
||||
@@ -402,14 +556,22 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
zap.Error(err),
|
||||
)
|
||||
h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(c.Request.Context()), apiKey.GroupID, selectionSessionHash, account.ID, err)
|
||||
if result != nil {
|
||||
// 委派链流中断与 OpenAI handler 同语义:上游已计量的部分 usage 照常入账(#5148);
|
||||
// failover 错误恒定 result=nil,不会重复计费。
|
||||
if delegatedResult != nil {
|
||||
submitDelegatedUsage()
|
||||
} else if result != nil {
|
||||
submitForwardUsage(result)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 6. Record usage
|
||||
submitForwardUsage(result)
|
||||
if delegatedResult != nil {
|
||||
submitDelegatedUsage()
|
||||
} else {
|
||||
submitForwardUsage(result)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
// ollama_cloud 的默认模型目录 = DefaultOllamaCloudModelIDs:defaultModelIDsForPlatform
|
||||
// 不得回落 Claude 列表(default 分支),/models 在账号侧清单缺失时回落该目录。
|
||||
func TestDefaultModelIDsForPlatform_OllamaCloudReturnsDefaultCatalog(t *testing.T) {
|
||||
require.Equal(t, service.DefaultOllamaCloudModelIDs(), defaultModelIDsForPlatform(service.PlatformOllamaCloud))
|
||||
require.NotEmpty(t, defaultModelIDsForPlatform(service.PlatformAnthropic))
|
||||
for _, id := range defaultModelIDsForPlatform(service.PlatformOllamaCloud) {
|
||||
require.NotContains(t, id, "claude")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayModels_OllamaCloudGroupListsAllowedModels(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
groupID := int64(9201)
|
||||
h := newGatewayModelsHandlerForTest(
|
||||
&gatewayModelsAccountRepoStub{
|
||||
byGroup: map[int64][]service.Account{
|
||||
groupID: {
|
||||
{
|
||||
ID: 1,
|
||||
Platform: service.PlatformOllamaCloud,
|
||||
Credentials: map[string]any{},
|
||||
Extra: map[string]any{service.OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOllamaCloud},
|
||||
})
|
||||
|
||||
h.Models(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
var got gatewayModelsResponseForTest
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
|
||||
require.Equal(t, []string{"gpt-oss:120b"}, modelIDsForTest(got.Data))
|
||||
}
|
||||
|
||||
// 账号侧清单缺失(deny-all)时 /models 回落 ollama 默认目录,而不是 Claude 列表。
|
||||
func TestGatewayModels_OllamaCloudGroupWithoutListFallsBackToDefaultCatalog(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
groupID := int64(9202)
|
||||
h := newGatewayModelsHandlerForTest(
|
||||
&gatewayModelsAccountRepoStub{
|
||||
byGroup: map[int64][]service.Account{
|
||||
groupID: {
|
||||
{ID: 1, Platform: service.PlatformOllamaCloud, Credentials: map[string]any{}},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOllamaCloud},
|
||||
})
|
||||
|
||||
h.Models(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
var got gatewayModelsResponseForTest
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
|
||||
require.Equal(t, service.DefaultOllamaCloudModelIDs(), modelIDsForTest(got.Data),
|
||||
"ollama_cloud 不得回落 Claude 默认模型列表,应回落实测默认目录")
|
||||
}
|
||||
|
||||
// ollama_cloud 分组的 composite 白名单来源不串入 Claude 目录之外的默认回落。
|
||||
func TestGatewayModels_CompositeIncludesOllamaDefaultCatalog(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
groupID := int64(9203)
|
||||
h := newGatewayModelsHandlerForTest(
|
||||
&gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{groupID: {}}},
|
||||
)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
|
||||
})
|
||||
|
||||
h.Models(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
var got gatewayModelsResponseForTest
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
|
||||
ids := modelIDsForTest(got.Data)
|
||||
idsSet := make(map[string]struct{}, len(ids))
|
||||
for _, id := range ids {
|
||||
idsSet[id] = struct{}{}
|
||||
}
|
||||
for _, id := range service.DefaultOllamaCloudModelIDs() {
|
||||
require.Contains(t, idsSet, id, "composite /v1/models 兜底须含 ollama 目录条目 %q", id)
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,13 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
}
|
||||
if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite &&
|
||||
service.IsExplicitImageGenerationIntentValidated("/v1/responses", reqModel, body) &&
|
||||
!service.GroupAllowsImageGeneration(apiKey.Group) {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
h.responsesErrorResponse(c, http.StatusForbidden, "permission_error", service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
}
|
||||
|
||||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, reqModel, body); decision != nil && !decision.AllowNextStage {
|
||||
h.responsesSecurityAuditError(c, decision)
|
||||
@@ -195,14 +202,45 @@ 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)
|
||||
if isPoolRequest {
|
||||
// 续链只能由 OpenAI 兼容族归属账号服务(路由层已把这类请求收窄后交 OpenAI
|
||||
// handler);到达这里说明候选池无法承接,明确拒绝而不是静默丢弃上下文。
|
||||
if strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != "" {
|
||||
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error",
|
||||
"previous_response_id is not supported for this composite model; resend the full conversation without previous_response_id")
|
||||
return
|
||||
}
|
||||
if h.rejectCompositePoolCyberSessionBlocked(c, apiKey, body, reqModel, cyberBlockFormatResponses) {
|
||||
return
|
||||
}
|
||||
// 委派 OpenAI 网关链创建的响应须记录下游归属,后续续链经 OpenAI handler 校验租户。
|
||||
service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID)
|
||||
}
|
||||
poolDenials := newCompositePoolPlatformDenials()
|
||||
|
||||
// 3. Account selection + failover loop
|
||||
fs := NewFailoverState(h.maxAccountSwitches, false)
|
||||
var lastPolicyFailure compositePoolAttemptPolicyFailure
|
||||
schedAPIKey := apiKey
|
||||
|
||||
for {
|
||||
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, schedAPIKey.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))
|
||||
@@ -231,6 +269,17 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
default:
|
||||
if fs.LastFailoverErr != nil {
|
||||
h.handleResponsesFailoverExhausted(c, fs.LastFailoverErr, streamStarted)
|
||||
} else if lastPolicyFailure.denied() {
|
||||
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, lastPolicyFailure, streamAwareWrite)
|
||||
} else if streamStarted {
|
||||
h.handleStreamingAwareError(c, http.StatusBadGateway, "server_error", "All available accounts exhausted", true)
|
||||
} else {
|
||||
h.responsesErrorResponse(c, http.StatusBadGateway, "server_error", "All available accounts exhausted")
|
||||
}
|
||||
@@ -241,8 +290,88 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.responsesSecurityAuditError) {
|
||||
return
|
||||
}
|
||||
var switchedGroup bool
|
||||
schedAPIKey, requestCtx, channelMapping, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
|
||||
c, apiKey, schedAPIKey, requestCtx, channelMapping, reqModel, isPoolRequest, poolDenials, selection)
|
||||
if switchedGroup && compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) {
|
||||
// 跨组降级进入 composite 组(单目标或账号池)前从未做过 previous_response_id 租户校验,
|
||||
// 绝不允许把未校验的 previous_response_id 委派到共享 OpenAI 账号。
|
||||
if strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != "" {
|
||||
releaseCompositePoolSelection(selection)
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash)
|
||||
if streamStarted {
|
||||
h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error",
|
||||
"previous_response_id is not supported for this composite model; resend the full conversation without previous_response_id", true)
|
||||
} else {
|
||||
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error",
|
||||
"previous_response_id is not supported for this composite model; resend the full conversation without previous_response_id")
|
||||
}
|
||||
return
|
||||
}
|
||||
service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID)
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// Gemini 账号没有 Responses 转换链(generic 链只能发往 Anthropic 协议上游,会把
|
||||
// Google 凭据发错主机):池请求整平台屏蔽 gemini 后重选,候选只剩 gemini 时终止。
|
||||
if compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && account.Platform == service.PlatformGemini {
|
||||
releaseCompositePoolSelection(selection)
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash)
|
||||
if isPoolRequest {
|
||||
poolDenials.deny(account.Platform)
|
||||
fs.FailedAccountIDs[account.ID] = struct{}{}
|
||||
if _, ok := compositePoolSelectionRetryContext(requestCtx, poolDenials); ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if streamStarted {
|
||||
h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error",
|
||||
"Model is only available on Gemini accounts in this group, which do not support /v1/responses", true)
|
||||
} else {
|
||||
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error",
|
||||
"Model is only available on Gemini accounts in this group, which do not support /v1/responses")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 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, schedAPIKey) {
|
||||
attemptPolicy = evaluateCompositePoolAttemptPolicy(
|
||||
requestCtx, h.billingCacheService, h.openAIGatewayService, schedAPIKey, subscription, account, reqModel, false)
|
||||
isPoolAttempt = true
|
||||
if attemptPolicy.Failure.denied() {
|
||||
releaseCompositePoolSelection(selection)
|
||||
// 选号链可能已为该账号注册会话槽:排除前释放(镜像 Messages 池分支)。
|
||||
h.gatewayService.ReleaseAccountSession(context.Background(), account, sessionHash)
|
||||
if attemptPolicy.Failure.deniesPlatform() {
|
||||
poolDenials.deny(account.Platform)
|
||||
}
|
||||
lastPolicyFailure = attemptPolicy.Failure
|
||||
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 {
|
||||
@@ -293,12 +422,49 @@ 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)
|
||||
}
|
||||
// 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。
|
||||
if isPoolRequest {
|
||||
cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, schedAPIKey, account, forwardBody)
|
||||
if policyErr != nil {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
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)
|
||||
}
|
||||
respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite)
|
||||
return
|
||||
}
|
||||
if changed {
|
||||
forwardBody = cappedBody
|
||||
}
|
||||
}
|
||||
var result *service.ForwardResult
|
||||
// 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。
|
||||
var delegatedResult *service.OpenAIForwardResult
|
||||
delegated := false
|
||||
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")
|
||||
@@ -308,14 +474,47 @@ 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 compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && 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)
|
||||
delegated = true
|
||||
delegatedResult = openAIResult
|
||||
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 {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
if delegated {
|
||||
h.recordDelegatedCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, body, clientRequestedUsageFields(c, attemptChannelMapping, reqModel, ""))
|
||||
}
|
||||
|
||||
// 池委派 OpenAI 网关链的结果按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。
|
||||
submitDelegatedUsage := func() {
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
if isPoolAttempt {
|
||||
quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey)
|
||||
}
|
||||
h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{
|
||||
Result: delegatedResult,
|
||||
APIKey: apiKey,
|
||||
Account: account,
|
||||
Subscription: subscription,
|
||||
QuotaPlatform: quotaPlatform,
|
||||
PricingAt: pricingAt,
|
||||
RequestPayloadHash: service.HashUsageRequestPayload(body),
|
||||
ChannelUsageFields: clientRequestedUsageFields(c, attemptChannelMapping, reqModel, delegatedResult.UpstreamModel),
|
||||
LogComponent: "handler.gateway.responses",
|
||||
})
|
||||
}
|
||||
|
||||
// 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果"
|
||||
// 错误路径共用;failover 错误恒定 result=nil,不会重复计费。
|
||||
@@ -327,9 +526,14 @@ 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()))
|
||||
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel)
|
||||
channelUsageFields := clientRequestedUsageFields(c, attemptChannelMapping, reqModel, result.UpstreamModel)
|
||||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
|
||||
Result: result,
|
||||
@@ -376,7 +580,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
upstreamErrorAlreadyCommunicated := gatewayForwardErrorAlreadyCommunicated(c, writerSizeBeforeForward, err)
|
||||
upstreamErrorAlreadyCommunicated := compositePoolDelegatedForwardErrorAlreadyCommunicated(c, delegated, writerSizeBeforeForward, err)
|
||||
wroteFallback := false
|
||||
if !upstreamErrorAlreadyCommunicated {
|
||||
wroteFallback = h.ensureForwardErrorResponse(c, streamStarted)
|
||||
@@ -390,14 +594,22 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
// The response is already committed, so the client retries; send that
|
||||
// retry through scheduling again instead of back to this account.
|
||||
h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(requestCtx), apiKey.GroupID, sessionHash, account.ID, err)
|
||||
if result != nil {
|
||||
// 委派链流中断与 OpenAI handler 同语义:上游已计量的部分 usage 照常入账(#5148);
|
||||
// failover 错误恒定 result=nil,不会重复计费。
|
||||
if delegatedResult != nil {
|
||||
submitDelegatedUsage()
|
||||
} else if result != nil {
|
||||
submitForwardUsage(result)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 6. Record usage
|
||||
submitForwardUsage(result)
|
||||
if delegatedResult != nil {
|
||||
submitDelegatedUsage()
|
||||
} else {
|
||||
submitForwardUsage(result)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,7 +163,11 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
|
||||
defer userReleaseFunc()
|
||||
}
|
||||
|
||||
if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil {
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
if quotaPlatform == "" {
|
||||
quotaPlatform = platform
|
||||
}
|
||||
if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, quotaPlatform); err != nil {
|
||||
reqLog.Info("grok_media.billing_eligibility_check_failed", zap.Error(err))
|
||||
status, code, message, retryAfter := billingErrorDetails(err)
|
||||
if retryAfter > 0 {
|
||||
@@ -206,6 +210,9 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
|
||||
// 范围内:显式豁免,防止 service 层防御性装门按文本 D 误过滤媒体请求,
|
||||
// 也防止已计费的在途视频任务因绑定账号被门排除而查询返回伪 404。
|
||||
requestCtx := service.WithOpenAIProfitControlSuppressed(c.Request.Context())
|
||||
if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite {
|
||||
requestCtx = service.WithResolvedTargetPlatform(service.WithoutCompositeRouteContext(requestCtx), platform)
|
||||
}
|
||||
profitVetoCount := 0
|
||||
failedAccountIDs := make(map[int64]struct{})
|
||||
sameAccountRetryCount := make(map[int64]int)
|
||||
|
||||
@@ -115,6 +115,12 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
|
||||
// 解析渠道级模型映射
|
||||
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
|
||||
// composite 账号池请求:composite 作用域的渠道查找会跨平台行匹配(无 resolved
|
||||
// 平台),映射/限制不可靠。canonical body 保持公开模型、选号也用公开模型;
|
||||
// 平台作用域映射/限制在账号选定后按选中平台解析,非池请求保持原语义。
|
||||
if compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
channelMapping = service.ChannelMappingResult{MappedModel: reqModel}
|
||||
}
|
||||
forwardModel := openAIChannelForwardModel(channelMapping, reqModel)
|
||||
|
||||
if h.errorPassthroughService != nil {
|
||||
@@ -173,13 +179,20 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
ccPricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
|
||||
c.Request = c.Request.WithContext(ccPricingCtx)
|
||||
|
||||
// composite 账号池 per-attempt 平台策略状态:被配额/渠道限制拒绝的平台记入
|
||||
// deniedPlatforms,重选时以 filtered candidate ctx 传 selector 做整平台 mask;
|
||||
// 原请求 ctx 的候选池 immutable,不把选中账号写回。非池请求恒不生效。
|
||||
poolDenials := newCompositePoolPlatformDenials()
|
||||
var lastPolicyFailure compositePoolAttemptPolicyFailure
|
||||
selectionCtx := c.Request.Context()
|
||||
|
||||
for {
|
||||
if failoverClientGone(c) {
|
||||
return
|
||||
}
|
||||
reqLog.Debug("openai_chat_completions.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs)))
|
||||
selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
|
||||
c.Request.Context(),
|
||||
selectionCtx,
|
||||
apiKey.GroupID,
|
||||
"",
|
||||
sessionHash,
|
||||
@@ -212,6 +225,10 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
} else {
|
||||
if lastFailoverErr != nil {
|
||||
h.handleFailoverExhausted(c, lastFailoverErr, streamStarted)
|
||||
} else if lastPolicyFailure.denied() {
|
||||
respondCompositePoolAttemptPolicyFailure(c, lastPolicyFailure, func(cc *gin.Context, status int, code, message string) {
|
||||
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
|
||||
})
|
||||
} else {
|
||||
h.handleStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted)
|
||||
}
|
||||
@@ -235,6 +252,56 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
_ = scheduleDecision
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// composite 账号池请求的组 effort 策略在账号选定后按账号平台补齐;
|
||||
// 放在槽位获取前,deny/over-limit 可直接终止而不占槽。
|
||||
poolPolicyBody := body
|
||||
if cappedBody, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, body); err != nil {
|
||||
releaseCompositePoolSelection(selection)
|
||||
respondOpenAIReasoningEffortPolicyError(c, err, func(cc *gin.Context, status int, code, message string) {
|
||||
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
|
||||
})
|
||||
return
|
||||
} else if changed {
|
||||
poolPolicyBody = cappedBody
|
||||
}
|
||||
|
||||
// composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform
|
||||
// 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved
|
||||
// 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数,
|
||||
// 不得以重复调用 CheckBillingEligibility 代替。deny 不占并发槽:无状态
|
||||
// 请求记 deniedPlatforms 后按 masked 候选池整平台重选;候选全部被业务
|
||||
// 限制时按原语义终止,不误报 model unsupported。(chat 无 prevID 状态,
|
||||
// 无 pinned 分支。)
|
||||
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping}
|
||||
isPoolAttempt := false
|
||||
if compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
attemptPolicy = evaluateCompositePoolAttemptPolicy(
|
||||
c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, account, reqModel, false)
|
||||
isPoolAttempt = true
|
||||
if attemptPolicy.Failure.denied() {
|
||||
releaseCompositePoolSelection(selection)
|
||||
// streaming-aware writer:并发排队心跳可能已开始流,终止时不能拼 JSON。
|
||||
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
|
||||
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
|
||||
}
|
||||
if attemptPolicy.Failure.deniesPlatform() {
|
||||
poolDenials.deny(account.Platform)
|
||||
}
|
||||
lastPolicyFailure = attemptPolicy.Failure
|
||||
// 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号
|
||||
// 提前返回(不 clear),不会把原 sticky 账号当 platform mismatch
|
||||
// 清掉粘性绑定;其它平台成功后按用户目标正常改绑。
|
||||
failedAccountIDs[account.ID] = struct{}{}
|
||||
retryCtx, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials)
|
||||
if !ok {
|
||||
respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite)
|
||||
return
|
||||
}
|
||||
selectionCtx = retryCtx
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog)
|
||||
if slotResult == openAISlotAcquireProfitVetoed {
|
||||
// 利润终检否决:排除该账号重新选号;否决次数达上限则按无可用账号终止。
|
||||
@@ -251,9 +318,14 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
service.SetOpsLatencyMs(c, service.OpsRoutingLatencyMsKey, time.Since(routingStart).Milliseconds())
|
||||
forwardStart := time.Now()
|
||||
|
||||
forwardBody := body
|
||||
forwardBody := poolPolicyBody
|
||||
if channelMapping.Mapped {
|
||||
forwardBody = h.gatewayService.ReplaceModelInBody(body, channelMapping.MappedModel)
|
||||
forwardBody = h.gatewayService.ReplaceModelInBody(poolPolicyBody, channelMapping.MappedModel)
|
||||
}
|
||||
// 池请求按选中平台的渠道映射从 poolPolicyBody 派生本次 attempt 的 body:
|
||||
// 公开模型 → 选中平台渠道映射 → 账号 model_mapping(forward 服务内应用)。
|
||||
if isPoolAttempt {
|
||||
forwardBody = openAIModelMappedBody(poolPolicyBody, attemptPolicy.Mapping.Mapped, attemptPolicy.Mapping.MappedModel, h.gatewayService.ReplaceModelInBody)
|
||||
}
|
||||
writerSizeBeforeForward := c.Writer.Size()
|
||||
result, err := func() (*service.OpenAIForwardResult, error) {
|
||||
@@ -262,13 +334,19 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
}()
|
||||
return h.gatewayService.ForwardAsChatCompletions(c.Request.Context(), c, account, forwardBody, promptCacheKey, "")
|
||||
// 池请求的 attempt 局部 ctx 携带选中平台:forward 内渠道定价作用域与
|
||||
// 计费 QuotaPlatform 跟随实际平台,不写回 c.Request。
|
||||
forwardCtx := c.Request.Context()
|
||||
if isPoolAttempt {
|
||||
forwardCtx = attemptPolicy.AttemptCtx
|
||||
}
|
||||
return h.gatewayService.ForwardAsChatCompletions(forwardCtx, c, account, forwardBody, promptCacheKey, "")
|
||||
}()
|
||||
var cyberBlockBodyChat []byte
|
||||
if service.GetOpsCyberPolicy(c) != nil {
|
||||
cyberBlockBodyChat = body
|
||||
}
|
||||
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyChat, clientRequestedUsageFields(c, channelMapping, reqModel, ""), service.HashUsageRequestPayload(body))
|
||||
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyChat, clientRequestedUsageFields(c, attemptPolicy.Mapping, reqModel, ""), service.HashUsageRequestPayload(body))
|
||||
|
||||
forwardDurationMs := time.Since(forwardStart).Milliseconds()
|
||||
upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey)
|
||||
@@ -291,10 +369,15 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
clientIP := ip.GetClientIP(c)
|
||||
inboundEndpoint := GetInboundEndpoint(c)
|
||||
upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res)
|
||||
// 池请求按选中平台计量 user×platform 配额(尝试 ctx 携带 resolved 平台);
|
||||
// 非池保持准入语义不变。
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
if isPoolAttempt {
|
||||
quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey)
|
||||
}
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
cyberBlocked := service.GetOpsCyberPolicy(c) != nil
|
||||
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel)
|
||||
channelUsageFields := clientRequestedUsageFields(c, attemptPolicy.Mapping, reqModel, res.UpstreamModel)
|
||||
h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
|
||||
Result: res,
|
||||
|
||||
@@ -84,6 +84,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) {
|
||||
}
|
||||
|
||||
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
|
||||
if compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
channelMapping = service.ChannelMappingResult{MappedModel: reqModel}
|
||||
}
|
||||
routingModel := reqModel
|
||||
forwardBody := body
|
||||
if channelMapping.Mapped {
|
||||
@@ -127,6 +130,13 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
if compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
attemptMapping := h.gatewayService.CompositePoolAttemptChannelMapping(
|
||||
compositePoolAttemptContext(c.Request.Context(), account), apiKey.GroupID, reqModel)
|
||||
if attemptMapping.Mapped {
|
||||
forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptMapping.MappedModel)
|
||||
}
|
||||
}
|
||||
if err := h.gatewayService.ForwardResponsesInputTokens(c.Request.Context(), c, account, forwardBody); err != nil {
|
||||
reqLog.Error("openai_input_tokens.forward_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
}
|
||||
@@ -236,8 +246,8 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) {
|
||||
|
||||
reqModel := parsedReq.Model
|
||||
ensureCompositeTargetPlatform(c, apiKey, reqModel)
|
||||
// composite+grok 在路由层已分流到 GrokCountTokens,这里可达的目标平台是
|
||||
// openai 与 CN 供应商;CN 账号由 ForwardCountTokensAsAnthropic 本地估算。
|
||||
// 单目标 composite+grok 在路由层已分流到 GrokCountTokens;兼容族账号池仍可能
|
||||
// 选中 grok 账号,与 CN 账号一样由 ForwardCountTokensAsAnthropic 本地估算。
|
||||
if !openAICompatibleTextTargetAllowed(c, apiKey, reqModel) {
|
||||
h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups")
|
||||
return
|
||||
@@ -250,6 +260,9 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) {
|
||||
setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(false, false)))
|
||||
|
||||
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
|
||||
if compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
channelMapping = service.ChannelMappingResult{MappedModel: reqModel}
|
||||
}
|
||||
mappedBodyForMessages := newOpenAIModelMappedBodyCache(body, h.gatewayService.ReplaceModelInBody)
|
||||
|
||||
subscription, _ := middleware2.GetSubscriptionFromContext(c)
|
||||
@@ -304,7 +317,12 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
forwardBody := mappedBodyForMessages(channelMapping.Mapped, channelMapping.MappedModel)
|
||||
attemptMapping := channelMapping
|
||||
if compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
attemptMapping = h.gatewayService.CompositePoolAttemptChannelMapping(
|
||||
compositePoolAttemptContext(c.Request.Context(), account), apiKey.GroupID, reqModel)
|
||||
}
|
||||
forwardBody := mappedBodyForMessages(attemptMapping.Mapped, attemptMapping.MappedModel)
|
||||
defaultMappedModel := preferredMappedModel
|
||||
|
||||
if err := h.gatewayService.ForwardCountTokensAsAnthropic(c.Request.Context(), c, account, forwardBody, defaultMappedModel); err != nil {
|
||||
|
||||
@@ -211,6 +211,16 @@ func resolveOpenAIMessagesDispatchMappedModel(c *gin.Context, apiKey *service.AP
|
||||
(platform == service.PlatformGrok || service.IsMultiProtocolAPIKeyProvider(platform)) {
|
||||
return ""
|
||||
}
|
||||
// 账号池候选含任一 grok/CN/OpenCode Go 时同样不套 gpt-5.x 默认映射
|
||||
// (与对应单平台语义一致,否则 claude-* 别名被改写成 gpt 默认后账号
|
||||
// 声明失配);候选全为 openai 时保留既有分组默认。
|
||||
if candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context()); len(candidates) > 0 {
|
||||
for _, platform := range candidates {
|
||||
if platform == service.PlatformGrok || service.IsMultiProtocolAPIKeyProvider(platform) {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(apiKey.Group.ResolveMessagesDispatchModel(requestedModel))
|
||||
}
|
||||
@@ -330,6 +340,20 @@ func allowOpenAICompatibleMessagesDispatch(c *gin.Context, apiKey *service.APIKe
|
||||
(platform == service.PlatformGrok || service.IsMultiProtocolAPIKeyProvider(platform)) {
|
||||
return true
|
||||
}
|
||||
// 账号池候选与单目标同语义:候选全部为 grok/CN/OpenCode Go 时豁免;
|
||||
// 混有 openai 候选时仍受分组开关控制,不折叠候选。
|
||||
if candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context()); len(candidates) > 0 {
|
||||
allExempt := true
|
||||
for _, platform := range candidates {
|
||||
if platform != service.PlatformGrok && !service.IsMultiProtocolAPIKeyProvider(platform) {
|
||||
allExempt = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if allExempt {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return apiKey.Group.AllowMessagesDispatch
|
||||
}
|
||||
@@ -599,6 +623,13 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
|
||||
// 解析渠道级模型映射
|
||||
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
|
||||
// composite 账号池请求:composite 作用域的渠道查找会跨平台行匹配(无 resolved
|
||||
// 平台),映射/限制不可靠。canonical body 保持公开模型、选号也用公开模型;
|
||||
// 真正的平台作用域映射/限制在账号选定后按选中平台解析
|
||||
//(evaluateCompositePoolAttemptPolicy),非池请求保持原映射语义。
|
||||
if compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
channelMapping = service.ChannelMappingResult{MappedModel: reqModel}
|
||||
}
|
||||
forwardBody := openAIModelMappedBody(body, channelMapping.Mapped, channelMapping.MappedModel, h.gatewayService.ReplaceModelInBody)
|
||||
seedOpenAIForwardImageIntentHint(c, channelMapping.Mapped, imageIntent)
|
||||
forwardModel := openAIChannelForwardModel(channelMapping, reqModel)
|
||||
@@ -703,6 +734,12 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
pricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
|
||||
c.Request = c.Request.WithContext(pricingCtx)
|
||||
|
||||
// composite 账号池 per-attempt 平台策略状态:被配额/渠道限制拒绝的平台记入
|
||||
// deniedPlatforms,重选时以 filtered candidate ctx 传 selector 做整平台 mask;
|
||||
// 原请求 ctx 的候选池 immutable,不把选中账号写回。非池请求恒不生效。
|
||||
poolDenials := newCompositePoolPlatformDenials()
|
||||
var lastPolicyFailure compositePoolAttemptPolicyFailure
|
||||
selectionCtx := c.Request.Context()
|
||||
var (
|
||||
requestPayloadHashComputed bool
|
||||
requestPayloadHashValue string
|
||||
@@ -725,7 +762,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
// Select account supporting the requested model
|
||||
reqLog.Debug("openai.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs)))
|
||||
selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
|
||||
c.Request.Context(),
|
||||
selectionCtx,
|
||||
apiKey.GroupID,
|
||||
previousResponseID,
|
||||
sessionHash,
|
||||
@@ -770,6 +807,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
}
|
||||
if lastFailoverErr != nil {
|
||||
h.handleFailoverExhausted(c, lastFailoverErr, streamStarted)
|
||||
} else if lastPolicyFailure.denied() {
|
||||
respondCompositePoolAttemptPolicyFailure(c, lastPolicyFailure, func(cc *gin.Context, status int, code, message string) {
|
||||
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
|
||||
})
|
||||
} else {
|
||||
h.handleFailoverExhaustedSimple(c, 502, streamStarted)
|
||||
}
|
||||
@@ -796,7 +837,34 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
zap.Float64("load_skew", scheduleDecision.LoadSkew),
|
||||
)
|
||||
account := selection.Account
|
||||
if previousResponseID != "" && requestPlatform == service.PlatformOpenAI && !account.IsOpenAIApiKey() {
|
||||
// composite 账号池状态归属守卫:携带 previous_response_id 的池请求必须
|
||||
// 命中状态归属账号(StickyPreviousHit),否则在任何转发之前明确拒绝——
|
||||
// 不区分候选平台(CN A→CN B / CN→OpenCode / CN→openai 的未 hit 转移
|
||||
// 一律拒绝),不静默剥离 prevID、不把会话状态跨账号携带。pin 账号首跳
|
||||
// 失败被排除后再选到其他账号时同样由此拦下。早退须先释放 selector 已
|
||||
// 持有的槽位(Acquired=true 时 ReleaseFunc 非空,恰一次)。
|
||||
if previousResponseID != "" && compositePoolResponseStateGuardApplies(c, apiKey) && !scheduleDecision.StickyPreviousHit {
|
||||
releaseCompositePoolSelection(selection)
|
||||
// 归属账号本次已失败被排除(如 429):返回其可重试错误,不能变成永久性的 400。
|
||||
if lastFailoverErr != nil {
|
||||
h.handleFailoverExhausted(c, lastFailoverErr, streamStarted)
|
||||
return
|
||||
}
|
||||
// 绑定仍在但归属账号暂时不可用(限流、过载、临时不可调度等):可重试。
|
||||
if h.gatewayService.HasPreviousResponseBinding(c.Request.Context(), apiKey.GroupID, previousResponseID) {
|
||||
markOpsRoutingCapacityLimited(c)
|
||||
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "api_error",
|
||||
"the account that owns previous_response_id is temporarily unavailable; retry later", streamStarted)
|
||||
return
|
||||
}
|
||||
h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error",
|
||||
"previous_response_id belongs to a response owned by a different account; continue on the account that owns this response state or start a new response", streamStarted)
|
||||
return
|
||||
}
|
||||
// 仅实际 openai 平台账号要求 API-key 才支持 HTTP continuation;
|
||||
// pool 请求的 requestPlatform 归一化恒为 openai,不得作为判据
|
||||
// (否则 sticky 命中的 CN/OpenCode 账号会被误排除)。
|
||||
if previousResponseID != "" && account.Platform == service.PlatformOpenAI && !account.IsOpenAIApiKey() {
|
||||
// The public Responses HTTP API supports previous_response_id on API-key
|
||||
// accounts. OAuth/SetupToken upstreams do not, so keep searching instead
|
||||
// of silently deleting continuation state from a mixed account pool.
|
||||
@@ -826,6 +894,62 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
reqLog.Debug("openai.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name))
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// composite 账号池请求的组 effort 策略在账号选定后按账号平台补齐;
|
||||
// 放在槽位获取前,deny/over-limit 可直接终止而不占槽。canonical
|
||||
// forwardBody 保持不可变,策略结果只用于本次尝试的派生。
|
||||
poolPolicyBody := forwardBody
|
||||
if cappedBody, changed, err := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, apiKey, account, forwardBody); err != nil {
|
||||
releaseCompositePoolSelection(selection)
|
||||
respondOpenAIReasoningEffortPolicyError(c, err, func(cc *gin.Context, status int, code, message string) {
|
||||
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
|
||||
})
|
||||
return
|
||||
} else if changed {
|
||||
poolPolicyBody = cappedBody
|
||||
}
|
||||
|
||||
// composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform
|
||||
// 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved
|
||||
// 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数,
|
||||
// 不得以重复调用 CheckBillingEligibility 代替。deny 不占并发槽:
|
||||
// - pinned(prevID 状态归属)请求:直接回原 policy 错误(配额 429+重试
|
||||
// 头 / 渠道 503),不换账号、不删 previousID、不改绑定;
|
||||
// - 无状态请求:记 deniedPlatforms 后按 masked 候选池整平台重选,
|
||||
// 候选全部被业务限制时按原语义终止,不误报 model unsupported。
|
||||
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMapping}
|
||||
isPoolAttempt := false
|
||||
if compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
attemptPolicy = evaluateCompositePoolAttemptPolicy(
|
||||
c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, account, reqModel, requireCompact)
|
||||
isPoolAttempt = true
|
||||
if attemptPolicy.Failure.denied() {
|
||||
releaseCompositePoolSelection(selection)
|
||||
// streaming-aware writer:并发排队心跳可能已开始流,终止时不能拼 JSON。
|
||||
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
|
||||
h.handleStreamingAwareError(cc, status, code, message, streamStarted)
|
||||
}
|
||||
if previousResponseID != "" && compositePoolResponseStateGuardApplies(c, apiKey) {
|
||||
respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite)
|
||||
return
|
||||
}
|
||||
if attemptPolicy.Failure.deniesPlatform() {
|
||||
poolDenials.deny(account.Platform)
|
||||
}
|
||||
lastPolicyFailure = attemptPolicy.Failure
|
||||
// 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号
|
||||
// 提前返回(不 clear),不会把原 sticky 账号当 platform mismatch
|
||||
// 清掉粘性绑定;其它平台成功后按用户目标正常改绑。
|
||||
failedAccountIDs[account.ID] = struct{}{}
|
||||
retryCtx, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials)
|
||||
if !ok {
|
||||
respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite)
|
||||
return
|
||||
}
|
||||
selectionCtx = retryCtx
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog)
|
||||
if slotResult == openAISlotAcquireProfitVetoed {
|
||||
// 利润终检否决:排除该账号重新选号,全池耗尽由下一轮选号报错;
|
||||
@@ -849,20 +973,32 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
// 跨 passthrough 边界的 failover:从 Kiro 等透传账号切到 Bedrock 等非透传账号前,
|
||||
// 从不可变的 canonical forwardBody 派生本次尝试 body 并整块剔除上游私有的加密
|
||||
// reasoning item(含耦合的 id/summary),避免非透传上游 400 拒绝 Kiro reasoning 形态。
|
||||
attemptBody := h.deriveOpenAIForwardAttemptBody(reqLog, forwardBody, account, &passthroughFailoverState)
|
||||
// 池请求先按选中平台的渠道映射从 poolPolicyBody 派生本次 attempt 的
|
||||
// channel-mapped body,再交给账号级 model_mapping(derive 内应用一次)。
|
||||
attemptChannelBody := poolPolicyBody
|
||||
if isPoolAttempt {
|
||||
attemptChannelBody = openAIModelMappedBody(poolPolicyBody, attemptPolicy.Mapping.Mapped, attemptPolicy.Mapping.MappedModel, h.gatewayService.ReplaceModelInBody)
|
||||
}
|
||||
attemptBody := h.deriveOpenAIForwardAttemptBody(reqLog, attemptChannelBody, account, &passthroughFailoverState)
|
||||
result, err := func() (*service.OpenAIForwardResult, error) {
|
||||
defer func() {
|
||||
if accountReleaseFunc != nil {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
}()
|
||||
return h.gatewayService.Forward(c.Request.Context(), c, account, attemptBody)
|
||||
// 池请求的 attempt 局部 ctx 携带选中平台:forward 内的渠道定价作用域
|
||||
// 与计费 QuotaPlatform 都跟随实际平台,不写回 c.Request。
|
||||
forwardCtx := c.Request.Context()
|
||||
if isPoolAttempt {
|
||||
forwardCtx = attemptPolicy.AttemptCtx
|
||||
}
|
||||
return h.gatewayService.Forward(forwardCtx, c, account, attemptBody)
|
||||
}()
|
||||
if h.handleForwardRequestBodyMemoryOverload(c, err, streamStarted) {
|
||||
return
|
||||
}
|
||||
if service.GetOpsCyberPolicy(c) != nil {
|
||||
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, sessionHashBody, clientRequestedUsageFields(c, channelMapping, reqModel, ""), getRequestPayloadHash())
|
||||
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, sessionHashBody, clientRequestedUsageFields(c, attemptPolicy.Mapping, reqModel, ""), getRequestPayloadHash())
|
||||
}
|
||||
forwardDurationMs := time.Since(forwardStart).Milliseconds()
|
||||
upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey)
|
||||
@@ -886,10 +1022,15 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
requestPayloadHash := getRequestPayloadHash()
|
||||
inboundEndpoint := GetInboundEndpoint(c)
|
||||
upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res)
|
||||
// 池请求按选中平台计量 user×platform 配额(尝试 ctx 携带 resolved 平台);
|
||||
// 非池保持准入语义不变。
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
if isPoolAttempt {
|
||||
quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey)
|
||||
}
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
cyberBlocked := service.GetOpsCyberPolicy(c) != nil
|
||||
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel)
|
||||
channelUsageFields := clientRequestedUsageFields(c, attemptPolicy.Mapping, reqModel, res.UpstreamModel)
|
||||
h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
|
||||
Result: res,
|
||||
@@ -1298,6 +1439,12 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
|
||||
// 解析渠道级模型映射
|
||||
channelMappingMsg, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
|
||||
// composite 账号池请求:composite 作用域的渠道查找会跨平台行匹配(无 resolved
|
||||
// 平台),映射/限制不可靠。平台作用域映射/限制在账号选定后按选中平台解析,
|
||||
// 非池请求保持原语义。
|
||||
if compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
channelMappingMsg = service.ChannelMappingResult{MappedModel: reqModel}
|
||||
}
|
||||
mappedBodyForMessages := newOpenAIModelMappedBodyCache(body, h.gatewayService.ReplaceModelInBody)
|
||||
// Schedule by the channel-mapped model, as the Responses and Chat Completions
|
||||
// paths do: the forwarded body carries that model, so account model filters
|
||||
@@ -1365,6 +1512,13 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
msgPricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
|
||||
c.Request = c.Request.WithContext(msgPricingCtx)
|
||||
|
||||
// composite 账号池 per-attempt 平台策略状态:被配额/渠道限制拒绝的平台记入
|
||||
// deniedPlatforms,重选时以 filtered candidate ctx 传 selector 做整平台 mask;
|
||||
// 原请求 ctx 的候选池 immutable,不把选中账号写回。非池请求恒不生效。
|
||||
poolDenials := newCompositePoolPlatformDenials()
|
||||
var lastPolicyFailure compositePoolAttemptPolicyFailure
|
||||
selectionCtx := c.Request.Context()
|
||||
|
||||
for {
|
||||
if failoverClientGone(c) {
|
||||
return
|
||||
@@ -1375,7 +1529,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
}
|
||||
reqLog.Debug("openai_messages.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs)))
|
||||
selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
|
||||
c.Request.Context(),
|
||||
selectionCtx,
|
||||
apiKey.GroupID,
|
||||
"", // no previous_response_id
|
||||
sessionHash,
|
||||
@@ -1409,6 +1563,10 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
} else {
|
||||
if lastFailoverErr != nil {
|
||||
h.handleAnthropicFailoverExhausted(c, lastFailoverErr, streamStarted)
|
||||
} else if lastPolicyFailure.denied() {
|
||||
respondCompositePoolAttemptPolicyFailure(c, lastPolicyFailure, func(cc *gin.Context, status int, code, message string) {
|
||||
h.anthropicStreamingAwareError(cc, status, code, message, streamStarted)
|
||||
})
|
||||
} else {
|
||||
h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted)
|
||||
}
|
||||
@@ -1432,6 +1590,39 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
_ = scheduleDecision
|
||||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||||
|
||||
// composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform
|
||||
// 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved
|
||||
// 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数。
|
||||
// deny 不占并发槽:无状态请求记 deniedPlatforms 后按 masked 候选池整平台
|
||||
// 重选;候选全部被业务限制时按原语义终止,不误报 model unsupported。
|
||||
// (messages 循环无 previous_response_id,无 pinned 分支。)
|
||||
attemptPolicyMsg := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: channelMappingMsg}
|
||||
isPoolAttemptMsg := false
|
||||
if compositePoolAttemptPolicyApplies(c, apiKey) {
|
||||
attemptPolicyMsg = evaluateCompositePoolAttemptPolicy(
|
||||
c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, account, reqModel, false)
|
||||
isPoolAttemptMsg = true
|
||||
if attemptPolicyMsg.Failure.denied() {
|
||||
releaseCompositePoolSelection(selection)
|
||||
if attemptPolicyMsg.Failure.deniesPlatform() {
|
||||
poolDenials.deny(account.Platform)
|
||||
}
|
||||
lastPolicyFailure = attemptPolicyMsg.Failure
|
||||
// 同时排除该账号:下一轮 masked ctx 下 sticky 层对 excluded 账号
|
||||
// 提前返回(不 clear),不清掉原 sticky 粘性绑定。
|
||||
failedAccountIDs[account.ID] = struct{}{}
|
||||
retryCtx, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials)
|
||||
if !ok {
|
||||
respondCompositePoolAttemptPolicyFailure(c, attemptPolicyMsg.Failure, func(cc *gin.Context, status int, code, message string) {
|
||||
h.anthropicStreamingAwareError(cc, status, code, message, streamStarted)
|
||||
})
|
||||
return
|
||||
}
|
||||
selectionCtx = retryCtx
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, reqStream, &streamStarted, reqLog)
|
||||
if slotResult == openAISlotAcquireProfitVetoed {
|
||||
// 利润终检否决:排除该账号重新选号,全池耗尽由下一轮选号报错;
|
||||
@@ -1450,8 +1641,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
forwardStart := time.Now()
|
||||
|
||||
defaultMappedModel := strings.TrimSpace(effectiveMappedModel)
|
||||
// 应用渠道模型映射到请求体
|
||||
forwardBody := mappedBodyForMessages(channelMappingMsg.Mapped, channelMappingMsg.MappedModel)
|
||||
// 应用渠道模型映射到请求体;池请求按选中平台的渠道映射从 canonical body
|
||||
// 派生本次 attempt 的 body:公开模型 → 选中平台渠道映射 → 账号 model_mapping。
|
||||
forwardBody := mappedBodyForMessages(attemptPolicyMsg.Mapping.Mapped, attemptPolicyMsg.Mapping.MappedModel)
|
||||
writerSizeBeforeForward := service.OpenAICompactKeepaliveAdjustedWrittenSize(c)
|
||||
result, err := func() (*service.OpenAIForwardResult, error) {
|
||||
defer func() {
|
||||
@@ -1459,13 +1651,19 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
accountReleaseFunc()
|
||||
}
|
||||
}()
|
||||
return h.gatewayService.ForwardAsAnthropic(c.Request.Context(), c, account, forwardBody, promptCacheKey, defaultMappedModel)
|
||||
// 池请求的 attempt 局部 ctx 携带选中平台:forward 内渠道定价作用域与
|
||||
// 计费 QuotaPlatform 跟随实际平台,不写回 c.Request。
|
||||
forwardCtx := c.Request.Context()
|
||||
if isPoolAttemptMsg {
|
||||
forwardCtx = attemptPolicyMsg.AttemptCtx
|
||||
}
|
||||
return h.gatewayService.ForwardAsAnthropic(forwardCtx, c, account, forwardBody, promptCacheKey, defaultMappedModel)
|
||||
}()
|
||||
var cyberBlockBodyMsg []byte
|
||||
if service.GetOpsCyberPolicy(c) != nil {
|
||||
cyberBlockBodyMsg = body
|
||||
}
|
||||
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyMsg, clientRequestedUsageFields(c, channelMappingMsg, reqModel, ""), service.HashUsageRequestPayload(body))
|
||||
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyMsg, clientRequestedUsageFields(c, attemptPolicyMsg.Mapping, reqModel, ""), service.HashUsageRequestPayload(body))
|
||||
forwardDurationMs := time.Since(forwardStart).Milliseconds()
|
||||
upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey)
|
||||
responseLatencyMs := forwardDurationMs
|
||||
@@ -1489,10 +1687,15 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
requestPayloadHash := service.HashUsageRequestPayload(body)
|
||||
inboundEndpoint := GetInboundEndpoint(c)
|
||||
upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res)
|
||||
// 池请求按选中平台计量 user×platform 配额(尝试 ctx 携带 resolved 平台);
|
||||
// 非池保持准入语义不变。
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
if isPoolAttemptMsg {
|
||||
quotaPlatform = service.QuotaPlatform(attemptPolicyMsg.AttemptCtx, apiKey)
|
||||
}
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
cyberBlocked := service.GetOpsCyberPolicy(c) != nil
|
||||
channelUsageFields := clientRequestedUsageFields(c, channelMappingMsg, reqModel, res.UpstreamModel)
|
||||
channelUsageFields := clientRequestedUsageFields(c, attemptPolicyMsg.Mapping, reqModel, res.UpstreamModel)
|
||||
h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) {
|
||||
if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
|
||||
Result: res,
|
||||
@@ -4854,6 +5057,8 @@ func (h *OpenAIGatewayHandler) recordCyberPolicyIfMarked(c *gin.Context, apiKey
|
||||
// 提前拍成标量,避免在下方 goroutine 内访问 gin.Context。
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
nativeCompactionV2 := service.IsOpenAINativeCompactionV2(c)
|
||||
upstreamModel := strings.TrimSpace(c.GetString(service.OpsUpstreamModelKey))
|
||||
pricingAt := service.RequestPricingAtFromContext(requestCtx)
|
||||
apiKeyPrefix := ""
|
||||
if apiKey != nil {
|
||||
apiKeyPrefix = keyPrefix(apiKey.Key, 8)
|
||||
@@ -4913,6 +5118,8 @@ func (h *OpenAIGatewayHandler) recordCyberPolicyIfMarked(c *gin.Context, apiKey
|
||||
Subscription: subscription,
|
||||
RequestID: requestID,
|
||||
Model: model,
|
||||
UpstreamModel: upstreamModel,
|
||||
PricingAt: pricingAt,
|
||||
Stream: stream,
|
||||
InputTokens: mark.UpstreamInTok,
|
||||
OutputTokens: mark.UpstreamOutTok,
|
||||
|
||||
@@ -468,7 +468,11 @@ func setOpsSelectedAccount(c *gin.Context, accountID int64, platform ...string)
|
||||
if c == nil || accountID <= 0 {
|
||||
return
|
||||
}
|
||||
// 尝试级元数据随账号切换重置:Handler 在账号 failover 间复用同一个 Gin
|
||||
// context,上一账号的实际出站端点/模型不得泄漏到下一账号的失败日志。
|
||||
service.ClearOpsUpstreamModel(c)
|
||||
service.ClearOpsUpstreamEndpoint(c)
|
||||
service.ClearActualOpenAIUpstreamEndpoint(c)
|
||||
c.Set(opsAccountIDKey, accountID)
|
||||
if c.Request != nil {
|
||||
ctx := context.WithValue(c.Request.Context(), ctxkey.AccountID, accountID)
|
||||
|
||||
@@ -114,12 +114,14 @@ func ProvideGatewayHandler(
|
||||
settingService *service.SettingService,
|
||||
coordinator *securityaudit.Coordinator,
|
||||
geminiCachedContentService *service.GeminiCachedContentService,
|
||||
openAIHandler *OpenAIGatewayHandler,
|
||||
) *GatewayHandler {
|
||||
h := NewGatewayHandler(gatewayService, openAIGatewayService, geminiCompatService, antigravityGatewayService,
|
||||
userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool,
|
||||
errorPassthroughService, contentModerationService, userMsgQueueService, cfg, settingService)
|
||||
h.securityAuditCoordinator = coordinator
|
||||
h.geminiCachedContentService = geminiCachedContentService
|
||||
h.openAIHandler = openAIHandler
|
||||
return h
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ const (
|
||||
PlatformMiniMax = domain.PlatformMiniMax
|
||||
PlatformOpenCodeGo = domain.PlatformOpenCodeGo
|
||||
PlatformTypeSafe = domain.PlatformTypeSafe
|
||||
PlatformOllamaCloud = domain.PlatformOllamaCloud
|
||||
)
|
||||
|
||||
// AllPlatforms 返回所有支持的平台列表(平台清单,按展示顺序)。
|
||||
|
||||
@@ -21,5 +21,6 @@ func TestAllPlatformsIncludesEveryConcretePlatform(t *testing.T) {
|
||||
"typesafe",
|
||||
"command_code",
|
||||
"cline",
|
||||
"ollama_cloud",
|
||||
}, AllPlatforms())
|
||||
}
|
||||
@@ -20,6 +20,15 @@ const (
|
||||
// CompositeRouteSource 标识 composite 解析结果来自显式路由还是内置模型探测。
|
||||
CompositeRouteSource Key = "ctx_composite_route_source"
|
||||
|
||||
// CompositeRequiredClaimStrength 是 composite 账号归属(account_model / account_pool)
|
||||
// 构成时采用的声明层级:账号须达到该层级才能承接请求。
|
||||
CompositeRequiredClaimStrength Key = "ctx_composite_required_claim_strength"
|
||||
|
||||
// CompositeCandidatePlatforms 是 composite 多平台候选池(account_pool 决策)
|
||||
// 的参与平台集合(去重升序)。与 ResolvedTargetPlatform 互斥写入:池决策不
|
||||
// 固定单一目标平台,选号期间不得被最终账号平台覆盖。
|
||||
CompositeCandidatePlatforms Key = "ctx_composite_candidate_platforms"
|
||||
|
||||
// RequestID 为服务端生成/透传的请求 ID。
|
||||
RequestID Key = "ctx_request_id"
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
@@ -15,17 +16,29 @@ const (
|
||||
ollamaCloudBaseURLRegexSQL = `^[hH][tT][tT][pP][sS]://([wW][wW][wW]\.)?[oO][lL][lL][aA][mM][aA]\.[cC][oO][mM](:443)?(/v1)?$`
|
||||
ollamaCloudBaseURLMatchSQLPrefix = "btrim("
|
||||
ollamaCloudBaseURLMatchSQLSuffix = ") ~ '" + ollamaCloudBaseURLRegexSQL + "'"
|
||||
// ollamaCloudUsagePlatformsSQL 是 service.isOllamaCloudUsagePlatform 的 SQL
|
||||
// 镜像:Ollama Cloud key 允许挂在 openai/anthropic 与国产 OpenAI 兼容平台
|
||||
// 下复用。所有平台白名单 SQL 只允许引用本常量,不得各处重写字面量,防止漂移。
|
||||
ollamaCloudUsagePlatformsSQL = "'openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'"
|
||||
ollamaCloudUsageEligibleSQL = `
|
||||
)
|
||||
|
||||
// ollamaCloudUsagePlatformsSQL 是 service.OllamaCloudUsagePlatforms(权威平台
|
||||
// 白名单,含 platform=ollama_cloud 本体与 legacy 宿主平台)派生的 SQL IN
|
||||
// 字面量。派生自同一列表,两侧结构上不可能漂移;原先的手工镜像注释随之作废。
|
||||
// 所有平台白名单 SQL 只允许引用本变量,不得各处重写字面量。
|
||||
var ollamaCloudUsagePlatformsSQL = ollamaCloudPlatformsSQLLiteral(service.OllamaCloudUsagePlatforms)
|
||||
|
||||
var ollamaCloudUsageEligibleSQL = `
|
||||
platform IN (` + ollamaCloudUsagePlatformsSQL + `)
|
||||
AND type = 'apikey'
|
||||
AND ` + ollamaCloudBaseURLMatchSQLPrefix + `credentials ->> 'base_url'` + ollamaCloudBaseURLMatchSQLSuffix + `
|
||||
AND jsonb_typeof(credentials -> 'api_key') = 'string'
|
||||
`
|
||||
)
|
||||
|
||||
// ollamaCloudPlatformsSQLLiteral 把平台列表渲染为 SQL IN 字面量('a', 'b')。
|
||||
func ollamaCloudPlatformsSQLLiteral(platforms []string) string {
|
||||
quoted := make([]string, len(platforms))
|
||||
for i, platform := range platforms {
|
||||
quoted[i] = "'" + platform + "'"
|
||||
}
|
||||
return strings.Join(quoted, ", ")
|
||||
}
|
||||
|
||||
func ollamaCloudBaseURLMatchesSQL(expression string) string {
|
||||
return ollamaCloudBaseURLMatchSQLPrefix + expression + ollamaCloudBaseURLMatchSQLSuffix
|
||||
@@ -186,6 +199,7 @@ func (r *accountRepository) updateOllamaCloudUsageGroup(
|
||||
if !ok || apiKey == "" {
|
||||
return service.ErrOllamaCloudUsageAccountInvalid
|
||||
}
|
||||
var syncedMemberIDs []int64
|
||||
apply := func(txCtx context.Context, client *dbent.Client) error {
|
||||
matchesProxy, err := lockAndMatchProbeProxyIdentity(txCtx, client, account)
|
||||
if err != nil {
|
||||
@@ -261,14 +275,33 @@ func (r *accountRepository) updateOllamaCloudUsageGroup(
|
||||
if affected != int64(len(members)) {
|
||||
return service.ErrOllamaCloudUsageIdentityChanged
|
||||
}
|
||||
for _, memberID := range memberIDs {
|
||||
id := memberID
|
||||
if err := enqueueSchedulerOutbox(txCtx, client, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
syncedMemberIDs = memberIDs
|
||||
return nil
|
||||
}
|
||||
if dbent.TxFromContext(ctx) != nil {
|
||||
return apply(ctx, clientFromContext(ctx, r.client))
|
||||
if err := apply(ctx, clientFromContext(ctx, r.client)); err != nil {
|
||||
return err
|
||||
}
|
||||
service.AfterAccountCommit(ctx, func(commitCtx context.Context) {
|
||||
r.syncSchedulerAccountSnapshots(commitCtx, syncedMemberIDs)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
tx, err := r.client.Tx(ctx)
|
||||
if errors.Is(err, dbent.ErrTxStarted) {
|
||||
return apply(ctx, r.client)
|
||||
if err := apply(ctx, r.client); err != nil {
|
||||
return err
|
||||
}
|
||||
// 对齐 account_repo.go:516(contextTx == nil 时立即刷快照,兼容 testEntTx 集成测试夹具;
|
||||
// 生产嵌套事务均经 dbent.TxFromContext 走上方 AfterAccountCommit 分支)。
|
||||
r.syncSchedulerAccountSnapshots(ctx, syncedMemberIDs)
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -278,7 +311,11 @@ func (r *accountRepository) updateOllamaCloudUsageGroup(
|
||||
if err := apply(txCtx, tx.Client()); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
if err := tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.syncSchedulerAccountSnapshots(ctx, syncedMemberIDs)
|
||||
return nil
|
||||
}
|
||||
|
||||
func lockOllamaCloudUsageGroup(
|
||||
|
||||
@@ -303,6 +303,64 @@ func TestOllamaCloudUsageGroupWritesAreAtomicAcrossPlatformsAndURLVariants(t *te
|
||||
require.NotContains(t, firstLoaded.Extra, service.OllamaCloudUsageSessionExtraKey)
|
||||
}
|
||||
|
||||
type ollamaUsageSnapshotSyncCache struct {
|
||||
service.SchedulerCache
|
||||
mu sync.Mutex
|
||||
accounts map[int64]*service.Account
|
||||
}
|
||||
|
||||
func (c *ollamaUsageSnapshotSyncCache) SetAccount(_ context.Context, account *service.Account) error {
|
||||
if account == nil {
|
||||
return nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.accounts == nil {
|
||||
c.accounts = make(map[int64]*service.Account)
|
||||
}
|
||||
cloned := *account
|
||||
c.accounts[account.ID] = &cloned
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestUpdateOllamaCloudUsageSnapshotSyncsGroupMembersToSchedulerCache(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tx := testEntTx(t)
|
||||
cache := &ollamaUsageSnapshotSyncCache{}
|
||||
repo := newAccountRepositoryWithSQL(tx.Client(), tx, cache)
|
||||
first := mustCreateAccount(t, tx.Client(), &service.Account{
|
||||
Name: "ollama-cache-sync-1", Platform: service.PlatformOllamaCloud, Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "shared-sync-key", "base_url": "https://ollama.com/v1"},
|
||||
Extra: map[string]any{
|
||||
service.OllamaCloudUsageSessionExtraKey: "cipher:shared",
|
||||
service.OllamaCloudUsageAutoRefreshExtraKey: true,
|
||||
},
|
||||
})
|
||||
second := mustCreateAccount(t, tx.Client(), &service.Account{
|
||||
Name: "ollama-cache-sync-2", Platform: service.PlatformOllamaCloud, Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "shared-sync-key", "base_url": "https://ollama.com/v1"},
|
||||
Extra: map[string]any{
|
||||
service.OllamaCloudUsageSessionExtraKey: "cipher:shared",
|
||||
service.OllamaCloudUsageAutoRefreshExtraKey: true,
|
||||
},
|
||||
})
|
||||
firstLoaded, err := repo.GetByID(ctx, first.ID)
|
||||
require.NoError(t, err)
|
||||
now := time.Now().UTC()
|
||||
snapshot := &service.OllamaCloudUsageSnapshot{
|
||||
Status: service.OllamaCloudUsageStatusOK, LastAttemptAt: now, NextRefreshAt: now.Add(time.Hour),
|
||||
}
|
||||
require.NoError(t, repo.UpdateOllamaCloudUsageSnapshot(ctx, firstLoaded, snapshot))
|
||||
|
||||
cache.mu.Lock()
|
||||
defer cache.mu.Unlock()
|
||||
for _, id := range []int64{first.ID, second.ID} {
|
||||
synced := cache.accounts[id]
|
||||
require.NotNil(t, synced, "member %d must be synced to scheduler cache", id)
|
||||
require.Contains(t, synced.Extra, service.OllamaCloudUsageSnapshotExtraKey)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentOllamaCloudUsageSaveAndDeleteSerializeGroupState(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -121,6 +122,9 @@ func TestSaveAndDeleteOllamaCloudUsageSessionKeepCiphertextOutOfSQL(t *testing.T
|
||||
mock.ExpectExec(`(?s)UPDATE accounts.*ollama_cloud_usage_session.*ollama_cloud_usage_auto_refresh.*ollama_cloud_usage_snapshot`).
|
||||
WithArgs(`{"ollama_cloud_usage_auto_refresh":true,"ollama_cloud_usage_session":"cipher:wos-session=browser-cookie-secret"}`, "key", sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).
|
||||
WithArgs(service.SchedulerOutboxEventAccountChanged, account.ID, nil, nil, sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
require.NoError(t, repo.SaveOllamaCloudUsageSession(context.Background(), account, replacement, true))
|
||||
|
||||
@@ -130,6 +134,9 @@ func TestSaveAndDeleteOllamaCloudUsageSessionKeepCiphertextOutOfSQL(t *testing.T
|
||||
mock.ExpectExec(`(?s)UPDATE accounts.*ollama_cloud_usage_session.*ollama_cloud_usage_auto_refresh.*ollama_cloud_usage_snapshot`).
|
||||
WithArgs(`{}`, "key", sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).
|
||||
WithArgs(service.SchedulerOutboxEventAccountChanged, account.ID, nil, nil, sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
require.NoError(t, repo.DeleteOllamaCloudUsageSession(context.Background(), account))
|
||||
|
||||
@@ -179,7 +186,7 @@ func TestListOllamaCloudUsageGroupAccountsUsesOneStrictBatchQuery(t *testing.T)
|
||||
require.Empty(t, accounts)
|
||||
query := normalizeSQLWhitespace(capturedSQL)
|
||||
require.Contains(t, query, "credentials ->> 'api_key' = ANY($1)")
|
||||
require.Contains(t, query, "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax')")
|
||||
require.Contains(t, query, "platform IN ("+ollamaCloudUsagePlatformsSQL+")")
|
||||
require.Contains(t, query, "jsonb_typeof(credentials -> 'api_key') = 'string'")
|
||||
require.Contains(t, query, ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'"))
|
||||
require.NotContains(t, query, "~*")
|
||||
@@ -207,7 +214,7 @@ func TestListDueOllamaCloudUsageAccountsFiltersOrdersAndLimits(t *testing.T) {
|
||||
for _, clause := range []string{
|
||||
"deleted_at IS NULL",
|
||||
"status = 'active'",
|
||||
"platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax')",
|
||||
"platform IN (" + ollamaCloudUsagePlatformsSQL + ")",
|
||||
"type = 'apikey'",
|
||||
ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'"),
|
||||
"jsonb_typeof(extra -> 'ollama_cloud_usage_session') = 'string'",
|
||||
@@ -251,7 +258,7 @@ func TestBulkUpdateOllamaIdentityCleanupIsValueConditional(t *testing.T) {
|
||||
require.Contains(t, query, "NOT ("+ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'"))
|
||||
require.Contains(t, query, ollamaCloudBaseURLMatchesSQL("$1::jsonb ->> 'base_url'"))
|
||||
require.NotContains(t, query, "~*")
|
||||
require.Contains(t, query, "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax') AND type = 'apikey'")
|
||||
require.Contains(t, query, "platform IN ("+ollamaCloudUsagePlatformsSQL+") AND type = 'apikey'")
|
||||
require.Contains(t, query, "- 'ollama_cloud_usage_session' - 'ollama_cloud_usage_auto_refresh' - 'ollama_cloud_usage_snapshot'")
|
||||
payload, ok := exec.execArgs[0][0].([]byte)
|
||||
require.True(t, ok)
|
||||
@@ -286,6 +293,9 @@ func TestDisableOllamaCloudUsageAutoRefreshUsesGroupIdentityCAS(t *testing.T) {
|
||||
mock.ExpectExec(`(?s)UPDATE accounts.*ollama_cloud_usage_auto_refresh`).
|
||||
WithArgs(`{"ollama_cloud_usage_auto_refresh":false,"ollama_cloud_usage_session":"cipher:wos-session=secret"}`, "key", sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).
|
||||
WithArgs(service.SchedulerOutboxEventAccountChanged, account.ID, nil, nil, sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
repo := newAccountRepositoryWithSQL(client, nil, nil)
|
||||
|
||||
@@ -317,7 +327,7 @@ func TestUpdateCredentialsCleanupBranchRequiresChangedCredentials(t *testing.T)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
// SQL 平台白名单常量与 service 判定必须互为镜像:对每个已知平台,常量里的
|
||||
// SQL 平台白名单与 service 判定必须互为镜像:对每个已知平台,常量里的
|
||||
// 成员关系都要与 IsOllamaCloudUsageAccount(apikey + 官方 ollama.com)一致,
|
||||
// 防止两侧平台列表各自漂移。
|
||||
func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T) {
|
||||
@@ -326,13 +336,11 @@ func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T)
|
||||
for _, match := range matches {
|
||||
sqlPlatforms[match[1]] = struct{}{}
|
||||
}
|
||||
require.Len(t, sqlPlatforms, 6)
|
||||
for _, platform := range []string{
|
||||
service.PlatformOpenAI, service.PlatformAnthropic,
|
||||
service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax,
|
||||
require.Len(t, sqlPlatforms, len(service.OllamaCloudUsagePlatforms))
|
||||
for _, platform := range append(slices.Clone(service.OllamaCloudUsagePlatforms),
|
||||
service.PlatformGemini, service.PlatformGrok, service.PlatformAntigravity,
|
||||
service.PlatformComposite, "kiro",
|
||||
} {
|
||||
) {
|
||||
account := ollamaCloudUsageRepositoryAccount()
|
||||
account.Platform = platform
|
||||
_, inSQL := sqlPlatforms[platform]
|
||||
@@ -340,6 +348,24 @@ func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOllamaCloudUsagePlatformsMirror 锁定 SQL 平台白名单由 service 权威列表
|
||||
// (OllamaCloudUsagePlatforms,含 ollama_cloud 本体)派生这一事实:字面量可
|
||||
// 完整解析、成员一致、eligible 拼接结果包含全部平台项。若有人把派生改回手工
|
||||
// 字面量并漏掉/多写平台,本测试立即红。
|
||||
func TestOllamaCloudUsagePlatformsMirror(t *testing.T) {
|
||||
matches := regexp.MustCompile(`'([^']+)'`).FindAllStringSubmatch(ollamaCloudUsagePlatformsSQL, -1)
|
||||
sqlPlatforms := make([]string, 0, len(matches))
|
||||
for _, match := range matches {
|
||||
sqlPlatforms = append(sqlPlatforms, match[1])
|
||||
}
|
||||
require.Len(t, matches, len(service.OllamaCloudUsagePlatforms), "SQL 字面量解析出的平台项数量必须与权威列表一致")
|
||||
require.ElementsMatch(t, service.OllamaCloudUsagePlatforms, sqlPlatforms)
|
||||
require.Contains(t, sqlPlatforms, service.PlatformOllamaCloud)
|
||||
for _, platform := range service.OllamaCloudUsagePlatforms {
|
||||
require.Contains(t, ollamaCloudUsageEligibleSQL, "'"+platform+"'")
|
||||
}
|
||||
}
|
||||
|
||||
// 语义等价性:平台放开后,普通(非 ollama)kimi apikey 账号改凭证会从通用
|
||||
// apikey 分支落到 Ollama 分支——多减三个它本来就不存在的 ollama 键。分支必须
|
||||
// 仍然清掉 probe 快照,且不得减其它任何 extra 键。
|
||||
@@ -373,10 +399,30 @@ func TestUpdateCredentialsPlainCNAPIKeyAccountCleanupStaysSemanticallyEquivalent
|
||||
require.NoError(t, err)
|
||||
query := normalizeSQLWhitespace(capturedSQL)
|
||||
require.Contains(t, query,
|
||||
"platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax') AND type = 'apikey' AND credentials IS DISTINCT FROM $1::jsonb")
|
||||
"platform IN ("+ollamaCloudUsagePlatformsSQL+") AND type = 'apikey' AND credentials IS DISTINCT FROM $1::jsonb")
|
||||
require.Contains(t, query,
|
||||
"THEN COALESCE(extra, '{}'::jsonb) - 'upstream_billing_probe' - 'ollama_cloud_usage_session' - 'ollama_cloud_usage_auto_refresh' - 'ollama_cloud_usage_snapshot'")
|
||||
require.NotContains(t, query, "- 'upstream_billing_probe_enabled'")
|
||||
require.NotContains(t, query, "- 'upstream_billing_rate_sync_enabled'")
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestUpdateOllamaCloudUsageRollsBackWhenOutboxFails(t *testing.T) {
|
||||
client, mock := newOllamaCloudUsageRepositoryTestClient(t)
|
||||
account := ollamaCloudUsageRepositoryAccount()
|
||||
mock.ExpectBegin()
|
||||
expectOllamaCloudUsageGroupLock(mock, account, true, `"cipher:wos-session=secret"`, `true`, `null`)
|
||||
mock.ExpectExec(`(?s)UPDATE accounts.*ollama_cloud_usage_auto_refresh`).
|
||||
WithArgs(`{"ollama_cloud_usage_auto_refresh":false,"ollama_cloud_usage_session":"cipher:wos-session=secret"}`, "key", sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).
|
||||
WithArgs(service.SchedulerOutboxEventAccountChanged, account.ID, nil, nil, sqlmock.AnyArg()).
|
||||
WillReturnError(context.DeadlineExceeded)
|
||||
mock.ExpectRollback()
|
||||
repo := newAccountRepositoryWithSQL(client, nil, nil)
|
||||
|
||||
err := repo.DisableOllamaCloudUsageAutoRefresh(context.Background(), account)
|
||||
|
||||
require.ErrorIs(t, err, context.DeadlineExceeded)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
@@ -44,7 +44,7 @@ func TestScopedAdminReviewGroupPriorityAndStatus(t *testing.T) {
|
||||
cache := &scopedReviewSchedulerCache{accounts: make(map[int64]*service.Account)}
|
||||
repo := NewAdminAccountRepository(client, db, cache)
|
||||
groups := NewAdminGroupRepository(client, db)
|
||||
admin := service.NewAdminService(nil, nil, groups, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, client, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
admin := service.NewAdminService(nil, nil, groups, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, client, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
scoped := admin.(service.ScopedAdminAccounts)
|
||||
ctx := context.Background()
|
||||
a, err := client.Group.Create().SetName("授权组").Save(ctx)
|
||||
|
||||
@@ -30,7 +30,7 @@ func TestProxyUpdateInvalidatesBoundProbeSnapshotsAndEnqueuesOutboxAtomically(t
|
||||
AddRow("http", "old.example", 8080, "user", "pass", service.StatusActive))
|
||||
mock.ExpectExec(`(?s)UPDATE "proxies" SET`).WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
expectProxyUpdateReload(mock, 9, "new.example", "user", "pass")
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \(` + regexp.QuoteMeta(ollamaCloudUsagePlatformsSQL) + `\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
WithArgs(int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(17)).AddRow(int64(18)))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)")).
|
||||
@@ -70,7 +70,7 @@ func TestProxyUpdateRollsBackWhenProbeInvalidationOutboxFails(t *testing.T) {
|
||||
AddRow("http", "old.example", 8080, "", "", service.StatusActive))
|
||||
mock.ExpectExec(`(?s)UPDATE "proxies" SET`).WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
expectProxyUpdateReload(mock, 9, "new.example", "", "")
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \(` + regexp.QuoteMeta(ollamaCloudUsagePlatformsSQL) + `\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
WithArgs(int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(17)))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)")).
|
||||
|
||||
@@ -1648,7 +1648,12 @@ func filterSchedulerCredentials(credentials map[string]any) map[string]any {
|
||||
// Gemini 显式缓存的候选过滤(GeminiExplicitCacheExclusions)读本投影判定账号是否支持显式缓存:
|
||||
// 官方地址、Vertex 认证方式与上游网关的显式缓存声明。缺这几个键时只能按类型粗筛,
|
||||
// 不支持的账号要逐个选中后才被剔除。
|
||||
"base_url", "auth_mode", service.GeminiExplicitCacheUpstreamCredentialKey, service.GeminiExplicitCacheUpstreamMaxTTLCredentialKey}
|
||||
"base_url", "auth_mode", service.GeminiExplicitCacheUpstreamCredentialKey, service.GeminiExplicitCacheUpstreamMaxTTLCredentialKey,
|
||||
// Ollama Cloud 调度阈值过滤(GetOllamaCloudAccountMode)与 generic 跨平台池候选资格
|
||||
// (GetAPIProtocol / GetAnthropicProtocolBaseURL)均跑在本投影上:缺 account_mode
|
||||
// 会使 credits 账号误入 legacy 窗口评估,缺 api_protocol / api_base_urls 会使多协议账号
|
||||
// 在快照态丢失协议配置(如绕过非 APIKey 多协议账号防入池守卫)。
|
||||
"account_mode", "api_protocol", "api_base_urls"}
|
||||
filtered := make(map[string]any)
|
||||
for _, key := range keys {
|
||||
if value, ok := credentials[key]; ok && value != nil {
|
||||
@@ -1717,6 +1722,14 @@ func filterSchedulerExtra(extra map[string]any) map[string]any {
|
||||
"openai_passthrough_model_filter",
|
||||
// 生图尺寸档位在候选过滤阶段按本投影判定,裁掉后受限账号会接到不允许的档位。
|
||||
service.AccountExtraOpenAIImageSizeTiers,
|
||||
// ollama_cloud 空 mapping 的出站白名单必须进投影:候选过滤的
|
||||
// Account.IsModelSupported 以它为白名单(无清单即 deny-all)。
|
||||
// 裁掉它,白名单账号会在选号阶段被整体误判为 model_not_supported,
|
||||
// 表现为 ollama_cloud 分组恒 no available accounts。
|
||||
service.OllamaCloudAllowedModelsExtraKey,
|
||||
// ollama_cloud legacy 账号的 5h/7d 调度阈值停调跑在本投影上:
|
||||
// 缺该快照键会导致快照态 decodeOllamaCloudUsageSnapshot 恒为 nil 而失去停调保护。
|
||||
service.OllamaCloudUsageSnapshotExtraKey,
|
||||
"codex_fingerprint_mode",
|
||||
"codex_fingerprint_seed",
|
||||
"codex_5h_used_percent",
|
||||
@@ -1741,6 +1754,7 @@ func filterSchedulerExtra(extra map[string]any) map[string]any {
|
||||
service.UpstreamBillingProbeExtraKey,
|
||||
service.GrokMediaEligibleExtraKey,
|
||||
"grok_billing_snapshot",
|
||||
"grok_usage_snapshot",
|
||||
}
|
||||
filtered := make(map[string]any)
|
||||
for _, key := range keys {
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//go:build unit
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// ollama_cloud 空 mapping 的出站白名单(extra.allowed_models)必须穿过调度投影:
|
||||
// 候选过滤的 Account.IsModelSupported 以它为白名单(无清单即 deny-all)。裁掉它,
|
||||
// 白名单账号会在选号阶段被整体误判为 model_not_supported(#4936 同款投影缺失)。
|
||||
func TestFilterSchedulerExtra_KeepsOllamaCloudAllowedModels(t *testing.T) {
|
||||
extra := map[string]any{
|
||||
service.OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b", "qwen3:32b"},
|
||||
"unknown_key": "must-be-dropped",
|
||||
}
|
||||
|
||||
filtered := filterSchedulerExtra(extra)
|
||||
require.Len(t, filtered, 1)
|
||||
|
||||
kept, ok := filtered[service.OllamaCloudAllowedModelsExtraKey]
|
||||
require.True(t, ok, "allowed_models 必须保留在调度投影中")
|
||||
require.Contains(t, kept, "gpt-oss:120b")
|
||||
|
||||
// 走真实的序列化/反序列化路径:sched:meta 里的 []string 会以 []any 读回,
|
||||
// ollamaCloudOutboundModelNames 两种形态都必须能解析。
|
||||
payload, err := json.Marshal(filtered)
|
||||
require.NoError(t, err)
|
||||
var decoded map[string]any
|
||||
require.NoError(t, json.Unmarshal(payload, &decoded))
|
||||
|
||||
account := service.Account{ID: 1, Platform: service.PlatformOllamaCloud, Extra: decoded}
|
||||
require.True(t, account.IsModelSupported("gpt-oss:120b"))
|
||||
require.False(t, account.IsModelSupported("totally-unpriced-model"))
|
||||
}
|
||||
|
||||
// ollama_cloud 调度阈值停调(EvaluateAccountSchedulingThreshold)与多协议池资格
|
||||
// 均在快照投影账号上执行:必须保留 ollama_cloud_usage_snapshot、account_mode、
|
||||
// api_protocol 与 api_base_urls。
|
||||
func TestSchedulerMetadataAccount_KeepsOllamaCloudThresholdAndProtocolProjection(t *testing.T) {
|
||||
now := time.Date(2026, time.October, 10, 12, 0, 0, 0, time.UTC)
|
||||
fiveHourReset := now.Add(2 * time.Hour)
|
||||
snapshot := map[string]any{
|
||||
"status": service.OllamaCloudUsageStatusOK,
|
||||
"data": map[string]any{
|
||||
"five_hour": map[string]any{
|
||||
"used_percent": 95.0,
|
||||
"reset_at": fiveHourReset.Format(time.RFC3339),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
legacyAccount := service.Account{
|
||||
ID: 11,
|
||||
Platform: service.PlatformOllamaCloud,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive,
|
||||
Schedulable: true,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-ollama",
|
||||
"base_url": "https://ollama.com/v1",
|
||||
"account_mode": service.AccountModeOllamaLegacy,
|
||||
"api_protocol": service.APIProtocolAdaptive,
|
||||
"api_base_urls": map[string]any{
|
||||
"chat_completions": "https://ollama.com/v1",
|
||||
"anthropic": "https://ollama.com",
|
||||
"responses": "https://ollama.com/v1",
|
||||
},
|
||||
"account_scheduling_threshold": 80,
|
||||
},
|
||||
Extra: map[string]any{
|
||||
service.OllamaCloudAllowedModelsExtraKey: []string{"qwen3.5:397b"},
|
||||
service.OllamaCloudUsageSnapshotExtraKey: snapshot,
|
||||
},
|
||||
}
|
||||
|
||||
_, metaPayload, err := marshalSchedulerCacheAccount(legacyAccount)
|
||||
require.NoError(t, err)
|
||||
var projected service.Account
|
||||
require.NoError(t, json.Unmarshal(metaPayload, &projected))
|
||||
|
||||
require.Equal(t, service.AccountModeOllamaLegacy, projected.GetOllamaCloudAccountMode())
|
||||
require.Equal(t, service.APIProtocolAdaptive, projected.GetAPIProtocol())
|
||||
require.Equal(t, "https://ollama.com", projected.GetAnthropicProtocolBaseURL())
|
||||
decision := service.EvaluateAccountSchedulingThreshold(&projected, nil, now)
|
||||
require.True(t, decision.ShouldPause, "快照投影账号达到 5h 阈值时必须停调")
|
||||
|
||||
// credits 账号在投影后必须保持 ollama_credits 模式,不得退回 legacy 被窗口停调。
|
||||
creditsAccount := legacyAccount
|
||||
creditsAccount.ID = 12
|
||||
creditsAccount.Credentials = map[string]any{
|
||||
"api_key": "sk-ollama",
|
||||
"base_url": "https://ollama.com/v1",
|
||||
"account_mode": service.AccountModeOllamaCredits,
|
||||
"account_scheduling_threshold": 80,
|
||||
}
|
||||
_, creditsMeta, err := marshalSchedulerCacheAccount(creditsAccount)
|
||||
require.NoError(t, err)
|
||||
var projectedCredits service.Account
|
||||
require.NoError(t, json.Unmarshal(creditsMeta, &projectedCredits))
|
||||
require.Equal(t, service.AccountModeOllamaCredits, projectedCredits.GetOllamaCloudAccountMode())
|
||||
require.False(t, service.EvaluateAccountSchedulingThreshold(&projectedCredits, nil, now).ShouldPause)
|
||||
|
||||
// H7: Grok OAuth 配额快照(grok_usage_snapshot)必须进入投影,保证跨族池自动暂停生效。
|
||||
grokExtra := filterSchedulerExtra(map[string]any{
|
||||
"grok_usage_snapshot": map[string]any{"remaining_queries": 0},
|
||||
})
|
||||
require.Contains(t, grokExtra, "grok_usage_snapshot")
|
||||
}
|
||||
@@ -866,7 +866,7 @@ func TestAPIContracts(t *testing.T) {
|
||||
"force_email_on_third_party_signup": false,
|
||||
"default_concurrency": 5,
|
||||
"default_balance": 1.25,
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"cline":{"daily":null,"weekly":null,"monthly":null},"command_code":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"cline":{"daily":null,"weekly":null,"monthly":null},"command_code":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"auth_source_default_email_platform_quotas": null,
|
||||
"auth_source_default_github_platform_quotas": null,
|
||||
"auth_source_default_google_platform_quotas": null,
|
||||
@@ -1192,7 +1192,7 @@ func TestAPIContracts(t *testing.T) {
|
||||
"purchase_subscription_url": "",
|
||||
"table_default_page_size": 20,
|
||||
"table_page_size_options": [10, 20, 50],
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"cline":{"daily":null,"weekly":null,"monthly":null},"command_code":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"cline":{"daily":null,"weekly":null,"monthly":null},"command_code":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"auth_source_default_email_platform_quotas": null,
|
||||
"auth_source_default_github_platform_quotas": null,
|
||||
"auth_source_default_google_platform_quotas": null,
|
||||
@@ -1471,7 +1471,12 @@ func newContractDeps(t *testing.T) *contractDeps {
|
||||
apiKeyCache := stubApiKeyCache{}
|
||||
groupRepo := &stubGroupRepo{}
|
||||
userSubRepo := &stubUserSubscriptionRepo{}
|
||||
accountRepo := stubAccountRepo{}
|
||||
accountRepo := stubAccountRepo{
|
||||
accounts: map[int64]*service.Account{
|
||||
101: {ID: 101, Name: "bulk-anthropic-1", Platform: service.PlatformAnthropic, Status: service.StatusActive, Schedulable: true},
|
||||
102: {ID: 102, Name: "bulk-anthropic-2", Platform: service.PlatformAnthropic, Status: service.StatusActive, Schedulable: true},
|
||||
},
|
||||
}
|
||||
proxyRepo := stubProxyRepo{}
|
||||
redeemRepo := &stubRedeemCodeRepo{}
|
||||
|
||||
@@ -1497,7 +1502,7 @@ func newContractDeps(t *testing.T) *contractDeps {
|
||||
settingRepo := newStubSettingRepo()
|
||||
settingService := service.NewSettingService(settingRepo, cfg)
|
||||
|
||||
adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
authHandler := handler.NewAuthHandler(cfg, nil, userService, settingService, nil, redeemService, nil, nil)
|
||||
apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService)
|
||||
usageHandler := handler.NewUsageHandler(usageService, apiKeyService, nil, nil, nil)
|
||||
@@ -1871,6 +1876,7 @@ func (stubGroupRepo) CreateFromSource(ctx context.Context, group *service.Group,
|
||||
|
||||
type stubAccountRepo struct {
|
||||
bulkUpdateIDs []int64
|
||||
accounts map[int64]*service.Account
|
||||
}
|
||||
|
||||
func (s *stubAccountRepo) Create(ctx context.Context, account *service.Account) error {
|
||||
@@ -1886,7 +1892,13 @@ func (s *stubAccountRepo) GetByID(ctx context.Context, id int64) (*service.Accou
|
||||
}
|
||||
|
||||
func (s *stubAccountRepo) GetByIDs(ctx context.Context, ids []int64) ([]*service.Account, error) {
|
||||
return nil, errors.New("not implemented")
|
||||
out := make([]*service.Account, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if account, ok := s.accounts[id]; ok {
|
||||
out = append(out, account)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *stubAccountRepo) ExistsByID(ctx context.Context, id int64) (bool, error) {
|
||||
|
||||
@@ -201,7 +201,18 @@ func TestCompositeTargetPlatformMiddlewareRejectsOnlyOAuthAmbiguousOwnership(t *
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resolver := service.NewCompositeRouteResolver(nil)
|
||||
resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (service.CompositeModelOwnership, error) {
|
||||
return service.CompositeModelOwnership{Ambiguous: true, OpenAIGatewayOAuthClaimed: tc.oauthClaimed}, nil
|
||||
if tc.oauthClaimed {
|
||||
// 遗留 Ambiguous 形态(无候选池):含 OpenAI 网关族 OAuth 声明方时
|
||||
// 入口必须拒绝,不能落到默认 Anthropic handler 后再按模型名猜平台。
|
||||
return service.CompositeModelOwnership{Ambiguous: true, OpenAIGatewayOAuthClaimed: true}, nil
|
||||
}
|
||||
// composite 归属模型下 API Key 跨平台歧义是稳定候选池(Matched=true +
|
||||
// CandidatePlatforms),由统一 OpenAI 兼容选择器解析平台,入口放行且
|
||||
// 不在此解析单平台。
|
||||
return service.CompositeModelOwnership{
|
||||
Matched: true,
|
||||
CandidatePlatforms: []string{service.PlatformDeepseek, service.PlatformOpenAI},
|
||||
}, nil
|
||||
})
|
||||
router := gin.New()
|
||||
router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) {
|
||||
|
||||
@@ -169,7 +169,7 @@ func (r *scopedRouteAllowlistRepository) ScopedAdminUpdateGroupModels(ctx contex
|
||||
func TestScopedAdminRegisteredGroupModelsUseUpstreamAllowlistSemantics(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
repo := &scopedRouteAllowlistRepository{}
|
||||
api := service.NewAdminService(nil, nil, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
api := service.NewAdminService(nil, nil, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
settings := service.NewSettingService(nil, nil)
|
||||
settings.SetScopedAdminKeyRepository(&scopedRouteKeys{})
|
||||
key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "白名单验证", Enabled: true, Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"groups.models.read", "groups.models.write"}, GroupIDs: []int64{2}, Platforms: []string{service.PlatformOpenAI}}}}}, 9)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
@@ -65,19 +66,10 @@ func RegisterGatewayRoutes(
|
||||
// 合成路由改写之前,白名单的拒绝响应保持不变。
|
||||
rejectConflictingFields := middleware.RejectConflictingRequestFields()
|
||||
|
||||
isOpenAIResponsesCompatibleGatewayPlatform := func(c *gin.Context) bool {
|
||||
// openai、grok 与多协议 API Key 供应商经 OpenAI 网关转发(平台清单)。
|
||||
return domain.UsesOpenAIGateway(getGroupPlatform(c))
|
||||
}
|
||||
// 单目标与账号池统一走 dispatcher:池候选全属 OpenAI 兼容族进 OpenAI
|
||||
// CountTokens,其余(跨族池 / 非兼容族单目标)落通用网关。
|
||||
countTokensHandler := func(c *gin.Context) {
|
||||
switch platform := getGroupPlatform(c); {
|
||||
case platform == service.PlatformGrok:
|
||||
h.OpenAIGateway.GrokCountTokens(c)
|
||||
case domain.UsesOpenAIGateway(platform):
|
||||
h.OpenAIGateway.CountTokens(c)
|
||||
default:
|
||||
h.Gateway.CountTokens(c)
|
||||
}
|
||||
dispatchOpenAICompatibleCountTokens(c, h.OpenAIGateway.CountTokens, h.OpenAIGateway.GrokCountTokens, h.Gateway.CountTokens)
|
||||
}
|
||||
codexModelsHandler := func(c *gin.Context) {
|
||||
dispatchCodexModelsGateway(c, h.OpenAIGateway.CodexModels, h.Gateway.CodexModels)
|
||||
@@ -189,8 +181,18 @@ func RegisterGatewayRoutes(
|
||||
})
|
||||
return
|
||||
}
|
||||
if service.IsOpenAIResponsesInputTokensRequestPath(c) && isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.ResponsesInputTokens(c)
|
||||
if service.IsOpenAIResponsesInputTokensRequestPath(c) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.ResponsesInputTokens(c)
|
||||
return
|
||||
}
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{
|
||||
"error": gin.H{
|
||||
"type": "not_found_error",
|
||||
"message": "Responses input_tokens is not supported for this platform",
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
next(c)
|
||||
@@ -212,11 +214,7 @@ func RegisterGatewayRoutes(
|
||||
{
|
||||
// /v1/messages: auto-route based on group platform
|
||||
gateway.POST("/messages", func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.Messages(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.Messages(c)
|
||||
dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.Messages, h.Gateway.Messages)
|
||||
})
|
||||
// System One carries only JSON text; groupBodyLimit applies the text body limit.
|
||||
gateway.POST("/systemone", h.Gateway.SystemOne)
|
||||
@@ -235,18 +233,10 @@ func RegisterGatewayRoutes(
|
||||
gateway.GET("/live/:call_id", h.OpenAIGateway.LiveSideband)
|
||||
// OpenAI Responses API: auto-route based on group platform
|
||||
gateway.POST("/responses", func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.Responses(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.Responses(c)
|
||||
dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.Responses, h.Gateway.Responses)
|
||||
})
|
||||
gateway.POST("/responses/*subpath", guardResponsesSubpath(func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.Responses(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.Responses(c)
|
||||
dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.Responses, h.Gateway.Responses)
|
||||
}))
|
||||
gateway.POST("/alpha/search", h.OpenAIGateway.AlphaSearch)
|
||||
gateway.GET("/responses", func(c *gin.Context) {
|
||||
@@ -254,11 +244,7 @@ func RegisterGatewayRoutes(
|
||||
})
|
||||
// OpenAI Chat Completions API: auto-route based on group platform
|
||||
gateway.POST("/chat/completions", func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.ChatCompletions(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.ChatCompletions(c)
|
||||
dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.ChatCompletions, h.Gateway.ChatCompletions)
|
||||
})
|
||||
gateway.POST("/embeddings", func(c *gin.Context) {
|
||||
if !isOpenAIOnlyEndpointGatewayPlatform(c) {
|
||||
@@ -383,11 +369,7 @@ func RegisterGatewayRoutes(
|
||||
|
||||
// OpenAI Responses API(不带v1前缀的别名)— auto-route based on group platform
|
||||
responsesHandler := func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.Responses(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.Responses(c)
|
||||
dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.Responses, h.Gateway.Responses)
|
||||
}
|
||||
// 根路径别名共用中间件链:白名单准入在 apiKeyAuth 之后、compositeTarget
|
||||
// 之前,避免逐条路由手工维护链导致漏挂。
|
||||
@@ -423,11 +405,7 @@ func RegisterGatewayRoutes(
|
||||
}
|
||||
// OpenAI Chat Completions API(不带v1前缀的别名)— auto-route based on group platform
|
||||
rootRoute(http.MethodPost, "/chat/completions", bodyLimit, func(c *gin.Context) {
|
||||
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
|
||||
h.OpenAIGateway.ChatCompletions(c)
|
||||
return
|
||||
}
|
||||
h.Gateway.ChatCompletions(c)
|
||||
dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.ChatCompletions, h.Gateway.ChatCompletions)
|
||||
})
|
||||
rootRoute(http.MethodPost, "/embeddings", textBodyLimit, func(c *gin.Context) {
|
||||
if !isOpenAIOnlyEndpointGatewayPlatform(c) {
|
||||
@@ -572,6 +550,112 @@ func getGroupPlatform(c *gin.Context) string {
|
||||
return apiKey.Group.Platform
|
||||
}
|
||||
|
||||
// isOpenAICompatibleGatewayFamilyPlatform 报告单个平台是否经 OpenAI 网关转发
|
||||
// (openai、grok 与多协议 API Key 供应商,见平台清单)。
|
||||
func isOpenAICompatibleGatewayFamilyPlatform(platform string) bool {
|
||||
return domain.UsesOpenAIGateway(platform)
|
||||
}
|
||||
|
||||
// compositePoolCandidatePlatforms 返回 composite 账号池请求的候选平台集合;
|
||||
// 非池请求(未写池候选)返回 false。与 service pool 语义一致:已有明确
|
||||
// resolved endpoint pin(如 Gemini fallback、显式 single 决策)时按 single
|
||||
// 处理——候选数据保留在 ctx 但不作为活跃池。
|
||||
func compositePoolCandidatePlatforms(c *gin.Context) ([]string, bool) {
|
||||
if c == nil || c.Request == nil {
|
||||
return nil, false
|
||||
}
|
||||
if _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()); resolved {
|
||||
return nil, false
|
||||
}
|
||||
candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context())
|
||||
if len(candidates) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
return candidates, true
|
||||
}
|
||||
|
||||
// writeCompositeRouteAdmissionError 按实际入站 endpoint 选择错误信封:
|
||||
// messages 系列(Anthropic 协议入口)沿用 {"type":"error","error":{...}},
|
||||
// 其余 OpenAI 端点沿用 {"error":{...}},随后 Abort。
|
||||
func writeCompositeRouteAdmissionError(c *gin.Context, status int, message string) {
|
||||
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
|
||||
envelope := gin.H{"error": gin.H{"type": "invalid_request_error", "message": message}}
|
||||
if c.Request != nil && c.Request.URL != nil && strings.Contains(c.Request.URL.Path, "/messages") {
|
||||
envelope = gin.H{"type": "error", "error": gin.H{"type": "invalid_request_error", "message": message}}
|
||||
}
|
||||
c.JSON(status, envelope)
|
||||
c.Abort()
|
||||
}
|
||||
|
||||
// isCompositeOpenAIFamilyPool 报告账号池候选是否全部属于 OpenAI 兼容族。
|
||||
// 池的 handler 家族只由族归属决定,与池大小无关。
|
||||
func isCompositeOpenAIFamilyPool(candidates []string) bool {
|
||||
if len(candidates) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, platform := range candidates {
|
||||
if !isOpenAICompatibleGatewayFamilyPlatform(platform) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// isOpenAIResponsesCompatibleGatewayPlatform 报告请求是否应进入 OpenAI 兼容族
|
||||
// handler。账号池请求没有单一目标平台:池候选全部属于兼容族才进入,混入其他
|
||||
// 族的池返回 false 落通用网关(generic handler 按选中账号的协议能力分发,
|
||||
// 不再显式拒绝),不允许按池大小或猜测选族。
|
||||
func isOpenAIResponsesCompatibleGatewayPlatform(c *gin.Context) bool {
|
||||
if candidates, ok := compositePoolCandidatePlatforms(c); ok {
|
||||
return isCompositeOpenAIFamilyPool(candidates)
|
||||
}
|
||||
return isOpenAICompatibleGatewayFamilyPlatform(getGroupPlatform(c))
|
||||
}
|
||||
|
||||
// dispatchOpenAICompatibleGateway 把文本端点(messages/responses/chat
|
||||
// completions)路由进 OpenAI 兼容族:账号池候选全部属于兼容族 → OpenAI 网关;
|
||||
// 其余(跨族池 / 全原生协议族池)落通用网关——generic handler 在池激活时按
|
||||
// 选中账号的协议能力分发转发,不信任「一定有 anthropic 能力」;单目标沿用
|
||||
// 既有族判断落通用网关。
|
||||
func dispatchOpenAICompatibleGateway(c *gin.Context, openAIHandler, genericHandler gin.HandlerFunc) {
|
||||
if candidates, ok := compositePoolCandidatePlatforms(c); ok {
|
||||
if isCompositeOpenAIFamilyPool(candidates) {
|
||||
openAIHandler(c)
|
||||
return
|
||||
}
|
||||
genericHandler(c)
|
||||
return
|
||||
}
|
||||
if isOpenAICompatibleGatewayFamilyPlatform(getGroupPlatform(c)) {
|
||||
openAIHandler(c)
|
||||
return
|
||||
}
|
||||
genericHandler(c)
|
||||
}
|
||||
|
||||
// dispatchOpenAICompatibleCountTokens 沿用 count_tokens 的既有语义:openai 与
|
||||
// 国产兼容供应商走 OpenAI CountTokens,grok 走本地估算;账号池候选全部属于
|
||||
// 兼容族时进入 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
|
||||
}
|
||||
genericHandler(c)
|
||||
return
|
||||
}
|
||||
switch platform := getGroupPlatform(c); {
|
||||
case platform == service.PlatformGrok:
|
||||
grokHandler(c)
|
||||
case isOpenAICompatibleGatewayFamilyPlatform(platform):
|
||||
compatibleHandler(c)
|
||||
default:
|
||||
genericHandler(c)
|
||||
}
|
||||
}
|
||||
|
||||
func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) gin.HandlerFunc {
|
||||
if resolver == nil {
|
||||
resolver = service.NewCompositeRouteResolver(nil)
|
||||
@@ -615,12 +699,50 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver)
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": gin.H{"type": "invalid_request_error", "message": decision.AmbiguousMessage()}})
|
||||
return
|
||||
}
|
||||
if decision.Matched {
|
||||
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
|
||||
if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) {
|
||||
if _, modelPath := requestmodel.JSONModelPathForRoute(routePath, body); modelPath != "" {
|
||||
body = service.RewriteCompositeRequestModel(body, modelPath, upstreamModel)
|
||||
}
|
||||
if !decision.Matched {
|
||||
if !compositeRouteResolutionRequired(c.Request.URL.Path) {
|
||||
// 非文本端点(Seedance 任务、媒体等)由 handler 按自身平台语义处理。
|
||||
requestmodel.ResetRequestBody(c.Request, body)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
// 文本端点的模型既无显式路由、也无账号映射/候选池可归入具体平台:
|
||||
// 继续放行只会落到通用网关并按通用协议报错。对 composite 在入口明确
|
||||
// 以请求错误拒绝(带模型名与原因),信封按入站 endpoint 协议选择。
|
||||
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q cannot be resolved to any platform in this composite group (%s)", model, decision.Reason))
|
||||
return
|
||||
}
|
||||
if isCompositePoolResponsesContinuation(c, decision, body) {
|
||||
// 续链绑定只由 OpenAI 网关链创建,归属账号必然属于 OpenAI 兼容族:候选池收窄到
|
||||
// 兼容族后由 OpenAI handler 按归属账号钉住与守卫,避免跨族池选到无该响应状态的
|
||||
// 账号(静默丢失上下文或跨租户续链)。
|
||||
decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms)
|
||||
if len(decision.CandidatePlatforms) == 0 {
|
||||
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to continue previous_response_id; resend the full conversation without previous_response_id", model))
|
||||
return
|
||||
}
|
||||
} else if isCompositePoolResponsesCompact(c, decision, body) {
|
||||
// /responses/compact(含裸 /responses 的 compaction_trigger v1/v2)仅由 OpenAI 网关链
|
||||
// 支持(含 compact 归一化、渠道限制与心跳):跨族候选池收窄到 OpenAI 兼容族,
|
||||
// 避免落入通用网关按普通 Responses 误转协议。
|
||||
decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms)
|
||||
if len(decision.CandidatePlatforms) == 0 {
|
||||
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to support /responses/compact", model))
|
||||
return
|
||||
}
|
||||
} else if isCompositePoolResponsesInputTokens(c, decision) {
|
||||
// /responses/input_tokens 为免计费 token 预检端点,仅由 OpenAI 网关链支持:
|
||||
// 跨族候选池收窄到 OpenAI 兼容族,防止落入通用网关触发真实推理并扣费。
|
||||
decision.CandidatePlatforms = openAICompatibleCandidatePlatforms(decision.CandidatePlatforms)
|
||||
if len(decision.CandidatePlatforms) == 0 {
|
||||
writeCompositeRouteAdmissionError(c, http.StatusBadRequest, fmt.Sprintf("Model %q has no OpenAI-compatible account in this composite group to support /responses/input_tokens", model))
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
|
||||
if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) {
|
||||
if _, modelPath := requestmodel.JSONModelPathForRoute(routePath, body); modelPath != "" {
|
||||
body = service.RewriteCompositeRequestModel(body, modelPath, upstreamModel)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -689,6 +811,64 @@ func compositeGeminiModelFromParams(c *gin.Context) string {
|
||||
return modelAction
|
||||
}
|
||||
|
||||
// isCompositePoolResponsesContinuation 报告请求是否为 composite 账号池上的 Responses
|
||||
// 续链(带 previous_response_id)。
|
||||
func isCompositePoolResponsesContinuation(c *gin.Context, decision service.CompositeRouteDecision, body []byte) bool {
|
||||
if c == nil || c.Request == nil || c.Request.URL == nil || !strings.Contains(c.Request.URL.Path, "/responses") {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(decision.TargetPlatform) != "" || len(decision.CandidatePlatforms) == 0 {
|
||||
return false
|
||||
}
|
||||
return strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) != ""
|
||||
}
|
||||
|
||||
func isCompositePoolResponsesCompact(c *gin.Context, decision service.CompositeRouteDecision, body []byte) bool {
|
||||
if c == nil || c.Request == nil || c.Request.URL == nil {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(decision.TargetPlatform) != "" || len(decision.CandidatePlatforms) == 0 {
|
||||
return false
|
||||
}
|
||||
path := strings.TrimRight(c.Request.URL.Path, "/")
|
||||
if strings.HasSuffix(path, "/responses/compact") {
|
||||
return true
|
||||
}
|
||||
if path == "/v1/responses" || path == "/responses" || path == "/backend-api/codex/responses" {
|
||||
return service.HasCompactionTriggerInInput(body)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isCompositePoolResponsesInputTokens(c *gin.Context, decision service.CompositeRouteDecision) bool {
|
||||
if c == nil || c.Request == nil || c.Request.URL == nil {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(decision.TargetPlatform) != "" || len(decision.CandidatePlatforms) == 0 {
|
||||
return false
|
||||
}
|
||||
return service.IsOpenAIResponsesInputTokensRequestPath(c)
|
||||
}
|
||||
|
||||
// openAICompatibleCandidatePlatforms 返回候选平台中经 OpenAI 网关转发的平台(保持顺序)。
|
||||
func openAICompatibleCandidatePlatforms(candidates []string) []string {
|
||||
out := make([]string, 0, len(candidates))
|
||||
for _, platform := range candidates {
|
||||
if isOpenAICompatibleGatewayFamilyPlatform(platform) {
|
||||
out = append(out, platform)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// compositeRouteResolutionRequired 报告 composite 未解析的模型是否必须在入口拒绝:
|
||||
// 文本端点放行后会被 handler 的 detector 折叠成单平台或落到通用网关错发协议。
|
||||
func compositeRouteResolutionRequired(path string) bool {
|
||||
return strings.Contains(path, "/messages") ||
|
||||
strings.Contains(path, "/responses") ||
|
||||
strings.Contains(path, "/chat/completions")
|
||||
}
|
||||
|
||||
func compositeRouteEndpointForPath(path string) string {
|
||||
switch {
|
||||
case strings.Contains(path, "/messages/count_tokens"):
|
||||
|
||||
@@ -0,0 +1,518 @@
|
||||
//go:build unit
|
||||
|
||||
package routes
|
||||
|
||||
// RED 回归测试(feature/composite-cross-platform-scheduling)。
|
||||
//
|
||||
// 已知故障:composite 分组中同一公开模型被多个不同平台的 group-bound 账号
|
||||
// 同时声明(各有账号级 model_mapping),且未配置显式 composite route 时,
|
||||
// CompositeRouteResolver.Resolve 命中 ownership.Ambiguous 后直接返回
|
||||
// Matched=false(不再回落 DetectModelPlatform)。中间件因此不写入
|
||||
// ResolvedTargetPlatform,routes 层的 isOpenAIResponsesCompatibleGatewayPlatform
|
||||
// 判定失败,把 POST /v1/chat/completions 误分发给通用 Anthropic 网关
|
||||
// handler(h.Gateway.ChatCompletions)。该 handler 走 CC→Responses→Anthropic
|
||||
// 桥接,出站请求被拼成 {base_url}/v1/messages?beta=true——当账号 base_url
|
||||
// 以 /v1 结尾时即为 /v1/v1/messages。
|
||||
//
|
||||
// 期望行为(待实现修绿):该场景应统一进入 OpenAI 兼容网关 handler,由其
|
||||
// 现有 selector 在跨平台候选池中选号;无论选中哪个账号,出站都必须是
|
||||
// OpenAI Chat Completions 转发({base_url}/chat/completions,base 以 /v1
|
||||
// 结尾时不得重复拼版本段),且 body.model 为选中账号 model_mapping 映射后
|
||||
// 的上游模型。
|
||||
//
|
||||
// 链路真实性:本测试经 RegisterGatewayRoutes 挂载真实中间件链
|
||||
// (bodyLimit→apiKeyAuth→groupModelAllowlist→compositeTarget→…→handler 分发),
|
||||
// composite 中间件持有与 GatewayService 真实 resolveCompositeModelOwnership
|
||||
// 绑定的 CompositeRouteResolver;两条 handler 分支都是真实 handler
|
||||
// (GatewayHandler + OpenAIGatewayHandler),账号与分组通过
|
||||
// RegisterGatewayRoutes 生产同款注入方式放置。出站经 HTTPUpstream 桩捕获,
|
||||
// 不发起任何真实网络请求。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
servermiddleware "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"
|
||||
)
|
||||
|
||||
const (
|
||||
compositeDispatchGroupID = int64(4101)
|
||||
compositeDispatchDeepseekID = int64(4111)
|
||||
compositeDispatchOpenCodeID = int64(4112)
|
||||
|
||||
compositeDispatchDeepseekBase = "https://deepseek-composite-fake.test/v1"
|
||||
compositeDispatchOpenCodeBase = "https://opencode-composite-fake.test/v1"
|
||||
|
||||
// compositeDispatchPublicModel 是两个平台账号同时声明(各自 model_mapping
|
||||
// 的 key)的公开模型名,命中内置 detector 的 deepseek- 前缀,因此歧义
|
||||
// 只能由账号归属判断暴露。
|
||||
compositeDispatchPublicModel = "deepseek-flash"
|
||||
)
|
||||
|
||||
// compositeDispatchUpstream 捕获两条网关服务(通用 + OpenAI 兼容)的全部出站。
|
||||
type compositeDispatchUpstream struct {
|
||||
service.HTTPUpstream
|
||||
|
||||
mu sync.Mutex
|
||||
captured []compositeDispatchCapturedRequest
|
||||
}
|
||||
|
||||
type compositeDispatchCapturedRequest struct {
|
||||
accountID int64
|
||||
url string
|
||||
path string
|
||||
host string
|
||||
model string
|
||||
}
|
||||
|
||||
func (u *compositeDispatchUpstream) record(req *http.Request, accountID int64) {
|
||||
var body []byte
|
||||
if req.Body != nil {
|
||||
body, _ = io.ReadAll(req.Body)
|
||||
}
|
||||
captured := compositeDispatchCapturedRequest{
|
||||
accountID: accountID,
|
||||
url: req.URL.String(),
|
||||
path: req.URL.Path,
|
||||
host: req.URL.Hostname(),
|
||||
model: gjson.GetBytes(body, "model").String(),
|
||||
}
|
||||
u.mu.Lock()
|
||||
u.captured = append(u.captured, captured)
|
||||
u.mu.Unlock()
|
||||
}
|
||||
|
||||
func (u *compositeDispatchUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
|
||||
u.record(req, accountID)
|
||||
return u.respond(req), nil
|
||||
}
|
||||
|
||||
func (u *compositeDispatchUpstream) DoWithTLS(req *http.Request, _ string, accountID int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
u.record(req, accountID)
|
||||
return u.respond(req), nil
|
||||
}
|
||||
|
||||
// respond 按出站 path 返回最小可解析响应:CC 路径回最小 CC JSON;其他路径
|
||||
// (即错误分发的 Anthropic 桥)回最小 Anthropic SSE,让两条链路都能完整走完,
|
||||
// 避免把 RED 失败变成 failover 风暴或解析 panic。
|
||||
func (u *compositeDispatchUpstream) respond(req *http.Request) *http.Response {
|
||||
if strings.HasSuffix(req.URL.Path, "/chat/completions") {
|
||||
return compositeDispatchResponse("application/json", `{"id":"chatcmpl-red","object":"chat.completion","model":"deepseek-flash","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
|
||||
}
|
||||
sse := "event: message_start\n" +
|
||||
`data: {"type":"message_start","message":{"id":"msg-red","type":"message","role":"assistant","model":"deepseek-flash","content":[],"stop_reason":null,"usage":{"input_tokens":1,"output_tokens":1}}}` + "\n\n" +
|
||||
"event: message_delta\n" +
|
||||
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}` + "\n\n" +
|
||||
"event: message_stop\n" +
|
||||
`data: {"type":"message_stop"}` + "\n\n"
|
||||
return compositeDispatchResponse("text/event-stream", sse)
|
||||
}
|
||||
|
||||
func compositeDispatchResponse(contentType, body string) *http.Response {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{contentType}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}
|
||||
}
|
||||
|
||||
func (u *compositeDispatchUpstream) snapshot() []compositeDispatchCapturedRequest {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
return append([]compositeDispatchCapturedRequest(nil), u.captured...)
|
||||
}
|
||||
|
||||
// compositeDispatchAccountRepo 提供 deepseek + opencode_go 两个可调度账号。
|
||||
type compositeDispatchAccountRepo struct {
|
||||
service.AccountRepository
|
||||
accounts []service.Account
|
||||
}
|
||||
|
||||
func cloneCompositeDispatchAccounts(accounts []service.Account) []service.Account {
|
||||
out := make([]service.Account, 0, len(accounts))
|
||||
for _, account := range accounts {
|
||||
copy := account
|
||||
credentials := make(map[string]any, len(account.Credentials))
|
||||
for key, value := range account.Credentials {
|
||||
credentials[key] = value
|
||||
}
|
||||
copy.Credentials = credentials
|
||||
out = append(out, copy)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *compositeDispatchAccountRepo) schedulable() []service.Account {
|
||||
out := make([]service.Account, 0, len(r.accounts))
|
||||
for _, account := range r.accounts {
|
||||
if account.IsSchedulable() {
|
||||
out = append(out, account)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *compositeDispatchAccountRepo) GetByID(_ context.Context, id int64) (*service.Account, error) {
|
||||
for _, account := range r.accounts {
|
||||
if account.ID == id {
|
||||
copy := account
|
||||
return ©, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (r *compositeDispatchAccountRepo) GetByIDs(_ context.Context, ids []int64) ([]*service.Account, error) {
|
||||
out := make([]*service.Account, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if account, err := r.GetByID(context.Background(), id); err == nil && account != nil {
|
||||
out = append(out, account)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *compositeDispatchAccountRepo) ListSchedulable(context.Context) ([]service.Account, error) {
|
||||
return cloneCompositeDispatchAccounts(r.schedulable()), nil
|
||||
}
|
||||
|
||||
func (r *compositeDispatchAccountRepo) ListSchedulableByGroupID(_ context.Context, groupID int64) ([]service.Account, error) {
|
||||
out := make([]service.Account, 0)
|
||||
for _, account := range r.schedulable() {
|
||||
for _, id := range account.GroupIDs {
|
||||
if id == groupID {
|
||||
out = append(out, account)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return cloneCompositeDispatchAccounts(out), nil
|
||||
}
|
||||
|
||||
func (r *compositeDispatchAccountRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]service.Account, error) {
|
||||
out := make([]service.Account, 0)
|
||||
for _, account := range r.schedulable() {
|
||||
if account.Platform == platform {
|
||||
out = append(out, account)
|
||||
}
|
||||
}
|
||||
return cloneCompositeDispatchAccounts(out), nil
|
||||
}
|
||||
|
||||
func (r *compositeDispatchAccountRepo) ListSchedulableByGroupIDAndPlatform(_ context.Context, groupID int64, platform string) ([]service.Account, error) {
|
||||
out := make([]service.Account, 0)
|
||||
for _, account := range r.schedulable() {
|
||||
if account.Platform != platform {
|
||||
continue
|
||||
}
|
||||
for _, id := range account.GroupIDs {
|
||||
if id == groupID {
|
||||
out = append(out, account)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return cloneCompositeDispatchAccounts(out), nil
|
||||
}
|
||||
|
||||
func (r *compositeDispatchAccountRepo) ListSchedulableUngroupedByPlatform(_ context.Context, platform string) ([]service.Account, error) {
|
||||
return r.ListSchedulableByPlatform(context.Background(), platform)
|
||||
}
|
||||
|
||||
func (r *compositeDispatchAccountRepo) ListSchedulableByPlatforms(_ context.Context, platforms []string) ([]service.Account, error) {
|
||||
out := make([]service.Account, 0)
|
||||
for _, account := range r.schedulable() {
|
||||
for _, platform := range platforms {
|
||||
if account.Platform == platform {
|
||||
out = append(out, account)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return cloneCompositeDispatchAccounts(out), nil
|
||||
}
|
||||
|
||||
func (r *compositeDispatchAccountRepo) ListSchedulableByGroupIDAndPlatforms(_ context.Context, groupID int64, platforms []string) ([]service.Account, error) {
|
||||
out := make([]service.Account, 0)
|
||||
for _, account := range r.schedulable() {
|
||||
matchedPlatform := false
|
||||
for _, platform := range platforms {
|
||||
if account.Platform == platform {
|
||||
matchedPlatform = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matchedPlatform {
|
||||
continue
|
||||
}
|
||||
for _, id := range account.GroupIDs {
|
||||
if id == groupID {
|
||||
out = append(out, account)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return cloneCompositeDispatchAccounts(out), nil
|
||||
}
|
||||
|
||||
func (r *compositeDispatchAccountRepo) ListSchedulableUngroupedByPlatforms(_ context.Context, platforms []string) ([]service.Account, error) {
|
||||
return r.ListSchedulableByPlatforms(context.Background(), platforms)
|
||||
}
|
||||
|
||||
// ListModelAvailabilityCandidates 对齐接口语义:仅按持久化配置(active +
|
||||
// schedulable)返回候选,不做瞬态运行时过滤;groupID 为 nil 时 includeGrouped
|
||||
// 决定扫全量还是仅未分组账号。WIP 的 resolveCompositeModelOwnership 经此查询
|
||||
// composite 账号归属。
|
||||
func (r *compositeDispatchAccountRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, includeGrouped bool) ([]service.Account, error) {
|
||||
out := make([]service.Account, 0)
|
||||
for _, account := range r.schedulable() {
|
||||
if len(platforms) > 0 {
|
||||
matchedPlatform := false
|
||||
for _, platform := range platforms {
|
||||
if account.Platform == platform {
|
||||
matchedPlatform = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matchedPlatform {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if groupID == nil && !includeGrouped && len(account.GroupIDs) > 0 {
|
||||
continue
|
||||
}
|
||||
if groupID != nil {
|
||||
inGroup := false
|
||||
for _, id := range account.GroupIDs {
|
||||
if id == *groupID {
|
||||
inGroup = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !inGroup {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out = append(out, account)
|
||||
}
|
||||
return cloneCompositeDispatchAccounts(out), nil
|
||||
}
|
||||
|
||||
// compositeDispatchGroupRepo 满足通用调度器 resolveGatewayGroup 的分组读取。
|
||||
type compositeDispatchGroupRepo struct {
|
||||
service.GroupRepository
|
||||
group *service.Group
|
||||
}
|
||||
|
||||
func (r *compositeDispatchGroupRepo) GetByID(context.Context, int64) (*service.Group, error) {
|
||||
return r.group, nil
|
||||
}
|
||||
|
||||
func (r *compositeDispatchGroupRepo) GetByIDLite(context.Context, int64) (*service.Group, error) {
|
||||
return r.group, nil
|
||||
}
|
||||
|
||||
// compositeDispatchConcurrencyCache 放行用户/账号槽位并安全释放。
|
||||
type compositeDispatchConcurrencyCache struct {
|
||||
service.ConcurrencyCache
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) AcquireUserSlot(context.Context, int64, int, string) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) ReleaseUserSlot(context.Context, int64, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) AcquireAccountSlot(context.Context, int64, int, string) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) ReleaseAccountSlot(context.Context, int64, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) GetAccountConcurrency(context.Context, int64) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) GetAccountConcurrencyBatch(_ context.Context, accountIDs []int64) (map[int64]int, error) {
|
||||
result := make(map[int64]int, len(accountIDs))
|
||||
for _, accountID := range accountIDs {
|
||||
result[accountID] = 0
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) IncrementAccountWaitCount(context.Context, int64, int) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) DecrementAccountWaitCount(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) GetAccountWaitingCount(context.Context, int64) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) IncrementWaitCount(context.Context, int64, int) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) DecrementWaitCount(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *compositeDispatchConcurrencyCache) GetUserConcurrency(context.Context, int64) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func TestCompositeAmbiguousModelChatCompletionsForwardedViaOpenAIGatewayUpstream(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
groupID := compositeDispatchGroupID
|
||||
group := &service.Group{
|
||||
ID: groupID,
|
||||
Platform: service.PlatformComposite,
|
||||
Status: service.StatusActive,
|
||||
}
|
||||
user := &service.User{ID: 4103, Status: service.StatusActive}
|
||||
apiKey := &service.APIKey{
|
||||
ID: 4102,
|
||||
GroupID: &groupID,
|
||||
User: user,
|
||||
Group: group,
|
||||
}
|
||||
|
||||
repo := &compositeDispatchAccountRepo{
|
||||
accounts: []service.Account{
|
||||
{
|
||||
ID: compositeDispatchDeepseekID, Name: "cn-deepseek",
|
||||
Platform: service.PlatformDeepseek, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 4, Priority: 1,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "test-deepseek-key",
|
||||
"base_url": compositeDispatchDeepseekBase,
|
||||
"model_mapping": map[string]any{compositeDispatchPublicModel: "deepseek-chat"},
|
||||
},
|
||||
GroupIDs: []int64{compositeDispatchGroupID},
|
||||
AccountGroups: []service.AccountGroup{{AccountID: compositeDispatchDeepseekID, GroupID: compositeDispatchGroupID, Priority: 1}},
|
||||
},
|
||||
{
|
||||
ID: compositeDispatchOpenCodeID, Name: "opencode-go",
|
||||
Platform: service.PlatformOpenCodeGo, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 4, Priority: 2,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "test-opencode-key",
|
||||
"base_url": compositeDispatchOpenCodeBase,
|
||||
"model_mapping": map[string]any{compositeDispatchPublicModel: "deepseek-v4"},
|
||||
},
|
||||
GroupIDs: []int64{compositeDispatchGroupID},
|
||||
AccountGroups: []service.AccountGroup{{AccountID: compositeDispatchOpenCodeID, GroupID: compositeDispatchGroupID, Priority: 1}},
|
||||
},
|
||||
},
|
||||
}
|
||||
groupRepo := &compositeDispatchGroupRepo{group: group}
|
||||
upstream := &compositeDispatchUpstream{}
|
||||
|
||||
// 无显式 route:空 repo 的 resolver,经 NewGatewayService 绑定真实的
|
||||
// resolveCompositeModelOwnership(账号归属判定),与生产装配同构。
|
||||
compositeResolver := service.NewCompositeRouteResolver(nil)
|
||||
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
cfg.Gateway.MaxBodySize = 1024 * 1024
|
||||
cfg.Gateway.TextMaxBodySize = 1024 * 1024
|
||||
cfg.Gateway.MaxAccountSwitches = 3
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
|
||||
billingService := service.NewBillingService(cfg, nil)
|
||||
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
concurrencyService := service.NewConcurrencyService(&compositeDispatchConcurrencyCache{})
|
||||
deferred := &service.DeferredService{}
|
||||
|
||||
genericGateway := service.NewGatewayService(
|
||||
repo, groupRepo, nil, nil, nil, nil, nil, nil, cfg, nil,
|
||||
concurrencyService, billingService, nil, billingCache, nil,
|
||||
upstream, deferred, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
compositeResolver, nil, nil,
|
||||
)
|
||||
openAIGateway := service.NewOpenAIGatewayService(
|
||||
repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil,
|
||||
billingService, nil, billingCache, upstream, deferred,
|
||||
nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
|
||||
handlers := &handler.Handlers{
|
||||
Gateway: handler.NewGatewayHandler(
|
||||
genericGateway, nil, nil, nil, nil,
|
||||
concurrencyService, billingCache, nil, nil, nil, nil, nil, nil,
|
||||
cfg, nil,
|
||||
),
|
||||
OpenAIGateway: handler.NewOpenAIGatewayHandler(
|
||||
openAIGateway, concurrencyService, billingCache, &service.APIKeyService{},
|
||||
nil, nil, nil, nil, cfg,
|
||||
),
|
||||
AsyncImage: handler.NewAsyncImageHandler(nil, nil),
|
||||
}
|
||||
|
||||
router := gin.New()
|
||||
RegisterGatewayRoutes(
|
||||
router,
|
||||
handlers,
|
||||
servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) {
|
||||
c.Set(string(servermiddleware.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(servermiddleware.ContextKeyUser), servermiddleware.AuthSubject{UserID: user.ID, Concurrency: 1})
|
||||
c.Next()
|
||||
}),
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
compositeResolver,
|
||||
cfg,
|
||||
)
|
||||
|
||||
requestBody := `{"model":"` + compositeDispatchPublicModel + `","messages":[{"role":"user","content":"hi"}],"stream":false}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
captured := upstream.snapshot()
|
||||
require.NotEmpty(t, captured,
|
||||
"composite CC request must be forwarded to an upstream, got status=%d body=%s", w.Code, w.Body.String())
|
||||
|
||||
expectedModelByHost := map[string]string{
|
||||
"deepseek-composite-fake.test": "deepseek-chat",
|
||||
"opencode-composite-fake.test": "deepseek-v4",
|
||||
}
|
||||
for _, request := range captured {
|
||||
require.NotContainsf(t, request.path, "/messages",
|
||||
"composite chat completions must never be dispatched through the Anthropic messages bridge (account=%d url=%s model=%s)",
|
||||
request.accountID, request.url, request.model)
|
||||
// 精确相等而非后缀匹配:两个 fake base 均以 /v1 结尾,后缀匹配放得过
|
||||
// /v1/v1/chat/completions 这类重复版本段拼接。
|
||||
require.Equalf(t, "/v1/chat/completions", request.path,
|
||||
"outbound must hit the OpenAI-compatible chat completions endpoint exactly once-versioned (account=%d url=%s)", request.accountID, request.url)
|
||||
expectedModel, knownHost := expectedModelByHost[request.host]
|
||||
require.Truef(t, knownHost, "outbound must only hit the fake composite upstreams (url=%s)", request.url)
|
||||
require.Equalf(t, expectedModel, request.model,
|
||||
"outbound body.model must be the selected account's model_mapping target (account=%d url=%s)", request.accountID, request.url)
|
||||
}
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
}
|
||||
@@ -0,0 +1,877 @@
|
||||
//go:build unit
|
||||
|
||||
package routes
|
||||
|
||||
// composite 账号池 per-attempt 平台策略(审查修复增量4)的 handler 级回归:
|
||||
// 经真实 RegisterGatewayRoutes + fake upstream 验证
|
||||
// 1. 渠道限制拒绝选中平台时不发付费外呼,普通请求 mask 后换其他平台;
|
||||
// 2. 平台配额耗尽时不发往该平台,成功请求只向实际选中平台计量配额;
|
||||
// 3. RPM 每请求只按准入计一次(policy deny 重选不重复计数);
|
||||
// 4. 公开模型 → 选中平台渠道映射 → 账号 model_mapping 的顺序按 attempt 独立;
|
||||
// 5. pinned(previous_response_id 命中状态归属)请求遭配额拒绝时返回原 policy
|
||||
// 错误(429+Retry-After)、不外呼、不换账号、不删除绑定。
|
||||
// 出站经 HTTPUpstream 桩捕获,不发起真实网络请求。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
servermiddleware "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"
|
||||
)
|
||||
|
||||
const (
|
||||
attemptPolicyGroupID = int64(4330)
|
||||
attemptPolicyUserID = int64(4331)
|
||||
attemptPolicyAPIKey = int64(4332)
|
||||
)
|
||||
|
||||
// ── fakes ────────────────────────────────────────────────────────────────────
|
||||
|
||||
type attemptPolicyCapturedRequest struct {
|
||||
accountID int64
|
||||
host string
|
||||
path string
|
||||
body []byte
|
||||
}
|
||||
|
||||
// attemptPolicyUpstream 捕获出站请求并按 host 注入可配置失败。
|
||||
type attemptPolicyUpstream struct {
|
||||
service.HTTPUpstream
|
||||
|
||||
mu sync.Mutex
|
||||
captured []attemptPolicyCapturedRequest
|
||||
failHost map[string]bool
|
||||
}
|
||||
|
||||
func (u *attemptPolicyUpstream) capture(req *http.Request, accountID int64) []byte {
|
||||
var body []byte
|
||||
if req.Body != nil {
|
||||
body, _ = io.ReadAll(req.Body)
|
||||
}
|
||||
u.mu.Lock()
|
||||
u.captured = append(u.captured, attemptPolicyCapturedRequest{accountID: accountID, host: req.URL.Hostname(), path: req.URL.Path, body: body})
|
||||
u.mu.Unlock()
|
||||
return body
|
||||
}
|
||||
|
||||
func (u *attemptPolicyUpstream) snapshot() []attemptPolicyCapturedRequest {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
return append([]attemptPolicyCapturedRequest(nil), u.captured...)
|
||||
}
|
||||
|
||||
func (u *attemptPolicyUpstream) hosts() []string {
|
||||
snapshot := u.snapshot()
|
||||
hosts := make([]string, 0, len(snapshot))
|
||||
for _, item := range snapshot {
|
||||
hosts = append(hosts, item.host)
|
||||
}
|
||||
return hosts
|
||||
}
|
||||
|
||||
func (u *attemptPolicyUpstream) respondFor(req *http.Request, body []byte) *http.Response {
|
||||
if u.failHost[req.URL.Hostname()] {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusTooManyRequests,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}, "Retry-After": []string{"60"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limited"}}`)),
|
||||
}
|
||||
}
|
||||
if strings.Contains(req.URL.Path, "/responses") {
|
||||
// 原生 Responses 上游:stream=true 回最小 completed SSE;stream=false 回
|
||||
// Responses JSON 对象(含 id,供响应→账号绑定与 usage 解析)。
|
||||
if gjson.GetBytes(body, "stream").Bool() {
|
||||
sse := "event: response.completed\n" +
|
||||
`data: {"type":"response.completed","response":{"id":"resp_pin","object":"response","status":"completed","model":"deepseek-chat","output":[],"usage":{"input_tokens":200000,"output_tokens":100000,"total_tokens":300000}}}` + "\n\n"
|
||||
return compositeDispatchResponse("text/event-stream", sse)
|
||||
}
|
||||
return compositeDispatchResponse("application/json",
|
||||
`{"id":"resp_pin","object":"response","status":"completed","model":"deepseek-chat","output":[],"usage":{"input_tokens":200000,"output_tokens":100000,"total_tokens":300000}}`)
|
||||
}
|
||||
return compositeDispatchResponse("application/json", `{"id":"resp_pin","object":"chat.completion","model":"deepseek-chat","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":200000,"completion_tokens":100000,"total_tokens":300000}}`)
|
||||
}
|
||||
|
||||
func (u *attemptPolicyUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
|
||||
body := u.capture(req, accountID)
|
||||
return u.respondFor(req, body), nil
|
||||
}
|
||||
|
||||
func (u *attemptPolicyUpstream) DoWithTLS(req *http.Request, _ string, accountID int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
body := u.capture(req, accountID)
|
||||
return u.respondFor(req, body), nil
|
||||
}
|
||||
|
||||
// attemptPolicyQuotaCache 平台可感知的 user×platform 配额缓存:entries 缺席视为
|
||||
// MISS(DB fail-open 放行),incrPlatforms 记录每次配额累加的平台维度。
|
||||
type attemptPolicyQuotaCache struct {
|
||||
service.BillingCache
|
||||
|
||||
mu sync.Mutex
|
||||
entries map[string]*service.UserPlatformQuotaCacheEntry
|
||||
incrPlatform []string
|
||||
}
|
||||
|
||||
func (f *attemptPolicyQuotaCache) GetUserBalance(context.Context, int64) (float64, error) {
|
||||
return 100.0, nil
|
||||
}
|
||||
|
||||
func (f *attemptPolicyQuotaCache) InvalidateUserBalance(context.Context, int64) error { return nil }
|
||||
|
||||
func (f *attemptPolicyQuotaCache) GetUserPlatformQuotaCache(_ context.Context, _ int64, platform string) (*service.UserPlatformQuotaCacheEntry, bool, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
entry, ok := f.entries[platform]
|
||||
return entry, ok, nil
|
||||
}
|
||||
|
||||
func (f *attemptPolicyQuotaCache) SetUserPlatformQuotaCache(context.Context, int64, string, *service.UserPlatformQuotaCacheEntry, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *attemptPolicyQuotaCache) IncrUserPlatformQuotaUsageCache(_ context.Context, _ int64, platform string, _ float64, _ time.Duration, _ bool) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.incrPlatform = append(f.incrPlatform, platform)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *attemptPolicyQuotaCache) setEntry(platform string, entry *service.UserPlatformQuotaCacheEntry) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if entry == nil {
|
||||
delete(f.entries, platform)
|
||||
return
|
||||
}
|
||||
f.entries[platform] = entry
|
||||
}
|
||||
|
||||
func (f *attemptPolicyQuotaCache) incrSnapshot() []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.incrPlatform...)
|
||||
}
|
||||
|
||||
func exhaustedAttemptPolicyEntry(now time.Time) *service.UserPlatformQuotaCacheEntry {
|
||||
zero := 0.0
|
||||
return &service.UserPlatformQuotaCacheEntry{
|
||||
DailyUsageUSD: 0,
|
||||
DailyLimitUSD: &zero,
|
||||
DailyWindowStart: &now,
|
||||
SchemaVersion: service.UserPlatformQuotaCacheSchemaV1,
|
||||
}
|
||||
}
|
||||
|
||||
func allowedAttemptPolicyEntry(now time.Time) *service.UserPlatformQuotaCacheEntry {
|
||||
limit := 5.0
|
||||
return &service.UserPlatformQuotaCacheEntry{
|
||||
DailyUsageUSD: 0,
|
||||
DailyLimitUSD: &limit,
|
||||
DailyWindowStart: &now,
|
||||
SchemaVersion: service.UserPlatformQuotaCacheSchemaV1,
|
||||
}
|
||||
}
|
||||
|
||||
// attemptPolicyRPMCache 记录 RPM 递增次数:policy deny 重选不得重复计数。
|
||||
type attemptPolicyRPMCache struct {
|
||||
service.UserRPMCache
|
||||
|
||||
mu sync.Mutex
|
||||
group int
|
||||
user int
|
||||
}
|
||||
|
||||
func (f *attemptPolicyRPMCache) IncrementUserGroupRPM(context.Context, int64, int64) (int, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.group++
|
||||
return f.group, nil
|
||||
}
|
||||
|
||||
func (f *attemptPolicyRPMCache) IncrementUserRPM(context.Context, int64) (int, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.user++
|
||||
return f.user, nil
|
||||
}
|
||||
|
||||
func (f *attemptPolicyRPMCache) total() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.group + f.user
|
||||
}
|
||||
|
||||
type attemptPolicyUserRepo struct {
|
||||
service.UserRepository
|
||||
|
||||
mu sync.Mutex
|
||||
deductCalls int
|
||||
}
|
||||
|
||||
func (f *attemptPolicyUserRepo) DeductBalance(context.Context, int64, float64) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.deductCalls++
|
||||
return nil
|
||||
}
|
||||
|
||||
// attemptPolicyStickyCache 带计数器的进程内 sticky 会话缓存:验证 policy deny
|
||||
// masked 重选不会清掉原 sticky 绑定(DeleteSessionAccountID 零调用)。
|
||||
type attemptPolicyStickyCache struct {
|
||||
service.GatewayCache
|
||||
|
||||
mu sync.Mutex
|
||||
bindings map[string]int64
|
||||
setCnt int
|
||||
deleteCnt int
|
||||
}
|
||||
|
||||
func newAttemptPolicyStickyCache() *attemptPolicyStickyCache {
|
||||
return &attemptPolicyStickyCache{bindings: make(map[string]int64)}
|
||||
}
|
||||
|
||||
func (c *attemptPolicyStickyCache) GetSessionAccountID(_ context.Context, groupID int64, sessionHash string) (int64, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
id, ok := c.bindings[fmt.Sprintf("%d:%s", groupID, sessionHash)]
|
||||
if !ok {
|
||||
return 0, service.ErrStickySessionNotFound
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (c *attemptPolicyStickyCache) SetSessionAccountID(_ context.Context, groupID int64, sessionHash string, accountID int64, _ time.Duration) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.setCnt++
|
||||
c.bindings[fmt.Sprintf("%d:%s", groupID, sessionHash)] = accountID
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *attemptPolicyStickyCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *attemptPolicyStickyCache) DeleteSessionAccountID(_ context.Context, groupID int64, sessionHash string) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.deleteCnt++
|
||||
delete(c.bindings, fmt.Sprintf("%d:%s", groupID, sessionHash))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *attemptPolicyStickyCache) SetGrokVideoPendingBilling(context.Context, string, []byte, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *attemptPolicyStickyCache) GetGrokVideoPendingBilling(context.Context, string) ([]byte, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *attemptPolicyStickyCache) ClaimGrokVideoBilled(context.Context, string, time.Duration) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (c *attemptPolicyStickyCache) ReleaseGrokVideoBilled(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *attemptPolicyStickyCache) SetReasoningContent(context.Context, string, string, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *attemptPolicyStickyCache) GetReasoningContent(context.Context, string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (c *attemptPolicyStickyCache) snapshot() (map[string]int64, int, int) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
out := make(map[string]int64, len(c.bindings))
|
||||
for key, value := range c.bindings {
|
||||
out[key] = value
|
||||
}
|
||||
return out, c.setCnt, c.deleteCnt
|
||||
}
|
||||
|
||||
type attemptPolicyQuotaRepo struct {
|
||||
service.UserPlatformQuotaRepository
|
||||
}
|
||||
|
||||
func (f *attemptPolicyQuotaRepo) GetByUserPlatform(context.Context, int64, string) (*service.UserPlatformQuotaRecord, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type attemptPolicyChannelRepo struct {
|
||||
service.ChannelRepository
|
||||
channels []service.Channel
|
||||
platforms map[int64]string
|
||||
}
|
||||
|
||||
func (f *attemptPolicyChannelRepo) ListAll(context.Context) ([]service.Channel, error) {
|
||||
return f.channels, nil
|
||||
}
|
||||
|
||||
func (f *attemptPolicyChannelRepo) GetGroupPlatforms(context.Context, []int64) (map[int64]string, error) {
|
||||
return f.platforms, nil
|
||||
}
|
||||
|
||||
// ── fixtures ─────────────────────────────────────────────────────────────────
|
||||
|
||||
func newAttemptPolicyAccount(id int64, platform string, priority int, modelMapping map[string]any) service.Account {
|
||||
credentials := map[string]any{
|
||||
"api_key": "test-key-" + platform,
|
||||
"base_url": "https://" + platform + "-pool-fake.test/v1",
|
||||
}
|
||||
if modelMapping != nil {
|
||||
credentials["model_mapping"] = modelMapping
|
||||
}
|
||||
return service.Account{
|
||||
ID: id, Name: "pool-" + platform,
|
||||
Platform: platform, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 4, Priority: priority,
|
||||
Credentials: credentials,
|
||||
GroupIDs: []int64{attemptPolicyGroupID},
|
||||
AccountGroups: []service.AccountGroup{
|
||||
{AccountID: id, GroupID: attemptPolicyGroupID, Priority: 1},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type attemptPolicyRouterInput struct {
|
||||
accounts []service.Account
|
||||
quotaCache *attemptPolicyQuotaCache
|
||||
rpmCache *attemptPolicyRPMCache
|
||||
upstream *attemptPolicyUpstream
|
||||
channel *service.Channel
|
||||
userRepo *attemptPolicyUserRepo
|
||||
stickyCache *attemptPolicyStickyCache
|
||||
groupMutate func(group *service.Group)
|
||||
}
|
||||
|
||||
func newCompositePoolAttemptPolicyRouter(t *testing.T, in attemptPolicyRouterInput) *gin.Engine {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
if in.quotaCache == nil {
|
||||
in.quotaCache = &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{}}
|
||||
}
|
||||
if in.upstream == nil {
|
||||
in.upstream = &attemptPolicyUpstream{}
|
||||
}
|
||||
if in.stickyCache == nil {
|
||||
in.stickyCache = newAttemptPolicyStickyCache()
|
||||
}
|
||||
if in.userRepo == nil {
|
||||
in.userRepo = &attemptPolicyUserRepo{}
|
||||
}
|
||||
|
||||
cfg := &config.Config{RunMode: config.RunModeStandard}
|
||||
cfg.Default.RateMultiplier = 1
|
||||
cfg.Gateway.MaxBodySize = 1024 * 1024
|
||||
cfg.Gateway.TextMaxBodySize = 1024 * 1024
|
||||
cfg.Gateway.MaxAccountSwitches = 3
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
|
||||
repo := &compositeDispatchAccountRepo{accounts: in.accounts}
|
||||
group := &service.Group{
|
||||
ID: attemptPolicyGroupID,
|
||||
Platform: service.PlatformComposite,
|
||||
Status: service.StatusActive,
|
||||
RateMultiplier: 1,
|
||||
}
|
||||
if in.groupMutate != nil {
|
||||
in.groupMutate(group)
|
||||
}
|
||||
groupRepo := &compositeDispatchGroupRepo{group: group}
|
||||
|
||||
var channelSvc *service.ChannelService
|
||||
if in.channel != nil {
|
||||
channelSvc = service.NewChannelService(&attemptPolicyChannelRepo{
|
||||
channels: []service.Channel{*in.channel},
|
||||
platforms: map[int64]string{attemptPolicyGroupID: service.PlatformComposite},
|
||||
}, nil, nil, nil, nil)
|
||||
}
|
||||
|
||||
billingService := service.NewBillingService(cfg, nil)
|
||||
pricingResolver := service.NewModelPricingResolver(nil, billingService)
|
||||
billingCache := service.NewBillingCacheService(
|
||||
in.quotaCache, nil, nil, nil, in.rpmCache, nil, cfg, &attemptPolicyQuotaRepo{})
|
||||
concurrencyService := service.NewConcurrencyService(&compositeDispatchConcurrencyCache{})
|
||||
deferred := &service.DeferredService{}
|
||||
|
||||
compositeResolver := service.NewCompositeRouteResolver(nil)
|
||||
|
||||
genericGateway := service.NewGatewayService(
|
||||
repo, groupRepo, nil, nil, nil, nil, nil, nil, cfg, nil,
|
||||
concurrencyService, billingService, nil, billingCache, nil,
|
||||
in.upstream, deferred, nil, nil, nil, nil, nil, nil, channelSvc, nil,
|
||||
compositeResolver, nil, nil,
|
||||
)
|
||||
openAIGateway := service.NewOpenAIGatewayService(
|
||||
repo, nil, nil, in.userRepo, nil, nil, in.stickyCache, cfg, nil, concurrencyService,
|
||||
billingService, nil, billingCache, in.upstream, deferred,
|
||||
nil, nil, pricingResolver, channelSvc, nil, nil, &attemptPolicyQuotaRepo{},
|
||||
)
|
||||
|
||||
handlers := &handler.Handlers{
|
||||
Gateway: handler.NewGatewayHandler(
|
||||
genericGateway, nil, nil, nil, nil,
|
||||
concurrencyService, billingCache, nil, nil, nil, nil, nil, nil,
|
||||
cfg, nil,
|
||||
),
|
||||
OpenAIGateway: handler.NewOpenAIGatewayHandler(
|
||||
openAIGateway, concurrencyService, billingCache, &service.APIKeyService{},
|
||||
nil, nil, nil, nil, cfg,
|
||||
),
|
||||
AsyncImage: handler.NewAsyncImageHandler(nil, nil),
|
||||
}
|
||||
|
||||
router := gin.New()
|
||||
RegisterGatewayRoutes(
|
||||
router,
|
||||
handlers,
|
||||
servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) {
|
||||
groupID := group.ID
|
||||
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
|
||||
ID: attemptPolicyAPIKey,
|
||||
GroupID: &groupID,
|
||||
User: &service.User{ID: attemptPolicyUserID, Status: service.StatusActive},
|
||||
Group: group,
|
||||
})
|
||||
c.Set(string(servermiddleware.ContextKeyUser), servermiddleware.AuthSubject{UserID: attemptPolicyUserID, Concurrency: 1})
|
||||
c.Next()
|
||||
}),
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
compositeResolver,
|
||||
cfg,
|
||||
)
|
||||
return router
|
||||
}
|
||||
|
||||
func postAttemptPolicyRequest(t *testing.T, router *gin.Engine, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// ── 1) 渠道限制拒绝选中平台 → 不付费外呼该平台,mask 后换其他平台 ────────────
|
||||
func TestCompositePoolAttemptPolicyChannelRestrictionSwitchesPlatform(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{
|
||||
service.PlatformDeepseek: allowedAttemptPolicyEntry(now),
|
||||
service.PlatformOpenAI: allowedAttemptPolicyEntry(now),
|
||||
}}
|
||||
upstream := &attemptPolicyUpstream{}
|
||||
// 渠道只把 deepseek-flash 列入 openai 平台允许定价;deepseek 平台无任何
|
||||
// 定价行 → RestrictModels 下 deepseek 平台对该模型受限。
|
||||
channel := &service.Channel{
|
||||
ID: 1,
|
||||
Status: service.StatusActive,
|
||||
GroupIDs: []int64{attemptPolicyGroupID},
|
||||
RestrictModels: true,
|
||||
BillingModelSource: service.BillingModelSourceRequested,
|
||||
ModelPricing: []service.ChannelModelPricing{
|
||||
{Platform: service.PlatformOpenAI, Models: []string{"deepseek-flash"}},
|
||||
},
|
||||
}
|
||||
router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{
|
||||
accounts: []service.Account{
|
||||
newAttemptPolicyAccount(4333, service.PlatformDeepseek, 1, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
newAttemptPolicyAccount(4334, service.PlatformOpenAI, 2, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
},
|
||||
quotaCache: quotaCache,
|
||||
upstream: upstream,
|
||||
channel: channel,
|
||||
})
|
||||
|
||||
w := postAttemptPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"stream":false}`)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
hosts := upstream.hosts()
|
||||
require.NotEmpty(t, hosts)
|
||||
for _, host := range hosts {
|
||||
require.NotContains(t, host, "deepseek-pool-fake.test",
|
||||
"channel-restricted platform must never receive the paid request")
|
||||
require.Contains(t, host, "openai-pool-fake.test",
|
||||
"request must be served by an allowed platform")
|
||||
}
|
||||
}
|
||||
|
||||
// ── 2) 平台配额耗尽 → 不发往该平台;成功请求只对选中平台计量配额 ────────────
|
||||
func TestCompositePoolAttemptPolicyQuotaExhaustedSkipsPlatform(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{
|
||||
service.PlatformOpenAI: exhaustedAttemptPolicyEntry(now),
|
||||
service.PlatformDeepseek: allowedAttemptPolicyEntry(now),
|
||||
}}
|
||||
upstream := &attemptPolicyUpstream{}
|
||||
userRepo := &attemptPolicyUserRepo{}
|
||||
router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{
|
||||
accounts: []service.Account{
|
||||
newAttemptPolicyAccount(4333, service.PlatformOpenAI, 1, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
newAttemptPolicyAccount(4334, service.PlatformDeepseek, 2, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
},
|
||||
quotaCache: quotaCache,
|
||||
upstream: upstream,
|
||||
userRepo: userRepo,
|
||||
})
|
||||
|
||||
w := postAttemptPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"stream":false}`)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
for _, host := range upstream.hosts() {
|
||||
require.NotContains(t, host, "openai-pool-fake.test",
|
||||
"quota-exhausted platform must not receive the request")
|
||||
}
|
||||
require.NotEmpty(t, upstream.hosts(), "request must still be served by the healthy platform")
|
||||
|
||||
incremented := quotaCache.incrSnapshot()
|
||||
require.NotEmpty(t, incremented, "successful usage must increment the user×platform quota")
|
||||
for _, platform := range incremented {
|
||||
require.Equal(t, service.PlatformDeepseek, platform,
|
||||
"quota must be deducted on the actually selected platform, never composite/openai default")
|
||||
}
|
||||
}
|
||||
|
||||
// ── 3) RPM 只按准入计一次(policy deny 重选不重复计数) ───────────────────────
|
||||
func TestCompositePoolAttemptPolicyDenyDoesNotDoubleCountRPM(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{
|
||||
service.PlatformDeepseek: allowedAttemptPolicyEntry(now),
|
||||
service.PlatformOpenAI: allowedAttemptPolicyEntry(now),
|
||||
}}
|
||||
rpmCache := &attemptPolicyRPMCache{}
|
||||
upstream := &attemptPolicyUpstream{}
|
||||
channel := &service.Channel{
|
||||
ID: 1,
|
||||
Status: service.StatusActive,
|
||||
GroupIDs: []int64{attemptPolicyGroupID},
|
||||
RestrictModels: true,
|
||||
BillingModelSource: service.BillingModelSourceRequested,
|
||||
ModelPricing: []service.ChannelModelPricing{
|
||||
{Platform: service.PlatformOpenAI, Models: []string{"deepseek-flash"}},
|
||||
},
|
||||
}
|
||||
router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{
|
||||
accounts: []service.Account{
|
||||
newAttemptPolicyAccount(4333, service.PlatformDeepseek, 1, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
newAttemptPolicyAccount(4334, service.PlatformOpenAI, 2, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
},
|
||||
quotaCache: quotaCache,
|
||||
rpmCache: rpmCache,
|
||||
upstream: upstream,
|
||||
channel: channel,
|
||||
groupMutate: func(group *service.Group) { group.RPMLimit = 10 },
|
||||
})
|
||||
|
||||
w := postAttemptPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"stream":false}`)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
require.Len(t, upstream.hosts(), 1, "failover via policy mask must end in exactly one paid attempt")
|
||||
require.Equal(t, 1, rpmCache.total(),
|
||||
"RPM must be counted once at admission; policy deny re-selection must not re-run CheckBillingEligibility")
|
||||
}
|
||||
|
||||
// ── 4) 公开模型 → 选中平台渠道映射 → 账号 mapping,按 attempt 独立 ───────────
|
||||
func TestCompositePoolAttemptPolicyMappingOrderPerAttempt(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{
|
||||
service.PlatformDeepseek: allowedAttemptPolicyEntry(now),
|
||||
service.PlatformOpenAI: allowedAttemptPolicyEntry(now),
|
||||
}}
|
||||
upstream := &attemptPolicyUpstream{failHost: map[string]bool{"deepseek-pool-fake.test": true}}
|
||||
// 渠道映射只配置在 openai 平台行:deepseek-flash → deepseek-pro。
|
||||
channel := &service.Channel{
|
||||
ID: 1,
|
||||
Status: service.StatusActive,
|
||||
GroupIDs: []int64{attemptPolicyGroupID},
|
||||
BillingModelSource: service.BillingModelSourceRequested,
|
||||
ModelMapping: map[string]map[string]string{
|
||||
service.PlatformOpenAI: {"deepseek-flash": "deepseek-pro"},
|
||||
},
|
||||
}
|
||||
router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{
|
||||
accounts: []service.Account{
|
||||
// deepseek 账号首跳上游失败 → failover;其账号映射 deepseek-flash→deepseek-chat。
|
||||
newAttemptPolicyAccount(4333, service.PlatformDeepseek, 1, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
// openai 账号在渠道映射结果上再套账号映射 deepseek-pro→deepseek-final;
|
||||
// identity key 保留 deepseek-flash 以通过池 claims 能力门。公开模型若
|
||||
// 被错误地先做账号映射会得到 "account-direct"(渠道行无该映射,保持
|
||||
// 原样),与正确顺序的 "deepseek-final" 可判别。
|
||||
newAttemptPolicyAccount(4334, service.PlatformOpenAI, 2, map[string]any{"deepseek-flash": "account-direct", "deepseek-pro": "deepseek-final"}),
|
||||
},
|
||||
quotaCache: quotaCache,
|
||||
upstream: upstream,
|
||||
channel: channel,
|
||||
})
|
||||
|
||||
w := postAttemptPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"stream":false}`)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
captured := upstream.snapshot()
|
||||
require.Len(t, captured, 2, "one attempt per platform after failover")
|
||||
|
||||
byHost := make(map[string]attemptPolicyCapturedRequest, len(captured))
|
||||
for _, item := range captured {
|
||||
byHost[item.host] = item
|
||||
}
|
||||
deepseekAttempt, ok := byHost["deepseek-pool-fake.test"]
|
||||
require.True(t, ok, "deepseek account must be attempted first")
|
||||
require.Equal(t, "deepseek-chat", gjson.GetBytes(deepseekAttempt.body, "model").String(),
|
||||
"deepseek attempt must apply only its own account mapping (no cross-platform channel mapping)")
|
||||
|
||||
openAIAttempt, ok := byHost["openai-pool-fake.test"]
|
||||
require.True(t, ok, "failover must reach the openai account")
|
||||
require.Equal(t, "deepseek-final", gjson.GetBytes(openAIAttempt.body, "model").String(),
|
||||
"openai attempt must apply channel mapping (deepseek-flash→deepseek-pro) then account mapping (→deepseek-final)")
|
||||
}
|
||||
|
||||
// ── 5) pinned 请求遭平台配额拒绝:原 policy 错误、不外呼、不改绑定 ───────────
|
||||
func TestCompositePoolAttemptPolicyPinnedQuotaDeniedStaysOnOwner(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
// owner 选 openai 平台账号(priority 1):openai 账号走原生 Responses 转发,
|
||||
// 成功后 bindHTTPResponseAccount 落 response→account 与 owner 绑定。
|
||||
quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{
|
||||
service.PlatformDeepseek: allowedAttemptPolicyEntry(now),
|
||||
service.PlatformOpenAI: allowedAttemptPolicyEntry(now),
|
||||
}}
|
||||
upstream := &attemptPolicyUpstream{}
|
||||
router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{
|
||||
accounts: []service.Account{
|
||||
newAttemptPolicyAccount(4334, service.PlatformOpenAI, 1, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
newAttemptPolicyAccount(4333, service.PlatformDeepseek, 2, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
},
|
||||
quotaCache: quotaCache,
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
// 请求 A:/v1/responses 成功 → 上游响应 id=resp_pin 绑定到 openai 账号。
|
||||
wA := postAttemptPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"deepseek-flash","input":"hi","prompt_cache_key":"sess-attempt-pin","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, wA.Code, wA.Body.String())
|
||||
capturedAfterA := len(upstream.snapshot())
|
||||
require.NotEmpty(t, upstream.hosts())
|
||||
|
||||
// 平台配额耗尽(openai 为状态归属平台)。
|
||||
quotaCache.setEntry(service.PlatformOpenAI, exhaustedAttemptPolicyEntry(now))
|
||||
|
||||
// 请求 B:同会话 + prevID 命中状态归属 → 配额拒绝必须以原 policy 错误终止:
|
||||
// 429+Retry-After(非 400 掩盖),不外呼、不换账号、绑定不删。
|
||||
wB := postAttemptPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"deepseek-flash","input":"continue","prompt_cache_key":"sess-attempt-pin","previous_response_id":"resp_pin","stream":false}`)
|
||||
require.Equal(t, http.StatusTooManyRequests, wB.Code, wB.Body.String())
|
||||
require.Contains(t, wB.Body.String(), "rate_limit_exceeded")
|
||||
require.NotEmpty(t, wB.Header().Get("Retry-After"))
|
||||
require.Len(t, upstream.snapshot(), capturedAfterA, "pinned quota denial must never reach the upstream")
|
||||
|
||||
// 请求 C:配额恢复后同 prevID 仍服务 → 绑定未被删除且未跨账号。
|
||||
quotaCache.setEntry(service.PlatformOpenAI, allowedAttemptPolicyEntry(now))
|
||||
wC := postAttemptPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"deepseek-flash","input":"continue","prompt_cache_key":"sess-attempt-pin","previous_response_id":"resp_pin","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, wC.Code, wC.Body.String())
|
||||
require.Len(t, upstream.snapshot(), capturedAfterA+1)
|
||||
lastHost := upstream.hosts()[len(upstream.hosts())-1]
|
||||
require.Contains(t, lastHost, "openai-pool-fake.test",
|
||||
"binding must stay on the owner platform after a pinned policy denial")
|
||||
}
|
||||
|
||||
// ── 6) policy deny masked 重选不清原 sticky 绑定 ─────────────────────────────
|
||||
// deny 时同步 failedAccountIDs 排除该账号:下一轮 masked ctx 下 sticky 层对
|
||||
// excluded 账号提前返回(不 clear),DeleteSessionAccountID 零调用;其它平台
|
||||
// 成功后 sticky 按用户目标正常改绑(Set 覆盖,而非 Delete)。
|
||||
func TestCompositePoolAttemptPolicyDenyKeepsStickyBinding(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{
|
||||
service.PlatformDeepseek: allowedAttemptPolicyEntry(now),
|
||||
service.PlatformOpenAI: allowedAttemptPolicyEntry(now),
|
||||
}}
|
||||
upstream := &attemptPolicyUpstream{}
|
||||
stickyCache := newAttemptPolicyStickyCache()
|
||||
router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{
|
||||
accounts: []service.Account{
|
||||
newAttemptPolicyAccount(4333, service.PlatformDeepseek, 1, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
newAttemptPolicyAccount(4334, service.PlatformOpenAI, 2, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
},
|
||||
quotaCache: quotaCache,
|
||||
upstream: upstream,
|
||||
stickyCache: stickyCache,
|
||||
})
|
||||
|
||||
// 请求 1:session 建立粘性绑定(deepseek priority 1 命中)。
|
||||
w1 := postAttemptPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-ap-sticky","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, w1.Code, w1.Body.String())
|
||||
bindings1, setCnt1, deleteCnt1 := stickyCache.snapshot()
|
||||
t.Logf("DEBUG sticky bindings after R1: %v set=%d delete=%d", bindings1, setCnt1, deleteCnt1)
|
||||
require.GreaterOrEqual(t, setCnt1, 1, "session must establish a sticky binding")
|
||||
require.Equal(t, 0, deleteCnt1)
|
||||
require.NotEmpty(t, bindings1, "sticky binding must exist after the first request")
|
||||
for _, accountID := range bindings1 {
|
||||
require.Equal(t, int64(4333), accountID, "sticky binding must point at the first-served account")
|
||||
}
|
||||
|
||||
// deepseek 平台配额耗尽。
|
||||
quotaCache.setEntry(service.PlatformDeepseek, exhaustedAttemptPolicyEntry(now))
|
||||
hostsBefore := len(upstream.hosts())
|
||||
|
||||
// 请求 2:同 session → sticky 命中 deepseek → quota 预检拒绝 → mask 重选
|
||||
// openai 成功。全程不允许清除原 sticky 绑定。
|
||||
w2 := postAttemptPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-ap-sticky","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, w2.Code, w2.Body.String())
|
||||
for _, host := range upstream.hosts()[hostsBefore:] {
|
||||
require.Contains(t, host, "openai-pool-fake.test",
|
||||
"denied platform must not receive the request; failover must reach the healthy platform")
|
||||
}
|
||||
|
||||
bindings2, setCnt2, deleteCnt2 := stickyCache.snapshot()
|
||||
require.Equal(t, 0, deleteCnt2,
|
||||
"policy-deny mask re-selection must never delete the original sticky binding")
|
||||
require.Equal(t, 1, len(bindings2), "the same session key must be re-pointed, not fanned out")
|
||||
for _, accountID := range bindings2 {
|
||||
require.Equal(t, int64(4334), accountID,
|
||||
"sticky binding must be re-pointed to the successfully served account via Set (not Delete+re-add churn)")
|
||||
}
|
||||
require.Greater(t, setCnt2, setCnt1)
|
||||
}
|
||||
|
||||
// ── 7) 兄弟账号同平台:sticky X、deny 落平台后 Y 不外呼、Z 接管、delKeys=0 ────
|
||||
// 复审 A 场景:池含 X/Y(deepseek)+Z(opencode),sticky 绑 X;deepseek 平台被
|
||||
// policy deny 后 masked 重选里 sticky X 与兄弟 Y 都不得被平台失配清绑定,
|
||||
// 整个 deepseek 平台零外呼,Z 接管后 sticky 经正常 Set 改绑 Z。
|
||||
func TestCompositePoolAttemptPolicyDenyWithSiblingAccountsKeepsBinding(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{
|
||||
service.PlatformDeepseek: allowedAttemptPolicyEntry(now),
|
||||
service.PlatformOpenAI: allowedAttemptPolicyEntry(now),
|
||||
service.PlatformOpenCodeGo: allowedAttemptPolicyEntry(now),
|
||||
}}
|
||||
upstream := &attemptPolicyUpstream{}
|
||||
stickyCache := newAttemptPolicyStickyCache()
|
||||
router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{
|
||||
accounts: []service.Account{
|
||||
newAttemptPolicyAccount(4333, service.PlatformDeepseek, 1, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
newAttemptPolicyAccount(4335, service.PlatformDeepseek, 2, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
newAttemptPolicyAccount(4336, service.PlatformOpenCodeGo, 3, map[string]any{"deepseek-flash": "deepseek-chat"}),
|
||||
},
|
||||
quotaCache: quotaCache,
|
||||
upstream: upstream,
|
||||
stickyCache: stickyCache,
|
||||
})
|
||||
|
||||
// 请求 1:session 绑定 X(deepseek priority 1)。
|
||||
w1 := postAttemptPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-ap-sibling","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, w1.Code, w1.Body.String())
|
||||
bindings1, _, deleteCnt1 := stickyCache.snapshot()
|
||||
require.Equal(t, 0, deleteCnt1)
|
||||
require.Len(t, bindings1, 1)
|
||||
for _, accountID := range bindings1 {
|
||||
require.Equal(t, int64(4333), accountID, "session must bind the first-served deepseek account X")
|
||||
}
|
||||
|
||||
// deepseek 平台配额耗尽(X/Y 所在平台整体被 deny)。
|
||||
quotaCache.setEntry(service.PlatformDeepseek, exhaustedAttemptPolicyEntry(now))
|
||||
hostsBefore := len(upstream.hosts())
|
||||
|
||||
// 请求 2:同 session → sticky X 命中 → deepseek quota 拒绝 → masked 重选:
|
||||
// X/Y 同平台均不外呼、绑定不清,Z(opencode)接管成功。
|
||||
w2 := postAttemptPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-ap-sibling","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, w2.Code, w2.Body.String())
|
||||
hostsR2 := upstream.hosts()[hostsBefore:]
|
||||
require.NotEmpty(t, hostsR2)
|
||||
for _, host := range hostsR2 {
|
||||
require.NotContains(t, host, "deepseek-pool-fake.test",
|
||||
"sibling deepseek accounts must never receive the request after the platform denial")
|
||||
require.Contains(t, host, "opencode_go-pool-fake.test",
|
||||
"request must be served by the remaining healthy platform")
|
||||
}
|
||||
|
||||
// 零 delete;成功后 sticky 经 Set 正常改绑 Z。
|
||||
_, _, deleteCnt2 := stickyCache.snapshot()
|
||||
require.Equal(t, 0, deleteCnt2, "no sticky binding may be deleted by the temporary platform denial")
|
||||
bindings2, _, _ := stickyCache.snapshot()
|
||||
require.Len(t, bindings2, 1)
|
||||
for _, accountID := range bindings2 {
|
||||
require.Equal(t, int64(4336), accountID,
|
||||
"after a successful take-over the sticky binding is updated normally via Set")
|
||||
}
|
||||
}
|
||||
|
||||
// ── 8) BillingModelSource=upstream 逐账号限制只排除受限账号,不屏蔽同平台合法兄弟号 ─
|
||||
func TestCompositePoolAttemptPolicyUpstreamRestrictionDoesNotMaskSiblingAccount(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
quotaCache := &attemptPolicyQuotaCache{entries: map[string]*service.UserPlatformQuotaCacheEntry{
|
||||
service.PlatformDeepseek: allowedAttemptPolicyEntry(now),
|
||||
service.PlatformOpenAI: allowedAttemptPolicyEntry(now),
|
||||
}}
|
||||
upstream := &attemptPolicyUpstream{}
|
||||
channel := &service.Channel{
|
||||
ID: 1,
|
||||
Status: service.StatusActive,
|
||||
GroupIDs: []int64{attemptPolicyGroupID},
|
||||
RestrictModels: true,
|
||||
BillingModelSource: service.BillingModelSourceUpstream,
|
||||
ModelMapping: map[string]map[string]string{
|
||||
service.PlatformAnthropic: {"deepseek-flash": "unlisted-claude"},
|
||||
service.PlatformDeepseek: {"deepseek-flash": "deepseek-mid"},
|
||||
},
|
||||
ModelPricing: []service.ChannelModelPricing{
|
||||
{Platform: service.PlatformDeepseek, Models: []string{"deepseek-allowed"}},
|
||||
},
|
||||
}
|
||||
// 4341(deepseek priority 1):映射为受限的 deepseek-blocked;
|
||||
// 4342(deepseek priority 2):经渠道映射 deepseek-mid → deepseek-allowed(合法);
|
||||
// 4343(openai priority 3):映射为受限的 gpt-blocked(用于凑成双平台池)。
|
||||
router := newCompositePoolAttemptPolicyRouter(t, attemptPolicyRouterInput{
|
||||
accounts: []service.Account{
|
||||
newAttemptPolicyAccount(4341, service.PlatformDeepseek, 1, map[string]any{
|
||||
"deepseek-flash": "deepseek-blocked",
|
||||
"deepseek-mid": "deepseek-blocked",
|
||||
}),
|
||||
newAttemptPolicyAccount(4342, service.PlatformDeepseek, 2, map[string]any{
|
||||
"deepseek-flash": "deepseek-allowed",
|
||||
"deepseek-mid": "deepseek-allowed",
|
||||
}),
|
||||
newAttemptPolicyAccount(4343, service.PlatformOpenAI, 3, map[string]any{
|
||||
"deepseek-flash": "gpt-blocked",
|
||||
}),
|
||||
},
|
||||
quotaCache: quotaCache,
|
||||
upstream: upstream,
|
||||
channel: channel,
|
||||
})
|
||||
|
||||
w := postAttemptPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"stream":false}`)
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
captured := upstream.snapshot()
|
||||
require.Len(t, captured, 1)
|
||||
require.Contains(t, captured[0].host, "deepseek-pool-fake.test")
|
||||
require.Equal(t, "deepseek-allowed", gjson.GetBytes(captured[0].body, "model").String())
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//go:build unit
|
||||
|
||||
package routes
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// 跨族账号池上的 Responses 续链:归属账号必然是 OpenAI 兼容族(只有 OpenAI 网关链
|
||||
// 创建续链绑定),候选池收窄到兼容族后交 OpenAI handler 按归属钉住并校验租户;
|
||||
// 首轮经 generic 池委派创建的响应同样记录了下游归属,续链可继续。
|
||||
func TestCompositeCrossFamilyPoolContinuationPinsOwner(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
deepseek := newPoolPolicyAccountWithMapping(4301, service.PlatformDeepseek, 0, map[string]any{"xpool-model": "deepseek-chat"})
|
||||
deepseek.Credentials["api_protocol"] = service.APIProtocolResponses
|
||||
anthropic := newPoolPolicyAccountWithMapping(4302, service.PlatformAnthropic, 5, map[string]any{"xpool-model": "claude-sonnet-4-5"})
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: newPoolPolicyGroup(nil),
|
||||
accounts: []service.Account{deepseek, anthropic},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
first := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"xpool-model","input":"hi","prompt_cache_key":"sess-x-a","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, first.Code, first.Body.String())
|
||||
responseID := gjson.GetBytes(first.Body.Bytes(), "id").String()
|
||||
require.True(t, strings.HasPrefix(responseID, "resp_"), "got %q", responseID)
|
||||
captured := upstream.capturedSnapshot()
|
||||
require.Len(t, captured, 1)
|
||||
require.Equal(t, "deepseek-pool-fake.test", captured[0].host)
|
||||
|
||||
before := len(upstream.capturedSnapshot())
|
||||
second := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"xpool-model","input":"continue","prompt_cache_key":"sess-x-b","previous_response_id":"`+responseID+`","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, second.Code, second.Body.String())
|
||||
after := upstream.capturedSnapshot()[before:]
|
||||
require.NotEmpty(t, after)
|
||||
for _, record := range after {
|
||||
require.Equal(t, "deepseek-pool-fake.test", record.host, "continuation must stay on the owning account")
|
||||
}
|
||||
}
|
||||
|
||||
// 续链请求里优先级更高的 Anthropic 账号绝不能收到带 previous_response_id 的请求。
|
||||
func TestCompositeCrossFamilyPoolContinuationNeverReachesNonOpenAIAccount(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
deepseek := newPoolPolicyAccountWithMapping(4311, service.PlatformDeepseek, 5, map[string]any{
|
||||
"ds-only": "deepseek-chat",
|
||||
"xpool-model": "deepseek-chat",
|
||||
})
|
||||
deepseek.Credentials["api_protocol"] = service.APIProtocolResponses
|
||||
anthropic := newPoolPolicyAccountWithMapping(4312, service.PlatformAnthropic, 0, map[string]any{"xpool-model": "claude-sonnet-4-5"})
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: newPoolPolicyGroup(nil),
|
||||
accounts: []service.Account{deepseek, anthropic},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
first := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"ds-only","input":"hi","prompt_cache_key":"sess-y-a","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, first.Code, first.Body.String())
|
||||
responseID := gjson.GetBytes(first.Body.Bytes(), "id").String()
|
||||
require.True(t, strings.HasPrefix(responseID, "resp_"), "got %q", responseID)
|
||||
|
||||
before := len(upstream.capturedSnapshot())
|
||||
second := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"xpool-model","input":"continue","prompt_cache_key":"sess-y-b","previous_response_id":"`+responseID+`","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, second.Code, second.Body.String())
|
||||
for _, record := range upstream.capturedSnapshot()[before:] {
|
||||
require.Equal(t, "deepseek-pool-fake.test", record.host)
|
||||
}
|
||||
}
|
||||
|
||||
// 候选池没有 OpenAI 兼容族时续链无法继续:入口明确拒绝,不转发任何请求。
|
||||
func TestCompositePoolContinuationWithoutOpenAICompatibleCandidateRejected(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: newPoolPolicyGroup(nil),
|
||||
accounts: []service.Account{
|
||||
newPoolPolicyAccountWithMapping(4321, service.PlatformAnthropic, 0, map[string]any{"np-model": "claude-sonnet-4-5"}),
|
||||
newPoolPolicyAccountWithMapping(4322, service.PlatformGemini, 1, map[string]any{"np-model": "gemini-3.1-pro"}),
|
||||
},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
w := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"np-model","input":"continue","previous_response_id":"resp_abc","stream":false}`)
|
||||
require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())
|
||||
require.Contains(t, w.Body.String(), "previous_response_id")
|
||||
require.Empty(t, upstream.capturedSnapshot())
|
||||
}
|
||||
|
||||
// 跨族账号池访问 /v1/responses/compact:候选池收窄到 OpenAI 兼容族交由 OpenAI handler
|
||||
// 处理,优先级更高的 Anthropic 账号不会收到 compact 请求;无兼容族候选时入口明确拒绝。
|
||||
func TestCompositeCrossFamilyPoolCompactNarrowsToOpenAICompatible(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
openai := newPoolPolicyAccountWithMapping(4331, service.PlatformOpenAI, 5, map[string]any{"compact-model": "gpt-5.4"})
|
||||
anthropic := newPoolPolicyAccountWithMapping(4332, service.PlatformAnthropic, 0, map[string]any{"compact-model": "claude-sonnet-4-5"})
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: newPoolPolicyGroup(nil),
|
||||
accounts: []service.Account{openai, anthropic},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
w := postPoolPolicyRequest(t, router, "/v1/responses/compact",
|
||||
`{"model":"compact-model","input":"compact this"}`)
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
captured := upstream.capturedSnapshot()
|
||||
require.Len(t, captured, 1)
|
||||
require.Equal(t, "openai-pool-fake.test", captured[0].host)
|
||||
require.True(t, strings.HasSuffix(captured[0].path, "/responses/compact"), "path=%q", captured[0].path)
|
||||
|
||||
upstreamNone := &captureUpstream{}
|
||||
routerNone, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: newPoolPolicyGroup(nil),
|
||||
accounts: []service.Account{
|
||||
newPoolPolicyAccountWithMapping(4333, service.PlatformAnthropic, 0, map[string]any{"np-compact": "claude-sonnet-4-5"}),
|
||||
newPoolPolicyAccountWithMapping(4334, service.PlatformGemini, 1, map[string]any{"np-compact": "gemini-3.1-pro"}),
|
||||
},
|
||||
upstream: upstreamNone,
|
||||
})
|
||||
wNone := postPoolPolicyRequest(t, routerNone, "/v1/responses/compact",
|
||||
`{"model":"np-compact","input":"compact this"}`)
|
||||
require.Equal(t, http.StatusBadRequest, wNone.Code, wNone.Body.String())
|
||||
require.Contains(t, wNone.Body.String(), "/responses/compact")
|
||||
require.Empty(t, upstreamNone.capturedSnapshot())
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
//go:build unit
|
||||
|
||||
package routes
|
||||
|
||||
// composite 账号池 handler 级守卫测试:经真实 RegisterGatewayRoutes 链路验证
|
||||
// 1) previous_response_id 状态归属守卫(owner 合法但调度未命中 pin 时明确拒绝、
|
||||
// 不外呼、selector 预占槽位恰一次释放);2) reasoning-effort deny 早退同样
|
||||
// 恰一次释放;3) 非 pool 请求携带已归属 prevID 保持既有转发行为;4) 池策略
|
||||
// cap 按 attempt 应用、failover 跨平台不泄漏。出站经 HTTPUpstream 桩捕获,
|
||||
// 不发起真实网络请求。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
servermiddleware "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"
|
||||
)
|
||||
|
||||
// countingConcurrencyCache 在 RED fixture 的放行语义上为账号槽位加计数,
|
||||
// 用于断言守卫早退对 selector 已持有槽位的恰一次释放。
|
||||
type countingConcurrencyCache struct {
|
||||
service.ConcurrencyCache
|
||||
|
||||
acquireAccountCalls atomic.Int64
|
||||
releaseAccountCalls atomic.Int64
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) AcquireUserSlot(context.Context, int64, int, string) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) ReleaseUserSlot(context.Context, int64, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) AcquireAccountSlot(_ context.Context, _ int64, _ int, _ string) (bool, error) {
|
||||
m.acquireAccountCalls.Add(1)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) ReleaseAccountSlot(_ context.Context, _ int64, _ string) error {
|
||||
m.releaseAccountCalls.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) GetAccountConcurrency(context.Context, int64) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) GetAccountConcurrencyBatch(_ context.Context, accountIDs []int64) (map[int64]int, error) {
|
||||
result := make(map[int64]int, len(accountIDs))
|
||||
for _, id := range accountIDs {
|
||||
result[id] = 0
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) IncrementAccountWaitCount(context.Context, int64, int) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) DecrementAccountWaitCount(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) GetAccountWaitingCount(context.Context, int64) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) IncrementWaitCount(context.Context, int64, int) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) DecrementWaitCount(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *countingConcurrencyCache) GetUserConcurrency(context.Context, int64) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// stickyMemoryGatewayCache 提供进程内粘性会话绑定,驱动 scheduler 的
|
||||
// session-sticky 预占槽位路径(Acquired=true + ReleaseFunc)。
|
||||
type stickyMemoryGatewayCache struct {
|
||||
mu sync.Mutex
|
||||
bindings map[string]int64
|
||||
bindingKey func(groupID int64, sessionHash string) string
|
||||
}
|
||||
|
||||
func newStickyMemoryGatewayCache() *stickyMemoryGatewayCache {
|
||||
return &stickyMemoryGatewayCache{bindings: make(map[string]int64)}
|
||||
}
|
||||
|
||||
func (c *stickyMemoryGatewayCache) key(groupID int64, sessionHash string) string {
|
||||
return fmt.Sprintf("%d:%s", groupID, sessionHash)
|
||||
}
|
||||
|
||||
func (c *stickyMemoryGatewayCache) GetSessionAccountID(_ context.Context, groupID int64, sessionHash string) (int64, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
id, ok := c.bindings[c.key(groupID, sessionHash)]
|
||||
if !ok {
|
||||
return 0, service.ErrStickySessionNotFound
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (c *stickyMemoryGatewayCache) SetSessionAccountID(_ context.Context, groupID int64, sessionHash string, accountID int64, _ time.Duration) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.bindings[c.key(groupID, sessionHash)] = accountID
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *stickyMemoryGatewayCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *stickyMemoryGatewayCache) DeleteSessionAccountID(_ context.Context, groupID int64, sessionHash string) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
delete(c.bindings, c.key(groupID, sessionHash))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *stickyMemoryGatewayCache) SetGrokVideoPendingBilling(context.Context, string, []byte, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *stickyMemoryGatewayCache) GetGrokVideoPendingBilling(context.Context, string) ([]byte, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c *stickyMemoryGatewayCache) ClaimGrokVideoBilled(context.Context, string, time.Duration) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (c *stickyMemoryGatewayCache) ReleaseGrokVideoBilled(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *stickyMemoryGatewayCache) SetReasoningContent(context.Context, string, string, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *stickyMemoryGatewayCache) GetReasoningContent(context.Context, string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
type poolPolicyCapturedRequest struct {
|
||||
accountID int64
|
||||
host string
|
||||
path string
|
||||
body []byte
|
||||
}
|
||||
|
||||
// captureUpstream 捕获出站请求(原始 body),并按 host 注入可配置失败以驱动
|
||||
// failover;openai 平台账号经 Responses 协议转发,返回最小 completed SSE。
|
||||
type captureUpstream struct {
|
||||
service.HTTPUpstream
|
||||
|
||||
mu sync.Mutex
|
||||
captured []poolPolicyCapturedRequest
|
||||
failHost map[string]bool
|
||||
}
|
||||
|
||||
func (u *captureUpstream) capture(req *http.Request, accountID int64) []byte {
|
||||
var body []byte
|
||||
if req.Body != nil {
|
||||
body, _ = io.ReadAll(req.Body)
|
||||
}
|
||||
u.mu.Lock()
|
||||
u.captured = append(u.captured, poolPolicyCapturedRequest{
|
||||
accountID: accountID,
|
||||
host: req.URL.Hostname(),
|
||||
path: req.URL.Path,
|
||||
body: body,
|
||||
})
|
||||
u.mu.Unlock()
|
||||
return body
|
||||
}
|
||||
|
||||
func (u *captureUpstream) capturedSnapshot() []poolPolicyCapturedRequest {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
return append([]poolPolicyCapturedRequest(nil), u.captured...)
|
||||
}
|
||||
|
||||
func (u *captureUpstream) respondFor(req *http.Request) *http.Response {
|
||||
if u.failHost[req.URL.Hostname()] {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusTooManyRequests,
|
||||
Header: http.Header{
|
||||
"Content-Type": []string{"application/json"},
|
||||
"Retry-After": []string{"60"},
|
||||
},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limited"}}`)),
|
||||
}
|
||||
}
|
||||
if strings.HasSuffix(req.URL.Path, "/responses/compact") {
|
||||
return compositeDispatchResponse("application/json", `{"id":"resp_compact","object":"response.compaction","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}`)
|
||||
}
|
||||
if strings.Contains(req.URL.Path, "/responses") {
|
||||
sse := "event: response.completed\n" +
|
||||
`data: {"type":"response.completed","response":{"id":"resp_pool","object":"response","status":"completed","model":"deepseek-chat","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}` + "\n\n"
|
||||
return compositeDispatchResponse("text/event-stream", sse)
|
||||
}
|
||||
// id 使用 resp_ 前缀:生产 bindHTTPResponseAccount 会把该 id 绑定到选中
|
||||
// 账号,第二条请求的 previous_response_id 需通过 resp_* 形态校验。
|
||||
return compositeDispatchResponse("application/json", `{"id":"resp_pool_chat","object":"chat.completion","model":"deepseek-chat","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
|
||||
}
|
||||
|
||||
func (u *captureUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
|
||||
u.capture(req, accountID)
|
||||
return u.respondFor(req), nil
|
||||
}
|
||||
|
||||
func (u *captureUpstream) DoWithTLS(req *http.Request, _ string, accountID int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
u.capture(req, accountID)
|
||||
return u.respondFor(req), nil
|
||||
}
|
||||
|
||||
type poolPolicyRouterInput struct {
|
||||
group *service.Group
|
||||
accounts []service.Account
|
||||
cache *countingConcurrencyCache
|
||||
upstream *captureUpstream
|
||||
apiKeyID int64
|
||||
}
|
||||
|
||||
const (
|
||||
poolPolicyGroupID = int64(4210)
|
||||
poolPolicyUserID = int64(4201)
|
||||
)
|
||||
|
||||
func newCompositePoolPolicyTestRouter(t *testing.T, in poolPolicyRouterInput) (*gin.Engine, *service.OpenAIGatewayService) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
if in.cache == nil {
|
||||
in.cache = &countingConcurrencyCache{}
|
||||
}
|
||||
if in.upstream == nil {
|
||||
in.upstream = &captureUpstream{}
|
||||
}
|
||||
apiKeyID := in.apiKeyID
|
||||
if apiKeyID == 0 {
|
||||
apiKeyID = 4202
|
||||
}
|
||||
repo := &compositeDispatchAccountRepo{accounts: in.accounts}
|
||||
groupRepo := &compositeDispatchGroupRepo{group: in.group}
|
||||
|
||||
compositeResolver := service.NewCompositeRouteResolver(nil)
|
||||
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
cfg.Gateway.MaxBodySize = 1024 * 1024
|
||||
cfg.Gateway.TextMaxBodySize = 1024 * 1024
|
||||
cfg.Gateway.MaxAccountSwitches = 3
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
|
||||
billingService := service.NewBillingService(cfg, nil)
|
||||
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
concurrencyService := service.NewConcurrencyService(in.cache)
|
||||
deferred := &service.DeferredService{}
|
||||
|
||||
genericGateway := service.NewGatewayService(
|
||||
repo, groupRepo, nil, nil, nil, nil, nil, nil, cfg, nil,
|
||||
concurrencyService, billingService, nil, billingCache, nil,
|
||||
in.upstream, deferred, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
compositeResolver, nil, nil,
|
||||
)
|
||||
openAIGateway := service.NewOpenAIGatewayService(
|
||||
repo, nil, nil, nil, nil, nil, newStickyMemoryGatewayCache(), cfg, nil, concurrencyService,
|
||||
billingService, nil, billingCache, in.upstream, deferred,
|
||||
nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
|
||||
handlers := &handler.Handlers{
|
||||
Gateway: handler.NewGatewayHandler(
|
||||
genericGateway, openAIGateway, nil, nil, nil,
|
||||
concurrencyService, billingCache, nil, nil, nil, nil, nil, nil,
|
||||
cfg, nil,
|
||||
),
|
||||
OpenAIGateway: handler.NewOpenAIGatewayHandler(
|
||||
openAIGateway, concurrencyService, billingCache, &service.APIKeyService{},
|
||||
nil, nil, nil, nil, cfg,
|
||||
),
|
||||
AsyncImage: handler.NewAsyncImageHandler(nil, nil),
|
||||
}
|
||||
|
||||
router := gin.New()
|
||||
RegisterGatewayRoutes(
|
||||
router,
|
||||
handlers,
|
||||
servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) {
|
||||
groupID := in.group.ID
|
||||
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
|
||||
ID: apiKeyID,
|
||||
GroupID: &groupID,
|
||||
User: &service.User{ID: poolPolicyUserID, Status: service.StatusActive},
|
||||
Group: in.group,
|
||||
})
|
||||
c.Set(string(servermiddleware.ContextKeyUser), servermiddleware.AuthSubject{UserID: poolPolicyUserID, Concurrency: 1})
|
||||
c.Next()
|
||||
}),
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
compositeResolver,
|
||||
cfg,
|
||||
)
|
||||
return router, openAIGateway
|
||||
}
|
||||
|
||||
func newPoolPolicyGroup(mutate func(group *service.Group)) *service.Group {
|
||||
group := &service.Group{
|
||||
ID: poolPolicyGroupID,
|
||||
Platform: service.PlatformComposite,
|
||||
Status: service.StatusActive,
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(group)
|
||||
}
|
||||
return group
|
||||
}
|
||||
|
||||
func newPoolPolicyAccount(id int64, platform string, priority int) service.Account {
|
||||
return newPoolPolicyAccountWithMapping(id, platform, priority, map[string]any{
|
||||
"deepseek-flash": "deepseek-chat",
|
||||
})
|
||||
}
|
||||
|
||||
func newPoolPolicyAccountWithMapping(id int64, platform string, priority int, mapping map[string]any) service.Account {
|
||||
return service.Account{
|
||||
ID: id, Name: "pool-" + platform,
|
||||
Platform: platform, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 4, Priority: priority,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "test-key-" + platform,
|
||||
"base_url": "https://" + platform + "-pool-fake.test/v1",
|
||||
"model_mapping": mapping,
|
||||
},
|
||||
GroupIDs: []int64{poolPolicyGroupID},
|
||||
AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: poolPolicyGroupID, Priority: 1}},
|
||||
}
|
||||
}
|
||||
|
||||
func postPoolPolicyRequest(t *testing.T, router *gin.Engine, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// 池请求携带已归属本用户的 previous_response_id、调度未命中状态归属账号
|
||||
// (StickyPreviousHit=false)时:任何转发之前明确 400 拒绝,不外呼,sticky
|
||||
// 层预占的账号槽位被恰一次释放。
|
||||
func TestCompositePoolPreviousResponseIDRejectsWithoutPin(t *testing.T) {
|
||||
cache := &countingConcurrencyCache{}
|
||||
upstream := &captureUpstream{}
|
||||
group := newPoolPolicyGroup(nil)
|
||||
router, openAIGateway := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: group,
|
||||
accounts: []service.Account{newPoolPolicyAccount(4211, service.PlatformOpenAI, 1), newPoolPolicyAccount(4212, service.PlatformDeepseek, 2)},
|
||||
cache: cache,
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
// 请求 A(无 prevID,带 prompt_cache_key):建立 sticky 绑定。
|
||||
wA := postPoolPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-pool-guard","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, wA.Code, wA.Body.String())
|
||||
acquireAfterA := cache.acquireAccountCalls.Load()
|
||||
|
||||
// 预绑定 response 归属(模拟该 prevID 属于本用户的历史响应)。
|
||||
require.NoError(t, openAIGateway.BindOpenAIHTTPResponseOwner(context.Background(), poolPolicyGroupID, "resp_owned", poolPolicyUserID, 4202))
|
||||
|
||||
// 请求 B(同会话 + prevID):未命中 pin → 拒绝且不外呼。
|
||||
wB := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"deepseek-flash","input":"hi","prompt_cache_key":"sess-pool-guard","previous_response_id":"resp_owned","stream":false}`)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, wB.Code, wB.Body.String())
|
||||
require.Contains(t, wB.Body.String(), "previous_response_id")
|
||||
require.Equal(t, acquireAfterA, cache.acquireAccountCalls.Load()-1,
|
||||
"request B must pre-acquire the account slot once via the sticky layer")
|
||||
require.Equal(t, acquireAfterA+1, cache.releaseAccountCalls.Load(),
|
||||
"guard must release the pre-acquired slot exactly once")
|
||||
}
|
||||
|
||||
// reasoning-effort deny 在账号选定后触发:403 拒绝、不外呼、sticky 层预占的
|
||||
// 槽位恰一次释放(不泄漏、不重复释放)。
|
||||
func TestCompositePoolReasoningPolicyDenyReleasesSelectorSlot(t *testing.T) {
|
||||
cache := &countingConcurrencyCache{}
|
||||
upstream := &captureUpstream{}
|
||||
group := newPoolPolicyGroup(func(group *service.Group) {
|
||||
group.ReasoningEffortMappings = []service.ReasoningEffortMapping{{From: "xhigh", To: "deny"}}
|
||||
})
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: group,
|
||||
accounts: []service.Account{newPoolPolicyAccount(4211, service.PlatformOpenAI, 1), newPoolPolicyAccount(4212, service.PlatformDeepseek, 2)},
|
||||
cache: cache,
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
// 请求 A:建立 sticky 绑定(无 deny 冲突的正常 effort)。
|
||||
wA := postPoolPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-pool-deny","reasoning_effort":"low","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, wA.Code, wA.Body.String())
|
||||
acquireAfterA := cache.acquireAccountCalls.Load()
|
||||
releaseAfterA := cache.releaseAccountCalls.Load()
|
||||
|
||||
// 请求 B:同会话 + deny effort → 选号预占后由策略守卫终止。
|
||||
wB := postPoolPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"prompt_cache_key":"sess-pool-deny","reasoning_effort":"xhigh","stream":false}`)
|
||||
|
||||
require.Equal(t, http.StatusForbidden, wB.Code, wB.Body.String())
|
||||
require.Equal(t, upstream.capturedSnapshot()[len(upstream.capturedSnapshot())-1].accountID != 0, true)
|
||||
require.Equal(t, acquireAfterA+1, cache.acquireAccountCalls.Load(),
|
||||
"request B must pre-acquire the account slot once via the sticky layer")
|
||||
require.Equal(t, releaseAfterA+1, cache.releaseAccountCalls.Load(),
|
||||
"deny path must release the pre-acquired slot exactly once")
|
||||
}
|
||||
|
||||
// 非 pool 请求(单一 openai 目标)携带已归属 prevID 保持既有转发行为,不受
|
||||
// 池状态守卫影响。
|
||||
func TestNonCompositePoolPreviousResponseIDStillForwards(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
group := &service.Group{ID: poolPolicyGroupID, Platform: service.PlatformOpenAI, Status: service.StatusActive}
|
||||
router, openAIGateway := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: group,
|
||||
accounts: []service.Account{newPoolPolicyAccount(4211, service.PlatformOpenAI, 1)},
|
||||
upstream: upstream,
|
||||
})
|
||||
require.NoError(t, openAIGateway.BindOpenAIHTTPResponseOwner(context.Background(), poolPolicyGroupID, "resp_owned", poolPolicyUserID, 4202))
|
||||
|
||||
w := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"deepseek-flash","input":"hi","previous_response_id":"resp_owned","stream":false}`)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
require.NotEmpty(t, upstream.capturedSnapshot(), "non-pool requests keep the existing prevID forwarding behavior")
|
||||
}
|
||||
|
||||
// 池策略 cap 按 attempt 应用:deepseek 账号首跳失败后 failover 到 openai,
|
||||
// openai attempt 使用从 canonical body 新鲜 cap 的 medium——策略按 attempt
|
||||
// 应用、canonical body 不被改写。
|
||||
func TestCompositePoolReasoningPolicyCapAppliedPerAttempt(t *testing.T) {
|
||||
upstream := &captureUpstream{failHost: map[string]bool{
|
||||
"deepseek-pool-fake.test": true,
|
||||
}}
|
||||
group := newPoolPolicyGroup(func(group *service.Group) {
|
||||
group.MaxReasoningEffort = "medium"
|
||||
})
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: group,
|
||||
accounts: []service.Account{
|
||||
newPoolPolicyAccount(4211, service.PlatformDeepseek, 1),
|
||||
newPoolPolicyAccount(4212, service.PlatformOpenAI, 2),
|
||||
},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
w := postPoolPolicyRequest(t, router, "/v1/chat/completions",
|
||||
`{"model":"deepseek-flash","messages":[{"role":"user","content":"hi"}],"reasoning_effort":"xhigh","stream":false}`)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
|
||||
captured := upstream.capturedSnapshot()
|
||||
require.Len(t, captured, 2, "one attempt per account after failover")
|
||||
byHost := make(map[string]poolPolicyCapturedRequest, len(captured))
|
||||
for _, record := range captured {
|
||||
byHost[record.host] = record
|
||||
}
|
||||
deepseekAttempt, ok := byHost["deepseek-pool-fake.test"]
|
||||
require.True(t, ok, "deepseek account must be attempted first")
|
||||
require.Equal(t, "xhigh", gjson.GetBytes(deepseekAttempt.body, "reasoning_effort").String(),
|
||||
"non-openai attempt must keep the client effort uncapped")
|
||||
openaiAttempt, ok := byHost["openai-pool-fake.test"]
|
||||
require.True(t, ok, "failover must reach the openai account")
|
||||
// openai 平台账号经 CC→Responses 协议转发,出站体为 reasoning.effort。
|
||||
require.Equal(t, "medium", gjson.GetBytes(openaiAttempt.body, "reasoning.effort").String(),
|
||||
"openai attempt must carry the group-capped effort applied per attempt")
|
||||
}
|
||||
|
||||
// CN 账号真正的 previous_response pin(正向,依赖 2A 的 pool HTTP 资格门修复):
|
||||
// 第一条用仅 CN 父账号 claim 的模型建立 resp→CN 绑定;第二条换新 session 种子
|
||||
// 并让另一候选优先级更高(排除了 same-session sticky 的解释),只有
|
||||
// previous_response_id 命中原 CN 账号才能选中它并转发。2A 修复前该用例 RED。
|
||||
func TestCompositePoolCNPreviousResponseIDPinBeatsPriorityAndSeed(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
group := newPoolPolicyGroup(nil)
|
||||
// kimi 优先级更高(p1):无 pin 时 load-balance 会选 kimi;
|
||||
// deepseek(p2,native Responses)是 resp id 的归属账号。
|
||||
cnParent := newPoolPolicyAccountWithMapping(4211, service.PlatformDeepseek, 2, map[string]any{
|
||||
"deepseek-flash": "deepseek-chat",
|
||||
"pool-model": "deepseek-chat",
|
||||
})
|
||||
cnParent.Credentials["api_protocol"] = service.APIProtocolResponses
|
||||
other := newPoolPolicyAccountWithMapping(4212, service.PlatformKimi, 1, map[string]any{
|
||||
"pool-model": "kimi-chat",
|
||||
})
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: group,
|
||||
accounts: []service.Account{cnParent, other},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
// 第一条:仅 deepseek claim 的模型 → 绑定 resp id → deepseek。
|
||||
wA := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"deepseek-flash","input":"hi","prompt_cache_key":"sess-pin-a","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, wA.Code, wA.Body.String())
|
||||
capturedA := upstream.capturedSnapshot()
|
||||
require.Len(t, capturedA, 1)
|
||||
require.Equal(t, int64(4211), capturedA[0].accountID, "first request must be served by the CN parent account")
|
||||
|
||||
responseID := gjson.GetBytes(wA.Body.Bytes(), "id").String()
|
||||
require.True(t, strings.HasPrefix(responseID, "resp_"), "downstream response must carry a resp_* id, got %q", responseID)
|
||||
|
||||
// 第二条:新 session 种子(sticky 不可命中)+ 双账号池模型 + kimi 优先级更高;
|
||||
// 只有 previous_response_id 的真 pin 才能解释选中 deepseek。
|
||||
wB := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"pool-model","input":"continue","prompt_cache_key":"sess-pin-b","previous_response_id":"`+responseID+`","stream":false}`)
|
||||
|
||||
require.Equal(t, http.StatusOK, wB.Code, wB.Body.String())
|
||||
captured := upstream.capturedSnapshot()
|
||||
require.Len(t, captured, 2)
|
||||
require.Equal(t, int64(4211), captured[1].accountID,
|
||||
"previous_response_id pin must select the owning CN account over the higher-priority candidate")
|
||||
require.Equal(t, "deepseek-pool-fake.test", captured[1].host)
|
||||
}
|
||||
|
||||
// CN→CN 未 hit 跨账号转移必须拒绝:resp id 归属 deepseek,deepseek 首跳 429
|
||||
// failover 后不得转给另一 CN 候选(kimi),kimi 不收到带旧 prevID 的请求。归属账号
|
||||
// 的 429 是可重试错误,必须原样返回而不是永久性的 400,且续链绑定保留:上游恢复后
|
||||
// 同一 previous_response_id 仍回到 deepseek 继续。
|
||||
func TestCompositePoolPreviousResponseIDRejectsCrossCNSelection(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
group := newPoolPolicyGroup(nil)
|
||||
cnParent := newPoolPolicyAccountWithMapping(4211, service.PlatformDeepseek, 1, map[string]any{
|
||||
"deepseek-flash": "deepseek-chat",
|
||||
"pool-model": "deepseek-chat",
|
||||
})
|
||||
cnParent.Credentials["api_protocol"] = service.APIProtocolResponses
|
||||
other := newPoolPolicyAccountWithMapping(4212, service.PlatformKimi, 2, map[string]any{
|
||||
"pool-model": "kimi-chat",
|
||||
})
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: group,
|
||||
accounts: []service.Account{cnParent, other},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
// 第一条:仅 deepseek claim 的模型 → 绑定 resp id → deepseek。
|
||||
wA := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"deepseek-flash","input":"hi","prompt_cache_key":"sess-cross-a","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, wA.Code, wA.Body.String())
|
||||
responseID := gjson.GetBytes(wA.Body.Bytes(), "id").String()
|
||||
require.True(t, strings.HasPrefix(responseID, "resp_"), "downstream response must carry a resp_* id, got %q", responseID)
|
||||
|
||||
// 第二条:新 session 种子 + 双账号池模型;武装 deepseek 首跳 429,
|
||||
// failover 到 kimi 时守卫必须拒绝——kimi 不收到带旧 prevID 的转发。
|
||||
upstream.mu.Lock()
|
||||
upstream.failHost = map[string]bool{"deepseek-pool-fake.test": true}
|
||||
upstream.mu.Unlock()
|
||||
capturedBefore := len(upstream.capturedSnapshot())
|
||||
wB := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"pool-model","input":"continue","prompt_cache_key":"sess-cross-b","previous_response_id":"`+responseID+`","stream":false}`)
|
||||
|
||||
require.Equal(t, http.StatusTooManyRequests, wB.Code, wB.Body.String())
|
||||
for _, record := range upstream.capturedSnapshot()[capturedBefore:] {
|
||||
require.NotEqual(t, "kimi-pool-fake.test", record.host,
|
||||
"the non-owning CN account must never receive the old prevID")
|
||||
}
|
||||
|
||||
// 第三条:上游恢复,同一续链仍由归属账号服务(绑定未因 429 被删除)。
|
||||
upstream.mu.Lock()
|
||||
upstream.failHost = nil
|
||||
upstream.mu.Unlock()
|
||||
capturedBefore = len(upstream.capturedSnapshot())
|
||||
wC := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"pool-model","input":"continue again","prompt_cache_key":"sess-cross-c","previous_response_id":"`+responseID+`","stream":false}`)
|
||||
require.Equal(t, http.StatusOK, wC.Code, wC.Body.String())
|
||||
after := upstream.capturedSnapshot()[capturedBefore:]
|
||||
require.NotEmpty(t, after)
|
||||
for _, record := range after {
|
||||
require.Equal(t, "deepseek-pool-fake.test", record.host, "continuation must return to the owning account")
|
||||
}
|
||||
}
|
||||
|
||||
// claude-* 别名被两个兼容族账号同时 claim 时,/v1/messages 不套 gpt-5.x
|
||||
// 默认 dispatch 映射(池含 CN),仍按账号级 model_mapping 转发。
|
||||
func TestCompositePoolMessagesClaudeAliasUsesAccountMapping(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
group := newPoolPolicyGroup(nil)
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: group,
|
||||
accounts: []service.Account{
|
||||
newPoolPolicyAccountWithMapping(4211, service.PlatformDeepseek, 1, map[string]any{"claude-alias": "deepseek-chat"}),
|
||||
newPoolPolicyAccountWithMapping(4212, service.PlatformKimi, 2, map[string]any{"claude-alias": "kimi-claude"}),
|
||||
},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
w := postPoolPolicyRequest(t, router, "/v1/messages",
|
||||
`{"model":"claude-alias","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
captured := upstream.capturedSnapshot()
|
||||
require.NotEmpty(t, captured, "claude alias claimed by pool accounts must forward")
|
||||
require.Equal(t, "deepseek-pool-fake.test", captured[0].host)
|
||||
require.Equal(t, "deepseek-chat", gjson.GetBytes(captured[0].body, "model").String(),
|
||||
"outbound model must come from the selected account's model_mapping, not the gpt-5.x dispatch default")
|
||||
}
|
||||
|
||||
// C4:跨族候选池([anthropic, deepseek])调用免计费 /v1/responses/input_tokens 时,
|
||||
// 必须收窄到 OpenAI 兼容族走 ResponsesInputTokens,绝不能跌落进 GatewayHandler.Responses
|
||||
// 执行真实付费生成。
|
||||
func TestCompositeCrossFamilyPool_ResponsesInputTokensNeverTriggersGeneration(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
group := newPoolPolicyGroup(nil)
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: group,
|
||||
accounts: []service.Account{
|
||||
newPoolPolicyAccountWithMapping(4301, service.PlatformAnthropic, 0, map[string]any{"shared-count": "claude-sonnet-4-6"}),
|
||||
newPoolPolicyAccountWithMapping(4302, service.PlatformDeepseek, 5, map[string]any{"shared-count": "deepseek-chat"}),
|
||||
},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
w := postPoolPolicyRequest(t, router, "/v1/responses/input_tokens",
|
||||
`{"model":"shared-count","input":"hello world"}`)
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
require.Equal(t, "response.input_tokens", gjson.GetBytes(w.Body.Bytes(), "object").String())
|
||||
require.Greater(t, gjson.GetBytes(w.Body.Bytes(), "input_tokens").Int(), int64(0))
|
||||
require.Empty(t, upstream.capturedSnapshot(), "token count must estimate locally on CN relay and never run Anthropic generation")
|
||||
}
|
||||
|
||||
// H6:裸 /v1/responses 携带 compaction_trigger 时,跨族池必须收窄到 OpenAI 兼容族。
|
||||
func TestCompositeCrossFamilyPool_BareResponsesCompactionTriggerNarrowsToOpenAIFamily(t *testing.T) {
|
||||
upstream := &captureUpstream{}
|
||||
group := newPoolPolicyGroup(nil)
|
||||
ds := newPoolPolicyAccountWithMapping(4312, service.PlatformDeepseek, 5, map[string]any{"shared-compact": "deepseek-chat"})
|
||||
ds.Credentials["api_protocol"] = service.APIProtocolResponses
|
||||
router, _ := newCompositePoolPolicyTestRouter(t, poolPolicyRouterInput{
|
||||
group: group,
|
||||
accounts: []service.Account{
|
||||
newPoolPolicyAccountWithMapping(4311, service.PlatformAnthropic, 0, map[string]any{"shared-compact": "claude-sonnet-4-6"}),
|
||||
ds,
|
||||
},
|
||||
upstream: upstream,
|
||||
})
|
||||
|
||||
w := postPoolPolicyRequest(t, router, "/v1/responses",
|
||||
`{"model":"shared-compact","stream":false,"input":[{"type":"compaction_trigger"}]}`)
|
||||
// 收窄到兼容族后绝不会发往 anthropic-pool-fake.test。
|
||||
for _, rec := range upstream.capturedSnapshot() {
|
||||
require.NotEqual(t, "anthropic-pool-fake.test", rec.host,
|
||||
"compaction_trigger on bare /v1/responses must never route to generic Anthropic handler; resp=%s", w.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
servermiddleware "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"
|
||||
)
|
||||
|
||||
// compositePoolOwnershipStub 让 resolver 对任意模型返回多平台账号池决策。
|
||||
type compositePoolOwnershipStub struct {
|
||||
platforms []string
|
||||
}
|
||||
|
||||
func (s compositePoolOwnershipStub) ResolveModelOwnership(_ context.Context, _ int64, _ string) (service.CompositeModelOwnership, error) {
|
||||
return service.CompositeModelOwnership{CandidatePlatforms: s.platforms}, nil
|
||||
}
|
||||
|
||||
func newCompositePoolTestRouter(t *testing.T, terminal gin.HandlerFunc, ownership compositePoolOwnershipStub, groupPlatform string) *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: groupPlatform},
|
||||
})
|
||||
c.Next()
|
||||
})))
|
||||
resolver := service.NewCompositeRouteResolver(compositeRouteRepoStub{})
|
||||
resolver.SetModelOwnershipResolver(ownership.ResolveModelOwnership)
|
||||
router.Use(compositeTargetPlatformMiddleware(resolver))
|
||||
for _, path := range []string{"/v1/chat/completions", "/v1/messages", "/v1/responses", "/v1/contents/generations/tasks"} {
|
||||
router.POST(path, terminal)
|
||||
}
|
||||
return router
|
||||
}
|
||||
|
||||
// 账号池决策必须把完整候选集合写入 ctx(去重升序),且不写单一
|
||||
// ResolvedTargetPlatform、不改写 body 模型、来源标记 account_pool。
|
||||
func TestCompositeTargetPlatformMiddlewareWritesPoolDecision(t *testing.T) {
|
||||
seen := false
|
||||
router := newCompositePoolTestRouter(t, func(c *gin.Context) {
|
||||
seen = true
|
||||
candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context())
|
||||
require.Equal(t, []string{service.PlatformDeepseek, service.PlatformZhipu}, candidates)
|
||||
|
||||
_, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context())
|
||||
require.False(t, resolved, "pool decision must not pin a single target platform")
|
||||
|
||||
source, ok := service.CompositeRouteSourceFromContext(c.Request.Context())
|
||||
require.True(t, ok)
|
||||
require.Equal(t, service.CompositeRouteSourceAccountPool, source)
|
||||
|
||||
publicModel, ok := service.RequestedPublicModelFromContext(c.Request.Context())
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "cn-alias", publicModel)
|
||||
|
||||
_, upstream := service.ResolvedUpstreamModelFromContext(c.Request.Context())
|
||||
require.False(t, upstream, "pool decision must not resolve an upstream model")
|
||||
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, `{"model":"cn-alias","messages":[]}`, string(body),
|
||||
"pool request must keep the public model in the body")
|
||||
c.Status(http.StatusNoContent)
|
||||
}, compositePoolOwnershipStub{platforms: []string{service.PlatformZhipu, service.PlatformDeepseek}}, service.PlatformComposite)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"cn-alias","messages":[]}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.True(t, seen, "pool request must reach the terminal handler")
|
||||
require.Equal(t, http.StatusNoContent, w.Code)
|
||||
}
|
||||
|
||||
// composite 文本端点的模型无法解析到任何平台时必须显式 400,不能再静默放行到
|
||||
// 通用网关按通用协议报错。
|
||||
func TestCompositeTargetPlatformMiddlewareRejectsUnresolvedModel(t *testing.T) {
|
||||
for _, path := range []string{"/v1/chat/completions", "/v1/messages", "/v1/responses"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
router := newCompositePoolTestRouter(t, func(c *gin.Context) {
|
||||
t.Fatal("unresolvable composite model must not reach any handler")
|
||||
}, compositePoolOwnershipStub{}, service.PlatformComposite)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"totally-unknown-alias"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, w.Code)
|
||||
require.Contains(t, w.Body.String(), "totally-unknown-alias")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 非文本端点(Seedance 任务等)由 handler 按自身平台语义处理:未解析的模型照常放行,
|
||||
// 不写目标平台/候选池、body 原样保留。
|
||||
func TestCompositeTargetPlatformMiddlewarePassesUnresolvedModelOnNonTextEndpoints(t *testing.T) {
|
||||
const body = `{"model":"doubao-seedance-2-0","content":[{"type":"text","text":"cat"}]}`
|
||||
seen := false
|
||||
router := newCompositePoolTestRouter(t, func(c *gin.Context) {
|
||||
seen = true
|
||||
_, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context())
|
||||
require.False(t, resolved)
|
||||
require.Empty(t, service.CompositeCandidatePlatformsFromContext(c.Request.Context()))
|
||||
got, err := io.ReadAll(c.Request.Body)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, body, string(got))
|
||||
c.Status(http.StatusNoContent)
|
||||
}, compositePoolOwnershipStub{}, service.PlatformComposite)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/contents/generations/tasks", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.True(t, seen)
|
||||
require.Equal(t, http.StatusNoContent, w.Code)
|
||||
}
|
||||
|
||||
// 非 composite 分组保持原行为:无模型解析拦截。
|
||||
func TestCompositeTargetPlatformMiddlewareKeepsNonCompositeBehavior(t *testing.T) {
|
||||
router := newCompositePoolTestRouter(t, func(c *gin.Context) {
|
||||
_, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context())
|
||||
require.False(t, resolved)
|
||||
candidates := service.CompositeCandidatePlatformsFromContext(c.Request.Context())
|
||||
require.Empty(t, candidates)
|
||||
c.Status(http.StatusNoContent)
|
||||
}, compositePoolOwnershipStub{platforms: []string{service.PlatformDeepseek}}, service.PlatformAnthropic)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"weird-model"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusNoContent, w.Code)
|
||||
}
|
||||
|
||||
// 全部 7 类兼容族平台的任意非空子集池都必须进入 OpenAI 网关 handler;
|
||||
// 池大小不参与族判断。
|
||||
func TestDispatchOpenAICompatibleGatewayRoutesAllFamilyPoolSubsets(t *testing.T) {
|
||||
family := []string{
|
||||
service.PlatformOpenAI, service.PlatformGrok,
|
||||
service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek,
|
||||
service.PlatformMiniMax, service.PlatformOpenCodeGo,
|
||||
}
|
||||
subsets := allNonEmptySubsets(family)
|
||||
require.Len(t, subsets, 127)
|
||||
for _, subset := range subsets {
|
||||
var openAI, generic int
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil).WithContext(
|
||||
service.WithCompositeCandidatePlatforms(context.Background(), subset))
|
||||
dispatchOpenAICompatibleGateway(c,
|
||||
func(c *gin.Context) { openAI++ },
|
||||
func(c *gin.Context) { generic++ })
|
||||
require.Equal(t, 1, openAI, "subset=%v must route to the OpenAI gateway handler", subset)
|
||||
require.Zero(t, generic, "subset=%v must not fall through to the generic handler", subset)
|
||||
}
|
||||
}
|
||||
|
||||
// 单一 DeepSeek 目标与全兼容族池走同一个 OpenAI handler,不产生第二次选号
|
||||
// 或不同 sticky 语义。
|
||||
func TestDispatchOpenAICompatibleGatewaySingleDeepSeekMatchesPoolFamily(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{Platform: service.PlatformComposite},
|
||||
})
|
||||
c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformDeepseek))
|
||||
|
||||
var openAI, generic int
|
||||
dispatchOpenAICompatibleGateway(c,
|
||||
func(c *gin.Context) { openAI++ },
|
||||
func(c *gin.Context) { generic++ })
|
||||
require.Equal(t, 1, openAI)
|
||||
require.Zero(t, generic)
|
||||
}
|
||||
|
||||
// 跨原生协议族池(兼容族混 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},
|
||||
{service.PlatformAnthropic},
|
||||
{service.PlatformAntigravity, service.PlatformKimi},
|
||||
{service.PlatformAnthropic, service.PlatformGemini, service.PlatformAntigravity},
|
||||
} {
|
||||
var openAI, generic int
|
||||
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.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)
|
||||
}
|
||||
}
|
||||
|
||||
// 非 composite 分组与解析到原生族单目标的 composite 分组保持既有落通用
|
||||
// handler 的行为(显式 route + 普通分组不回归)。
|
||||
func TestDispatchOpenAICompatibleGatewayKeepsGenericTargets(t *testing.T) {
|
||||
// anthropic 普通分组。
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{Platform: service.PlatformAnthropic},
|
||||
})
|
||||
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)
|
||||
|
||||
// composite 解析到 claude 单目标。
|
||||
c2, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c2.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
c2.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{Platform: service.PlatformComposite},
|
||||
})
|
||||
c2.Request = c2.Request.WithContext(service.WithResolvedTargetPlatform(c2.Request.Context(), service.PlatformAnthropic))
|
||||
openAI, generic = 0, 0
|
||||
dispatchOpenAICompatibleGateway(c2,
|
||||
func(c *gin.Context) { openAI++ },
|
||||
func(c *gin.Context) { generic++ })
|
||||
require.Zero(t, openAI)
|
||||
require.Equal(t, 1, generic)
|
||||
}
|
||||
|
||||
// count_tokens 沿用既有端点语义:兼容族池进 OpenAI CountTokens,跨族池落通用
|
||||
// CountTokens,grok 单目标保留 GrokCountTokens。
|
||||
func TestDispatchOpenAICompatibleCountTokensPoolAndSingle(t *testing.T) {
|
||||
var compatible, grok, generic int
|
||||
handlers := []gin.HandlerFunc{
|
||||
func(c *gin.Context) { compatible++ },
|
||||
func(c *gin.Context) { grok++ },
|
||||
func(c *gin.Context) { generic++ },
|
||||
}
|
||||
|
||||
newContext := func(seed func(c *gin.Context)) *gin.Context {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", nil)
|
||||
seed(c)
|
||||
return c
|
||||
}
|
||||
|
||||
// 兼容族池(含 grok 候选)进 OpenAI CountTokens。
|
||||
dispatchOpenAICompatibleCountTokens(newContext(func(c *gin.Context) {
|
||||
c.Request = c.Request.WithContext(service.WithCompositeCandidatePlatforms(c.Request.Context(),
|
||||
[]string{service.PlatformDeepseek, service.PlatformGrok}))
|
||||
}), handlers[0], handlers[1], handlers[2])
|
||||
require.Equal(t, 1, compatible)
|
||||
require.Zero(t, grok)
|
||||
require.Zero(t, generic)
|
||||
|
||||
// 跨族池落通用 CountTokens(generic 链路对不可计数账号按排除重选处理)。
|
||||
c := newContext(func(c *gin.Context) {
|
||||
c.Request = c.Request.WithContext(service.WithCompositeCandidatePlatforms(c.Request.Context(),
|
||||
[]string{service.PlatformAnthropic, service.PlatformDeepseek}))
|
||||
})
|
||||
compatible, grok, generic = 0, 0, 0
|
||||
dispatchOpenAICompatibleCountTokens(c, handlers[0], handlers[1], handlers[2])
|
||||
require.Zero(t, compatible)
|
||||
require.Zero(t, grok)
|
||||
require.Equal(t, 1, generic)
|
||||
require.False(t, c.IsAborted())
|
||||
|
||||
// grok 单目标保留本地估算路径。
|
||||
compatible, grok, generic = 0, 0, 0
|
||||
dispatchOpenAICompatibleCountTokens(newContext(func(c *gin.Context) {
|
||||
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{Platform: service.PlatformGrok},
|
||||
})
|
||||
}), handlers[0], handlers[1], handlers[2])
|
||||
require.Equal(t, 1, grok)
|
||||
require.Zero(t, compatible)
|
||||
require.Zero(t, generic)
|
||||
|
||||
// anthropic 普通分组保持通用 CountTokens。
|
||||
compatible, grok, generic = 0, 0, 0
|
||||
dispatchOpenAICompatibleCountTokens(newContext(func(c *gin.Context) {
|
||||
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{Platform: service.PlatformAnthropic},
|
||||
})
|
||||
}), handlers[0], handlers[1], handlers[2])
|
||||
require.Equal(t, 1, generic)
|
||||
require.Zero(t, compatible)
|
||||
require.Zero(t, grok)
|
||||
}
|
||||
|
||||
// allNonEmptySubsets 返回 platforms 的全部非空子集(2^n - 1 个)。
|
||||
func allNonEmptySubsets(platforms []string) [][]string {
|
||||
total := 1 << len(platforms)
|
||||
subsets := make([][]string, 0, total-1)
|
||||
for mask := 1; mask < total; mask++ {
|
||||
subset := make([]string, 0, len(platforms))
|
||||
for i, platform := range platforms {
|
||||
if mask&(1<<i) != 0 {
|
||||
subset = append(subset, platform)
|
||||
}
|
||||
}
|
||||
subsets = append(subsets, subset)
|
||||
}
|
||||
return subsets
|
||||
}
|
||||
|
||||
// pool 判定与 service 一致:ctx 同时携带池候选与 resolved pin(Gemini
|
||||
// fallback)时按 single 语义落通用 handler,不按跨族池 400、不进 OpenAI 族。
|
||||
func TestDispatchOpenAICompatibleGatewayDefersToResolvedPinOverPool(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{Platform: service.PlatformComposite},
|
||||
})
|
||||
ctx := service.WithCompositeCandidatePlatforms(c.Request.Context(),
|
||||
[]string{service.PlatformDeepseek, service.PlatformGemini})
|
||||
ctx = service.WithResolvedTargetPlatform(ctx, service.PlatformGemini)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
|
||||
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, "resolved pin must take single semantics over the pool candidates")
|
||||
require.False(t, c.IsAborted())
|
||||
}
|
||||
|
||||
// 入口准入 400 信封按入站协议选择:/v1/messages 系列用 Anthropic 信封。
|
||||
func TestCompositeTargetPlatformMiddlewareUsesAnthropicEnvelopeOnMessages(t *testing.T) {
|
||||
router := newCompositePoolTestRouter(t, func(c *gin.Context) {
|
||||
t.Fatal("unresolvable composite model must not reach any handler")
|
||||
}, compositePoolOwnershipStub{}, service.PlatformComposite)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"totally-unknown-alias","max_tokens":1}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, w.Code)
|
||||
var decoded struct {
|
||||
Type string `json:"type"`
|
||||
Error struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &decoded))
|
||||
require.Equal(t, "error", decoded.Type, "/v1/messages rejections must use the Anthropic error envelope")
|
||||
require.Equal(t, "invalid_request_error", decoded.Error.Type)
|
||||
require.Contains(t, decoded.Error.Message, "totally-unknown-alias")
|
||||
}
|
||||
|
||||
// 跨族池在 /v1/messages 上不再被 400 拒绝:混族池与全兼容族池一样按族归属
|
||||
// 分发(混族落通用 handler),信封由具体 handler 的错误路径决定。
|
||||
func TestCompositeCrossFamilyPoolFallsThroughOnMessagesAndChatCompletions(t *testing.T) {
|
||||
crossFamily := []string{service.PlatformAnthropic, service.PlatformDeepseek}
|
||||
|
||||
// /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))
|
||||
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:混族池同样落通用 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))
|
||||
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
|
||||
}
|
||||
|
||||
// 混族池:进入 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,103 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
servermiddleware "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"
|
||||
)
|
||||
|
||||
// familyRouteHits 记录 stub terminal handler 各自被命中的次数。
|
||||
type familyRouteHits struct {
|
||||
openAICompatible int
|
||||
grok int
|
||||
generic int
|
||||
}
|
||||
|
||||
// newOllamaCloudFamilyRouter 按 RegisterGatewayRoutes 的文本端点装配方式搭最小
|
||||
// 路由:APIKey 注入普通分组(非 composite、无池候选),composite 中间件原样接
|
||||
// 入(对非 composite 分组直接放行),messages/responses/chat completions 走真实
|
||||
// dispatchOpenAICompatibleGateway,count_tokens 走真实
|
||||
// dispatchOpenAICompatibleCountTokens,terminal handler 用 stub 标记实际进入的
|
||||
// 网关家族。
|
||||
func newOllamaCloudFamilyRouter(t *testing.T, groupPlatform string) (*gin.Engine, *familyRouteHits) {
|
||||
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: groupPlatform},
|
||||
})
|
||||
c.Next()
|
||||
})))
|
||||
router.Use(compositeTargetPlatformMiddleware(service.NewCompositeRouteResolver(compositeRouteRepoStub{})))
|
||||
|
||||
hits := &familyRouteHits{}
|
||||
openAICompatible := func(c *gin.Context) { hits.openAICompatible++; c.Status(http.StatusNoContent) }
|
||||
grokCompatible := func(c *gin.Context) { hits.grok++; c.Status(http.StatusNoContent) }
|
||||
generic := func(c *gin.Context) { hits.generic++; c.Status(http.StatusNoContent) }
|
||||
|
||||
// 与 RegisterGatewayRoutes 相同的注册闭包:族分发交给生产 dispatcher。
|
||||
router.POST("/v1/messages", func(c *gin.Context) {
|
||||
dispatchOpenAICompatibleGateway(c, openAICompatible, generic)
|
||||
})
|
||||
router.POST("/v1/responses", func(c *gin.Context) {
|
||||
dispatchOpenAICompatibleGateway(c, openAICompatible, generic)
|
||||
})
|
||||
router.POST("/v1/chat/completions", func(c *gin.Context) {
|
||||
dispatchOpenAICompatibleGateway(c, openAICompatible, generic)
|
||||
})
|
||||
router.POST("/v1/messages/count_tokens", func(c *gin.Context) {
|
||||
dispatchOpenAICompatibleCountTokens(c, openAICompatible, grokCompatible, generic)
|
||||
})
|
||||
return router, hits
|
||||
}
|
||||
|
||||
// ollama_cloud 普通分组(非 composite、无池候选)的三种文本入站端点必须全部
|
||||
// 进入 OpenAI 兼容网关,而不是通用 Anthropic 网关。族判定的唯一源头是
|
||||
// isOpenAICompatibleGatewayFamilyPlatform:清单缺 ollama_cloud 时,下列断言会以
|
||||
// generic 命中的形式失败,而不是静默通过。
|
||||
func TestOllamaCloudGroupRoutesTextEndpointsIntoOpenAICompatibleGateway(t *testing.T) {
|
||||
require.True(t, isOpenAICompatibleGatewayFamilyPlatform(service.PlatformOllamaCloud),
|
||||
"ollama_cloud must belong to the OpenAI-compatible gateway family")
|
||||
|
||||
router, hits := newOllamaCloudFamilyRouter(t, service.PlatformOllamaCloud)
|
||||
|
||||
for _, path := range []string{"/v1/messages", "/v1/responses", "/v1/chat/completions"} {
|
||||
before := *hits
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"llama3.1"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusNoContent, w.Code, "%s must reach a terminal handler", path)
|
||||
require.Equal(t, before.openAICompatible+1, hits.openAICompatible,
|
||||
"%s must route the ollama_cloud group into the OpenAI-compatible gateway", path)
|
||||
require.Equal(t, before.generic, hits.generic,
|
||||
"%s must not fall through to the generic Anthropic gateway", path)
|
||||
}
|
||||
}
|
||||
|
||||
// count_tokens 对 ollama_cloud 普通分组沿用兼容分支语义:走 OpenAI
|
||||
// CountTokens(compatible stub),不落 Grok 本地估算,也不落通用处理。
|
||||
func TestOllamaCloudGroupCountTokensUsesCompatibleBranch(t *testing.T) {
|
||||
router, hits := newOllamaCloudFamilyRouter(t, service.PlatformOllamaCloud)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens",
|
||||
strings.NewReader(`{"model":"llama3.1","messages":[]}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusNoContent, w.Code)
|
||||
require.Equal(t, 1, hits.openAICompatible, "count_tokens must take the compatible branch for ollama_cloud")
|
||||
require.Zero(t, hits.grok)
|
||||
require.Zero(t, hits.generic, "count_tokens must not fall through to the generic handler for ollama_cloud")
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"slices"
|
||||
@@ -330,9 +331,30 @@ func (a *Account) IsCNProvider() bool {
|
||||
return a != nil && IsCNProvider(a.Platform)
|
||||
}
|
||||
|
||||
// IsOllamaCloud 报告账号平台是否为 Ollama Cloud。
|
||||
func (a *Account) IsOllamaCloud() bool {
|
||||
return a != nil && IsOllamaCloud(a.Platform)
|
||||
}
|
||||
|
||||
// GetOllamaCloudAccountMode 返回 Ollama Cloud 账号的额度模式
|
||||
// (AccountModeOllamaLegacy / AccountModeOllamaCredits)。非 ollama_cloud 平台
|
||||
// 或非 apikey 类型返回空串;credentials 未设置或值不认识时默认 legacy
|
||||
// (保守:legacy 有 5h/7d 滚动窗口 → 受阈值停调保护,默认 credits 会让存量
|
||||
// legacy 账号失去保护)。与 GetAccountMode(国产 payg/coding 白名单)互不影响。
|
||||
func (a *Account) GetOllamaCloudAccountMode() string {
|
||||
if a == nil || !a.IsOllamaCloud() || a.Type != AccountTypeAPIKey {
|
||||
return ""
|
||||
}
|
||||
if strings.TrimSpace(a.GetCredential("account_mode")) == AccountModeOllamaCredits {
|
||||
return AccountModeOllamaCredits
|
||||
}
|
||||
return AccountModeOllamaLegacy
|
||||
}
|
||||
|
||||
// IsOpenAICompatible 报告账号是否走 OpenAI 网关(OpenAI 协议族)。
|
||||
// openai/grok 原生走 OpenAI 网关;国产供应商同为 OpenAI Chat Completions
|
||||
// 兼容上游,也经 OpenAI 网关转发。OpenCode 同样经 OpenAI 网关按模型分流。
|
||||
// 兼容上游,也经 OpenAI 网关转发。OpenCode 与 Ollama Cloud 同样经 OpenAI
|
||||
// 网关按模型/协议分流。
|
||||
func (a *Account) IsOpenAICompatible() bool {
|
||||
return a != nil && domain.UsesOpenAIGateway(a.Platform)
|
||||
}
|
||||
@@ -460,6 +482,44 @@ func (a *Account) GetCredentialAsInt64(key string) int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
// GetCredentialAsFloat64 返回浮点型凭据值,缺失、无法解析或非有限值(NaN/±Inf,
|
||||
// strconv.ParseFloat 接受 "Inf"/"NaN")时返回 0。与 GetCredentialAsInt64 同样的类型
|
||||
// 容忍(JSONB 数字为 float64/json.Number,运营也可能手写成字符串),供 Ollama Cloud
|
||||
// monthly_credit_usd 等金额键读取;非有限值进入 DTO 会让 JSON 序列化失败。
|
||||
func (a *Account) GetCredentialAsFloat64(key string) float64 {
|
||||
if f := a.getCredentialAsFloat64(key); !math.IsNaN(f) && !math.IsInf(f, 0) {
|
||||
return f
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (a *Account) getCredentialAsFloat64(key string) float64 {
|
||||
if a == nil || a.Credentials == nil {
|
||||
return 0
|
||||
}
|
||||
val, ok := a.Credentials[key]
|
||||
if !ok || val == nil {
|
||||
return 0
|
||||
}
|
||||
switch v := val.(type) {
|
||||
case float64:
|
||||
return v
|
||||
case int64:
|
||||
return float64(v)
|
||||
case int:
|
||||
return float64(v)
|
||||
case json.Number:
|
||||
if f, err := v.Float64(); err == nil {
|
||||
return f
|
||||
}
|
||||
case string:
|
||||
if f, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil {
|
||||
return f
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (a *Account) IsTempUnschedulableEnabled() bool {
|
||||
if a.Credentials == nil {
|
||||
return false
|
||||
@@ -1017,8 +1077,32 @@ func (a *Account) isModelMappingSupported(requestedModel string) bool {
|
||||
if a.Platform == PlatformDeepseek {
|
||||
return isDeepseekServableModel(requestedModel)
|
||||
}
|
||||
// ollama_cloud 运行时白名单:空映射时 extra.allowed_models 清单就是
|
||||
// 唯一可出站白名单;既无映射也无清单则 deny-all(不支持任何模型)。
|
||||
// 与保存期门禁 validateOllamaCloudAccountModelPricingGate 的「mapping
|
||||
// 或清单至少其一」语义对齐。空映射下请求的公开模型名即出站名
|
||||
// (ResolveMappedModel 原样透传),清单项又是按出站名断言过定价的,
|
||||
// 因此对公开名做精确匹配即可;保存期门禁已确保清单不含通配符
|
||||
// (通配符串无法解析到定价,保存即被拒)。
|
||||
if a.IsOllamaCloud() {
|
||||
allowed := ollamaCloudOutboundModelNames(a)
|
||||
if len(allowed) == 0 {
|
||||
return false
|
||||
}
|
||||
trimmed := strings.TrimSpace(requestedModel)
|
||||
for _, model := range allowed {
|
||||
if model == trimmed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true // 无映射 = 允许所有
|
||||
}
|
||||
if a.IsOllamaCloud() {
|
||||
mapped, matched := a.ResolveMappedModel(requestedModel)
|
||||
return matched && strings.TrimSpace(mapped) != ""
|
||||
}
|
||||
if mappingSupportsRequestedModel(mapping, requestedModel) {
|
||||
return true
|
||||
}
|
||||
@@ -1540,8 +1624,8 @@ func (a *Account) IsOpenAIApiKey() bool {
|
||||
}
|
||||
|
||||
// GetOpenAIBaseURL 解析 OpenAI 协议族账号的上游 base_url。
|
||||
// 适用 openai、国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)与 OpenCode Go;
|
||||
// grok 走 GetGrokBaseURL,此处对 grok 返回 "" 以保持原有行为。
|
||||
// 适用 openai、国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)、OpenCode Go 与
|
||||
// Ollama Cloud;grok 走 GetGrokBaseURL,此处对 grok 返回 "" 以保持原有行为。
|
||||
func (a *Account) GetOpenAIBaseURL() string {
|
||||
if !a.IsOpenAI() && !a.IsMultiProtocolAPIKey() {
|
||||
return ""
|
||||
@@ -1562,6 +1646,11 @@ func (a *Account) GetOpenAIBaseURL() string {
|
||||
if baseURL := a.defaultProviderBaseURL(APIProtocolChatCompletions); baseURL != "" {
|
||||
return baseURL
|
||||
}
|
||||
if a.IsMultiProtocolAPIKey() {
|
||||
// 多协议网关的缺省端点必须由 provider profile 给出:回落官方域名会把第三方
|
||||
// key 明文发到 api.openai.com。
|
||||
return ""
|
||||
}
|
||||
return "https://api.openai.com"
|
||||
}
|
||||
|
||||
@@ -1583,10 +1672,11 @@ func (a *Account) IsCodingPlan() bool {
|
||||
return a.GetAccountMode() == AccountModeCoding
|
||||
}
|
||||
|
||||
// GetAPIProtocol 返回国产供应商账号的上游 API 协议。存储于
|
||||
// GetAPIProtocol 返回多协议 API Key 账号的上游 API 协议。存储于
|
||||
// credentials["api_protocol"];缺失或与平台不匹配时回退 chat_completions
|
||||
// (与既有行为完全一致)。responses 协议仅 deepseek / kimi / minimax 支持(官方原生
|
||||
// Responses 端点,适配 Codex);zhipu 无此端点。
|
||||
// (与既有行为完全一致),opencode_go / ollama_cloud 例外:缺省为 adaptive
|
||||
// (按入站协议选择供应商原生端点)。responses 协议仅 deepseek / kimi / minimax 支持
|
||||
// (官方原生 Responses 端点,适配 Codex);zhipu 无此端点。
|
||||
func (a *Account) GetAPIProtocol() string {
|
||||
if a == nil || !a.IsMultiProtocolAPIKey() {
|
||||
return APIProtocolChatCompletions
|
||||
@@ -1603,6 +1693,9 @@ func (a *Account) GetAPIProtocol() string {
|
||||
case APIProtocolChatCompletions:
|
||||
return APIProtocolChatCompletions
|
||||
}
|
||||
if profile := a.providerProfile(); profile != nil && profile.DefaultAPIProtocol != "" {
|
||||
return profile.DefaultAPIProtocol
|
||||
}
|
||||
// 按模型分流的供应商(多模型聚合平台)未显式配置时默认 adaptive。
|
||||
if a.routesByModel() {
|
||||
return APIProtocolAdaptive
|
||||
@@ -1612,7 +1705,8 @@ func (a *Account) GetAPIProtocol() string {
|
||||
|
||||
// SupportsNativeCNResponses 报告该国产供应商是否提供原生 Responses 端点。
|
||||
// DeepSeek 官方为 /responses(无 /v1);Kimi 按量付费与 Coding Plan 均为
|
||||
// /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses。
|
||||
// /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses;
|
||||
// Ollama Cloud 为 /v1/responses(non-stateful,见 normalizeDeepSeekResponsesRequestBody)。
|
||||
func (a *Account) SupportsNativeCNResponses() bool {
|
||||
return a.providerSupportsProtocol(APIProtocolResponses)
|
||||
}
|
||||
|
||||
@@ -217,7 +217,7 @@ func TestDuplicateCreatePathMintsFreshSeedWhenEligible(t *testing.T) {
|
||||
func TestAccountServiceCreateAndUpdateCodexSeedLifecycle(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := NewAccountService(repo, nil)
|
||||
svc := NewAccountService(repo, nil, nil)
|
||||
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "legacy-create",
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetOllamaCloudAccountMode(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
platform string
|
||||
accountType string
|
||||
credentials map[string]any
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "defaults to legacy when unset",
|
||||
platform: PlatformOllamaCloud,
|
||||
accountType: AccountTypeAPIKey,
|
||||
credentials: nil,
|
||||
want: AccountModeOllamaLegacy,
|
||||
},
|
||||
{
|
||||
name: "explicit legacy",
|
||||
platform: PlatformOllamaCloud,
|
||||
accountType: AccountTypeAPIKey,
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaLegacy},
|
||||
want: AccountModeOllamaLegacy,
|
||||
},
|
||||
{
|
||||
name: "explicit credits",
|
||||
platform: PlatformOllamaCloud,
|
||||
accountType: AccountTypeAPIKey,
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaCredits},
|
||||
want: AccountModeOllamaCredits,
|
||||
},
|
||||
{
|
||||
name: "unknown value falls back to legacy",
|
||||
platform: PlatformOllamaCloud,
|
||||
accountType: AccountTypeAPIKey,
|
||||
credentials: map[string]any{"account_mode": "bogus"},
|
||||
want: AccountModeOllamaLegacy,
|
||||
},
|
||||
{
|
||||
name: "oauth account returns empty",
|
||||
platform: PlatformOllamaCloud,
|
||||
accountType: AccountTypeOAuth,
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaCredits},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "non ollama platform returns empty",
|
||||
platform: PlatformOpenAI,
|
||||
accountType: AccountTypeAPIKey,
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaCredits},
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
account := &Account{
|
||||
Platform: tc.platform,
|
||||
Type: tc.accountType,
|
||||
Credentials: tc.credentials,
|
||||
}
|
||||
require.Equal(t, tc.want, account.GetOllamaCloudAccountMode())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAccountMode_IgnoresOllamaCloudModes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// 防回归:GetAccountMode 是国产 payg/coding 的白名单解析器,
|
||||
// 不得被 ollama_cloud 的新 mode 值污染。
|
||||
for _, mode := range []string{AccountModeOllamaLegacy, AccountModeOllamaCredits} {
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"account_mode": mode},
|
||||
}
|
||||
require.Empty(t, account.GetAccountMode())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
)
|
||||
|
||||
// OllamaCloudAllowedModelsExtraKey 是 ollama_cloud 账号在 model_mapping 为空时
|
||||
// 声明可出站模型清单的 extra 键。值为字符串数组(如 ["gpt-oss:120b","qwen3.5:397b"])。
|
||||
//
|
||||
// 背景:account.IsModelSupported 对空 model_mapping 一律放行所有模型名,因此
|
||||
// 只扫 mapping 目标值的校验对空 mapping 账号零覆盖;ollama_cloud 的计费又是
|
||||
// 白名单语义(未列价的模型名显式拒绝计费),所以保存期必须拿到一个有限的
|
||||
// 可出站模型名集合来断言「全部可被 GetModelPricing 解析」,否则只能全量拒绝。
|
||||
const OllamaCloudAllowedModelsExtraKey = "allowed_models"
|
||||
|
||||
// accountModelPricingLookup 是保存期无价门禁所需的最小定价查询面,
|
||||
// *BillingService 以同一查价链(LiteLLM → fallback,含 :tag 两级 fallback)实现。
|
||||
type accountModelPricingLookup interface {
|
||||
GetModelPricing(model string) (*ModelPricing, error)
|
||||
}
|
||||
|
||||
// validateOllamaCloudAccountModelPricingGate 是 B2-③ 的保存期无价门禁:
|
||||
// ollama_cloud 账号保存时断言「该账号可出站的模型名集合均可被 GetModelPricing 解析」。
|
||||
//
|
||||
// 可出站集合的取法与 account.IsModelSupported 的放行语义对齐:
|
||||
// - 非空 model_mapping → 扫全部目标值(映射后真正发往上游的名字);
|
||||
// - 空 model_mapping → 必须同时提供 OllamaCloudAllowedModelsExtraKey 显式清单,
|
||||
// 清单全量纳入断言;空 mapping 且无清单一律拒绝(此时账号对全部模型名放行,
|
||||
// 门禁对它零覆盖,是静默零计费的敞口)。
|
||||
//
|
||||
// 只对 ollama_cloud 生效:其它平台的保存路径行为不变(多数平台定价缺失走
|
||||
// 请求期零成本兜底,属于既有的全平台 fail-open 设计,见
|
||||
// openai_gateway_usage.go 的 pricing_missing_record_zero_cost 分支)。
|
||||
// lookup 为 nil 时跳过(生产 wire 必然注入 *BillingService;仅直接构造
|
||||
// struct 的单元测试/内部调用会出现)。
|
||||
//
|
||||
// 与请求期转发前预检的刻意不对称(设计限制,非缺陷):请求期预检走完整定价
|
||||
// 解析链(Group → Channel → LiteLLM → fallback),「只有渠道价/分组价」的模型
|
||||
// 运行时允许出站;本门禁只查全局基础价(GetModelPricing,LiteLLM → fallback),
|
||||
// 因此仅在渠道/分组层配置定价的模型会在保存时被 MODEL_PRICING_MISSING 拒绝。
|
||||
// 这是刻意比运行时更严格的策略:账号与分组是多对多,保存时拿不到确定的
|
||||
// channel/group 上下文,「门禁查渠道价」在语义上不成立;而 ollama 的真实模型
|
||||
// 全部有全局基础价,实践中不会误拒。
|
||||
func validateOllamaCloudAccountModelPricingGate(lookup accountModelPricingLookup, account *Account) error {
|
||||
if lookup == nil || account == nil || !account.IsOllamaCloud() {
|
||||
return nil
|
||||
}
|
||||
|
||||
models := ollamaCloudOutboundModelNames(account)
|
||||
if len(models) == 0 {
|
||||
return infraerrors.BadRequest("MODEL_PRICING_MISSING",
|
||||
fmt.Sprintf("ollama_cloud 账号 model_mapping 为空时必须在 extra.%s 提供显式的可出站模型清单,否则无法保证全部模型可计费",
|
||||
OllamaCloudAllowedModelsExtraKey))
|
||||
}
|
||||
|
||||
unpriced := make([]string, 0)
|
||||
for _, model := range models {
|
||||
// 计费侧对托管模型上游(accountServesHostedModels,含 ollama_cloud)会剔除未在渠道/分组
|
||||
// 显式配价的 claude-* 候选;保存期门禁不接受仅渠道/分组层定价,故含 claude 的出站模型名
|
||||
// 必须一并拦截,避免通过门禁后在记账阶段落入 $0。
|
||||
if strings.Contains(strings.ToLower(model), "claude") {
|
||||
unpriced = append(unpriced, model)
|
||||
continue
|
||||
}
|
||||
if _, err := lookup.GetModelPricing(model); err != nil {
|
||||
unpriced = append(unpriced, model)
|
||||
}
|
||||
}
|
||||
if len(unpriced) > 0 {
|
||||
return infraerrors.BadRequest("MODEL_PRICING_MISSING",
|
||||
fmt.Sprintf("以下 ollama_cloud 模型缺少全局基础定价,无法保证计费。此校验要求每个可出站模型都有全局基础价(LiteLLM 或内置 fallback),仅在渠道/分组层配置的定价不会被接受:请先在全局模型定价中补价,或调整 model_mapping/extra.%s。缺价模型: %s",
|
||||
OllamaCloudAllowedModelsExtraKey, strings.Join(unpriced, ", ")))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ollamaCloudPricingGateRevalidationNeeded 报告一次账号更新是否需要重跑保存期无价门禁。
|
||||
//
|
||||
// 门禁只拦「可能改变可出站模型集合或影响调度准入」的更新:
|
||||
// - platform 变化(可出站模型集合的判定语义随平台切换);
|
||||
// - 可出站模型集合的实际输入变化(prevOutboundSet 是更新前
|
||||
// ollamaCloudOutboundModelNames 的快照,覆盖 credentials.model_mapping 与
|
||||
// extra.allowed_models 两条来源);
|
||||
// - 从不可调度改为可调度(启用):存量 legacy 账号(无 mapping/清单)的维护性
|
||||
// 编辑平时放行,但启用调度前必须补齐并通过门禁。
|
||||
//
|
||||
// name、notes、并发数、优先级、状态停用等维护性更新放行 —— 否则迁移过来的存量
|
||||
// 账号连改备注都会被 MODEL_PRICING_MISSING 锁死。调用方必须在应用本次请求的
|
||||
// 字段变更**之前**采集 prevPlatform / prevOutboundSet / prevSchedulable 快照。
|
||||
func ollamaCloudPricingGateRevalidationNeeded(prevPlatform string, prevOutboundSet []string, prevSchedulable bool, next *Account) bool {
|
||||
if next == nil || !next.IsOllamaCloud() {
|
||||
return false
|
||||
}
|
||||
if prevPlatform != next.Platform {
|
||||
return true
|
||||
}
|
||||
nextSet := append([]string(nil), ollamaCloudOutboundModelNames(next)...)
|
||||
slices.Sort(prevOutboundSet)
|
||||
slices.Sort(nextSet)
|
||||
if !slices.Equal(prevOutboundSet, nextSet) {
|
||||
return true
|
||||
}
|
||||
return !prevSchedulable && ollamaCloudSchedulableBySave(next)
|
||||
}
|
||||
|
||||
// ollamaCloudSchedulableBySave 只看保存路径能改变的两个调度准入开关
|
||||
// (status 是否 active、手动 Schedulable 开关),不含时间窗等运行态。
|
||||
func ollamaCloudSchedulableBySave(a *Account) bool {
|
||||
return a != nil && a.IsActive() && a.Schedulable
|
||||
}
|
||||
|
||||
// GetOllamaCloudOutboundModels 返回 ollama_cloud 账号配置的可出站模型列表(model_mapping
|
||||
// 目标或 extra.allowed_models 白名单),供管理端账号可用模型与连接测试默认选项复用。
|
||||
func (a *Account) GetOllamaCloudOutboundModels() []string {
|
||||
if a == nil || !a.IsOllamaCloud() {
|
||||
return nil
|
||||
}
|
||||
return ollamaCloudOutboundModelNames(a)
|
||||
}
|
||||
|
||||
// ollamaCloudOutboundModelNames 收集 ollama_cloud 账号的可出站模型名集合
|
||||
// (去重、去空)。空 mapping 且无有效清单时返回 nil。
|
||||
//
|
||||
// 清单值兼容两种形态:JSON 反序列化出的 []any(元素为 string),以及程序化
|
||||
// 构造的 []string。非字符串元素跳过(由清单「缺失即拒绝」的语义兜底不严的
|
||||
// 情况——含非字符串元素的清单视同未提供,见下方 return nil)。
|
||||
func ollamaCloudOutboundModelNames(account *Account) []string {
|
||||
seen := make(map[string]struct{})
|
||||
out := make([]string, 0)
|
||||
appendModel := func(model string) {
|
||||
trimmed := strings.TrimSpace(model)
|
||||
if trimmed == "" {
|
||||
return
|
||||
}
|
||||
if _, dup := seen[trimmed]; dup {
|
||||
return
|
||||
}
|
||||
seen[trimmed] = struct{}{}
|
||||
out = append(out, trimmed)
|
||||
}
|
||||
|
||||
if mapping := account.GetModelMapping(); len(mapping) > 0 {
|
||||
for _, target := range mapping {
|
||||
appendModel(target)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
switch list := account.Extra[OllamaCloudAllowedModelsExtraKey].(type) {
|
||||
case []any:
|
||||
for _, item := range list {
|
||||
model, ok := item.(string)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
appendModel(model)
|
||||
}
|
||||
case []string:
|
||||
for _, model := range list {
|
||||
appendModel(model)
|
||||
}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,687 @@
|
||||
package service
|
||||
|
||||
// B2-③ 保存期无价门禁回归测试(ollama_cloud):
|
||||
// ① mapping 目标含未定价名 → Create/Update 返回 400 MODEL_PRICING_MISSING 且
|
||||
// message 含该模型名;
|
||||
// ② 空 mapping 无 allowed_models 清单 → 400;
|
||||
// ③ 空 mapping + 显式清单(全部已定价,含真实 :tag 形态)→ 通过;
|
||||
// ④ 非 ollama 平台同样配置不受影响(回归)。
|
||||
//
|
||||
// 门禁同时接在两条保存路径上:
|
||||
// - AccountService.Create/Update(本文件,spec 权威位置);
|
||||
// - adminServiceImpl.CreateAccount/UpdateAccount(生产 admin handler 实际走
|
||||
// 的路径,见 TestAdminCreateAccount.../TestAdminUpdateAccount...)。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newOllamaGateAccountService(repo AccountRepository) *AccountService {
|
||||
return NewAccountService(repo, nil, NewBillingService(&config.Config{}, nil))
|
||||
}
|
||||
|
||||
func requireModelPricingMissing(t *testing.T, err error, wantNames ...string) {
|
||||
t.Helper()
|
||||
require.Error(t, err)
|
||||
require.Equal(t, 400, infraerrors.Code(err), "必须映射为 400: %v", err)
|
||||
require.Equal(t, "MODEL_PRICING_MISSING", infraerrors.Reason(err))
|
||||
for _, name := range wantNames {
|
||||
require.Contains(t, infraerrors.Message(err), name, "message 必须列出未定价模型名")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountServiceCreateOllamaCloudPricingGate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("mapping目标含未定价名_400并列出该名", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
_, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "ollama-bad-mapping",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
require.Empty(t, repo.accounts, "被拒绝的账号不得落库")
|
||||
})
|
||||
|
||||
t.Run("空mapping且无清单_400", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
_, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "ollama-no-list",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
})
|
||||
requireModelPricingMissing(t, err)
|
||||
require.Contains(t, infraerrors.Message(err), OllamaCloudAllowedModelsExtraKey)
|
||||
require.Empty(t, repo.accounts)
|
||||
})
|
||||
|
||||
t.Run("空mapping加已定价清单_通过", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "ollama-with-list",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k", "base_url": "https://ollama.com/v1"},
|
||||
Extra: map[string]any{
|
||||
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud", "qwen3.5:397b"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, created)
|
||||
require.NotEmpty(t, repo.accounts)
|
||||
})
|
||||
|
||||
t.Run("mapping目标全部已定价_通过", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
_, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "ollama-priced-mapping",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "k",
|
||||
"model_mapping": map[string]any{"big": "gpt-oss:120b", "coder": "qwen3.5:397b"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("非ollama平台不受影响_回归", func(t *testing.T) {
|
||||
for _, platform := range []string{PlatformOpenAI, PlatformKimi, PlatformAnthropic} {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "legacy-" + platform,
|
||||
Platform: platform,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
})
|
||||
require.NoError(t, err, "platform=%s 的空 mapping 账号保存不得被门禁拦截", platform)
|
||||
require.NotNil(t, created)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAccountServiceUpdateOllamaCloudPricingGate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
newOllamaAccount := func(t *testing.T) (*upstreamBillingProbeAccountRepo, *AccountService, *Account) {
|
||||
t.Helper()
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "ollama-update",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "k",
|
||||
"model_mapping": map[string]any{"big": "gpt-oss:120b"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return repo, svc, created
|
||||
}
|
||||
|
||||
t.Run("改成未定价目标_400", func(t *testing.T) {
|
||||
_, svc, created := newOllamaAccount(t)
|
||||
_, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
|
||||
Credentials: &map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
})
|
||||
|
||||
t.Run("清空mapping且无清单_400", func(t *testing.T) {
|
||||
_, svc, created := newOllamaAccount(t)
|
||||
_, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
|
||||
Credentials: &map[string]any{"api_key": "k"},
|
||||
})
|
||||
requireModelPricingMissing(t, err)
|
||||
})
|
||||
|
||||
t.Run("换成已定价清单_通过", func(t *testing.T) {
|
||||
repo, svc, created := newOllamaAccount(t)
|
||||
updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
|
||||
Credentials: &map[string]any{"api_key": "k"},
|
||||
Extra: &map[string]any{
|
||||
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []any{"gpt-oss:20b"}, updated.Extra[OllamaCloudAllowedModelsExtraKey])
|
||||
require.NotNil(t, repo.accounts[created.ID])
|
||||
})
|
||||
|
||||
t.Run("非ollama平台更新不受影响_回归", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "kimi-update",
|
||||
Platform: PlatformKimi,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "kimi-k2-0905-preview"}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
|
||||
Credentials: &map[string]any{"api_key": "k"},
|
||||
})
|
||||
require.NoError(t, err, "kimi 账号清空 mapping 的更新不得被门禁拦截")
|
||||
require.NotNil(t, updated)
|
||||
})
|
||||
}
|
||||
|
||||
// 生产 admin handler 实际走的保存路径(adminServiceImpl.CreateAccount/UpdateAccount)
|
||||
// 同样必须挂门禁——只测 AccountService 而 admin 路径漏挂,等于门禁空转。
|
||||
func TestAdminCreateAccountOllamaCloudPricingGate(t *testing.T) {
|
||||
svc := &adminServiceImpl{accountRepo: &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
_, err := svc.CreateAccount(context.Background(), &CreateAccountInput{
|
||||
Name: "ollama-admin-unpriced",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
|
||||
SkipDefaultGroupBind: true,
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
|
||||
created, err := svc.CreateAccount(context.Background(), &CreateAccountInput{
|
||||
Name: "ollama-admin-priced",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud", "nemotron-3-super"}},
|
||||
SkipDefaultGroupBind: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, created)
|
||||
}
|
||||
|
||||
func TestAdminUpdateAccountOllamaCloudPricingGate(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
|
||||
created, err := svc.CreateAccount(context.Background(), &CreateAccountInput{
|
||||
Name: "ollama-admin-update",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}},
|
||||
SkipDefaultGroupBind: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = svc.UpdateAccount(context.Background(), created.ID, &UpdateAccountInput{
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
|
||||
updated, err := svc.UpdateAccount(context.Background(), created.ID, &UpdateAccountInput{
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "qwen3.5:397b"}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, updated)
|
||||
}
|
||||
|
||||
// gate helper 单元测试:清单值形态与非 ollama 平台短路。
|
||||
func TestOllamaCloudOutboundModelNames(t *testing.T) {
|
||||
account := &Account{Platform: PlatformOllamaCloud, Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"a": "gpt-oss:120b", "b": "", "c": "qwen3.5:397b", "d": "gpt-oss:120b"},
|
||||
}}
|
||||
// map 迭代顺序不定,只断言集合内容(去空、去重)。
|
||||
require.ElementsMatch(t, []string{"gpt-oss:120b", "qwen3.5:397b"}, ollamaCloudOutboundModelNames(account))
|
||||
|
||||
account = &Account{Platform: PlatformOllamaCloud, Extra: map[string]any{
|
||||
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b", " "},
|
||||
}}
|
||||
require.Equal(t, []string{"gpt-oss:20b"}, ollamaCloudOutboundModelNames(account))
|
||||
|
||||
account = &Account{Platform: PlatformOllamaCloud, Extra: map[string]any{
|
||||
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b", 42},
|
||||
}}
|
||||
require.Nil(t, ollamaCloudOutboundModelNames(account), "含非字符串元素的清单视同未提供(拒绝语义)")
|
||||
|
||||
account = &Account{Platform: PlatformOpenAI}
|
||||
require.Nil(t, ollamaCloudOutboundModelNames(account))
|
||||
}
|
||||
|
||||
// 门禁触发收窄回归:缺 mapping/清单的存量 legacy 账号不得被维护性更新锁死,
|
||||
// 只有可能改变「可出站模型集合」或影响调度准入的更新才重验。
|
||||
func TestAccountServiceUpdateOllamaCloudPricingGateOnlyOnModelSetOrSchedulingChange(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
seedLegacyAccount := func(t *testing.T) (*upstreamBillingProbeAccountRepo, *AccountService, *Account) {
|
||||
t.Helper()
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
// legacy 形态:无 model_mapping、无 allowed_models 清单。Create 路径有门禁,
|
||||
// 直接经 repo 落库模拟迁移过来的存量账号。
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Name: "ollama-legacy",
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
}
|
||||
require.NoError(t, repo.Create(ctx, account))
|
||||
return repo, svc, account
|
||||
}
|
||||
|
||||
t.Run("legacy账号仅改name_必须成功", func(t *testing.T) {
|
||||
_, svc, account := seedLegacyAccount(t)
|
||||
updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Name: strPtr("ollama-legacy-renamed")})
|
||||
require.NoError(t, err, "维护性更新(仅改 name)不得被 MODEL_PRICING_MISSING 拦截")
|
||||
require.Equal(t, "ollama-legacy-renamed", updated.Name)
|
||||
})
|
||||
|
||||
t.Run("legacy账号改notes与并发数_放行", func(t *testing.T) {
|
||||
_, svc, account := seedLegacyAccount(t)
|
||||
concurrency := 5
|
||||
updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{
|
||||
Notes: strPtr("migrated account"),
|
||||
Concurrency: &concurrency,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "migrated account", *updated.Notes)
|
||||
require.Equal(t, 5, updated.Concurrency)
|
||||
})
|
||||
|
||||
t.Run("legacy账号加未定价mapping_仍400", func(t *testing.T) {
|
||||
_, svc, account := seedLegacyAccount(t)
|
||||
_, err := svc.Update(ctx, account.ID, UpdateAccountRequest{
|
||||
Credentials: &map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
})
|
||||
|
||||
t.Run("legacy账号加未定价清单_仍400", func(t *testing.T) {
|
||||
_, svc, account := seedLegacyAccount(t)
|
||||
_, err := svc.Update(ctx, account.ID, UpdateAccountRequest{
|
||||
Extra: &map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
})
|
||||
|
||||
t.Run("不可调度改可调度_必须校验", func(t *testing.T) {
|
||||
repo, svc, account := seedLegacyAccount(t)
|
||||
// 停用态(手动开关仍开):经 Update 把 status 改回 active 即「启用」,
|
||||
// 必须先通过门禁。
|
||||
repo.accounts[account.ID].Status = StatusDisabled
|
||||
_, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Status: strPtr(StatusActive)})
|
||||
requireModelPricingMissing(t, err)
|
||||
})
|
||||
|
||||
t.Run("停用legacy账号_放行", func(t *testing.T) {
|
||||
_, svc, account := seedLegacyAccount(t)
|
||||
updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Status: strPtr(StatusDisabled)})
|
||||
require.NoError(t, err, "停用(退出调度准入)属于维护性更新,不得被拦截")
|
||||
require.Equal(t, StatusDisabled, updated.Status)
|
||||
})
|
||||
|
||||
t.Run("非ollama平台行为不变_回归", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "kimi-legacy-update",
|
||||
Platform: PlatformKimi,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
|
||||
Name: strPtr("kimi-renamed"),
|
||||
Notes: strPtr("notes only"),
|
||||
})
|
||||
require.NoError(t, err, "非 ollama 平台的维护性更新行为必须保持不变")
|
||||
require.Equal(t, "kimi-renamed", updated.Name)
|
||||
})
|
||||
}
|
||||
|
||||
// 门禁触发收窄在生产 admin handler 路径(adminServiceImpl.UpdateAccount)同样生效:
|
||||
// 全对象 PUT 编辑会原样带回 credentials/extra,集合未变时不得重验锁死 legacy 账号。
|
||||
func TestAdminUpdateAccountOllamaCloudPricingGateOnlyOnModelSetOrSchedulingChange(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Name: "ollama-admin-legacy",
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
}
|
||||
require.NoError(t, repo.Create(ctx, account))
|
||||
|
||||
t.Run("仅改name_必须成功", func(t *testing.T) {
|
||||
updated, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{Name: "ollama-admin-legacy-renamed"})
|
||||
require.NoError(t, err, "admin 路径维护性更新(仅改 name)不得被拦截")
|
||||
require.Equal(t, "ollama-admin-legacy-renamed", updated.Name)
|
||||
})
|
||||
|
||||
t.Run("全对象PUT带回原credentials与extra_不重验放行", func(t *testing.T) {
|
||||
updated, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{
|
||||
Name: "ollama-admin-legacy",
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
Extra: map[string]any{"remark": "unchanged set"},
|
||||
})
|
||||
require.NoError(t, err, "可出站集合未变的全对象 PUT 不得触发门禁")
|
||||
require.NotNil(t, updated)
|
||||
})
|
||||
|
||||
t.Run("加未定价mapping_仍400", func(t *testing.T) {
|
||||
_, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
})
|
||||
|
||||
t.Run("不可调度改可调度_必须校验", func(t *testing.T) {
|
||||
repo.accounts[account.ID].Status = StatusDisabled
|
||||
_, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{Status: StatusActive})
|
||||
requireModelPricingMissing(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 评审收口回归:三条此前绕过门禁的 admin 写路径(BulkUpdateAccounts /
|
||||
// DuplicateAccount / SetAccountSchedulable)。定位是「门禁不可绕过」的一致性——
|
||||
// 运行时白名单与转发前定价预检已兜底最坏情形,本组测试锁的是保存期拦截行为
|
||||
// 本身:不合规整批拒绝且不落库、错误点名账号、维护性更新与非 ollama 平台放行。
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// ollamaGateSchedulableCall 记录一次 SetSchedulable 调用,用于断言「拒绝时未触达 DB」。
|
||||
type ollamaGateSchedulableCall struct {
|
||||
accountID int64
|
||||
schedulable bool
|
||||
}
|
||||
|
||||
// ollamaGateAdminRepoStub 在 upstreamBillingProbeAccountRepo 之上补齐本组回归所需的
|
||||
// 两个写入口:SetSchedulable(记录调用)与 CreateWithAccountGroups(复制路径的原子创建)。
|
||||
type ollamaGateAdminRepoStub struct {
|
||||
*upstreamBillingProbeAccountRepo
|
||||
schedulableCalls []ollamaGateSchedulableCall
|
||||
}
|
||||
|
||||
func newOllamaGateAdminRepoStub() *ollamaGateAdminRepoStub {
|
||||
return &ollamaGateAdminRepoStub{
|
||||
upstreamBillingProbeAccountRepo: &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ollamaGateAdminRepoStub) SetSchedulable(_ context.Context, id int64, schedulable bool) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if account := r.accounts[id]; account != nil {
|
||||
account.Schedulable = schedulable
|
||||
}
|
||||
r.schedulableCalls = append(r.schedulableCalls, ollamaGateSchedulableCall{accountID: id, schedulable: schedulable})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ollamaGateAdminRepoStub) CreateWithAccountGroups(ctx context.Context, account *Account, _ []AccountGroup) error {
|
||||
return r.Create(ctx, account)
|
||||
}
|
||||
|
||||
// seedOllamaGateAccount 直接经 repo 落库一个账号(绕过 Create 路径门禁),
|
||||
// 用于模拟「门禁上线前迁移过来的存量账号」。
|
||||
func seedOllamaGateAccount(t *testing.T, repo *ollamaGateAdminRepoStub, mutate func(*Account)) *Account {
|
||||
t.Helper()
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Name: "ollama-gate-seed",
|
||||
Status: StatusActive,
|
||||
Schedulable: false,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(account)
|
||||
}
|
||||
require.NoError(t, repo.Create(context.Background(), account))
|
||||
return account
|
||||
}
|
||||
|
||||
func TestAdminBulkUpdateAccountsOllamaCloudPricingGate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) {
|
||||
t.Helper()
|
||||
repo := newOllamaGateAdminRepoStub()
|
||||
svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
return repo, svc
|
||||
}
|
||||
|
||||
t.Run("bulk写入未定价mapping_整批拒绝点名账号且不落库", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
first := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-a" })
|
||||
second := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-bulk-b"
|
||||
a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}}
|
||||
})
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{first.ID, second.ID},
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
// 批量操作要能定位:错误信息必须点名每个不合规账号。
|
||||
require.Contains(t, infraerrors.Message(err), first.Name)
|
||||
require.Contains(t, infraerrors.Message(err), second.Name)
|
||||
// 整批拒绝:任何账号都不得写入。
|
||||
require.Empty(t, repo.bulkUpdates, "被拒绝的批量更新不得触达 DB")
|
||||
})
|
||||
|
||||
t.Run("bulk写入已定价mapping_通过", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, nil)
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{account.ID},
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "gpt-oss:120b"}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, repo.bulkUpdates, 1)
|
||||
})
|
||||
|
||||
t.Run("bulk启用legacy无配置账号_拒绝且不落库", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
first := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy-a" })
|
||||
second := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy-b" })
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{first.ID, second.ID},
|
||||
Schedulable: boolPtr(true),
|
||||
})
|
||||
requireModelPricingMissing(t, err)
|
||||
require.Contains(t, infraerrors.Message(err), first.Name)
|
||||
require.Contains(t, infraerrors.Message(err), second.Name)
|
||||
require.Empty(t, repo.bulkUpdates)
|
||||
})
|
||||
|
||||
t.Run("bulk停用_放行", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-bulk-disable"
|
||||
a.Schedulable = true
|
||||
})
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{account.ID},
|
||||
Schedulable: boolPtr(false),
|
||||
})
|
||||
require.NoError(t, err, "停用(退出调度准入)属于维护性更新,不得被拦截")
|
||||
require.Len(t, repo.bulkUpdates, 1)
|
||||
})
|
||||
|
||||
t.Run("bulk仅改name_legacy账号放行", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy" })
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{account.ID},
|
||||
Name: "ollama-bulk-legacy-renamed",
|
||||
})
|
||||
require.NoError(t, err, "维护性更新(仅改 name)不得被 MODEL_PRICING_MISSING 锁死")
|
||||
require.Len(t, repo.bulkUpdates, 1)
|
||||
})
|
||||
|
||||
t.Run("非ollama平台bulk不受影响_回归", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "kimi-bulk"
|
||||
a.Platform = PlatformKimi
|
||||
a.Schedulable = false
|
||||
})
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{account.ID},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "k",
|
||||
"model_mapping": map[string]any{"k2": "totally-unpriced-model"},
|
||||
},
|
||||
Schedulable: boolPtr(true),
|
||||
})
|
||||
require.NoError(t, err, "非 ollama 平台的批量更新行为必须保持不变")
|
||||
require.Len(t, repo.bulkUpdates, 1)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAdminDuplicateAccountOllamaCloudPricingGate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) {
|
||||
t.Helper()
|
||||
repo := newOllamaGateAdminRepoStub()
|
||||
svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
return repo, svc
|
||||
}
|
||||
|
||||
t.Run("复制不合规账号_拒绝且不落库", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
source := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-dup-bad"
|
||||
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}
|
||||
})
|
||||
_, err := svc.DuplicateAccount(ctx, source.ID, "", "")
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
require.Len(t, repo.accounts, 1, "被拒绝的复制不得落库")
|
||||
})
|
||||
|
||||
t.Run("复制无配置legacy账号_拒绝", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
source := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-dup-legacy" })
|
||||
_, err := svc.DuplicateAccount(ctx, source.ID, "", "")
|
||||
requireModelPricingMissing(t, err)
|
||||
require.Len(t, repo.accounts, 1)
|
||||
})
|
||||
|
||||
t.Run("复制已配置清单账号_通过且保持暂停", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
source := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-dup-good"
|
||||
a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}}
|
||||
})
|
||||
duplicate, err := svc.DuplicateAccount(ctx, source.ID, "", "")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, duplicate)
|
||||
require.Len(t, repo.accounts, 2)
|
||||
require.False(t, duplicate.Schedulable, "复制产物必须保持暂停,等人工复核后再启用")
|
||||
})
|
||||
|
||||
t.Run("非ollama平台复制不受影响_回归", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
source := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "kimi-dup"
|
||||
a.Platform = PlatformKimi
|
||||
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "totally-unpriced-model"}}
|
||||
})
|
||||
duplicate, err := svc.DuplicateAccount(ctx, source.ID, "", "")
|
||||
require.NoError(t, err, "非 ollama 平台的复制行为必须保持不变")
|
||||
require.NotNil(t, duplicate)
|
||||
require.Len(t, repo.accounts, 2)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAdminSetAccountSchedulableOllamaCloudPricingGate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) {
|
||||
t.Helper()
|
||||
repo := newOllamaGateAdminRepoStub()
|
||||
svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
return repo, svc
|
||||
}
|
||||
|
||||
t.Run("启用无配置legacy账号_拒绝且不落库", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-enable-legacy" })
|
||||
_, err := svc.SetAccountSchedulable(ctx, account.ID, true)
|
||||
requireModelPricingMissing(t, err)
|
||||
require.Empty(t, repo.schedulableCalls, "被拒绝的启用不得触达 DB")
|
||||
})
|
||||
|
||||
t.Run("停用_放行", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-disable"
|
||||
a.Schedulable = true
|
||||
})
|
||||
updated, err := svc.SetAccountSchedulable(ctx, account.ID, false)
|
||||
require.NoError(t, err, "停用(true→false)属于维护性操作,不得被拦截")
|
||||
require.NotNil(t, updated)
|
||||
require.Len(t, repo.schedulableCalls, 1)
|
||||
require.False(t, repo.schedulableCalls[0].schedulable)
|
||||
})
|
||||
|
||||
t.Run("启用未定价mapping账号_拒绝", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-enable-unpriced"
|
||||
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}
|
||||
})
|
||||
_, err := svc.SetAccountSchedulable(ctx, account.ID, true)
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
require.Empty(t, repo.schedulableCalls)
|
||||
})
|
||||
|
||||
t.Run("出站含claude模型名_门禁与无渠道价预检一律拒绝防零计费", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-claude-target"
|
||||
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "claude-sonnet-4-5"}}
|
||||
})
|
||||
_, err := svc.SetAccountSchedulable(ctx, account.ID, true)
|
||||
requireModelPricingMissing(t, err, "claude-sonnet-4-5")
|
||||
|
||||
resolver := NewModelPricingResolver(nil, svc.billingService)
|
||||
require.True(t, ollamaCloudModelUnpricedForBilling(ctx, resolver, "claude-sonnet-4-5"),
|
||||
"无分组/渠道显式定价时预检必须拦截 claude-*,对齐 RecordUsage 的 dropUnpricedClaudeBillingCandidates")
|
||||
})
|
||||
|
||||
t.Run("启用已定价账号_通过", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-enable-priced"
|
||||
a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}}
|
||||
})
|
||||
updated, err := svc.SetAccountSchedulable(ctx, account.ID, true)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, updated)
|
||||
require.Len(t, repo.schedulableCalls, 1)
|
||||
})
|
||||
|
||||
t.Run("非ollama平台启用不受影响_回归", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "kimi-enable"
|
||||
a.Platform = PlatformKimi
|
||||
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "totally-unpriced-model"}}
|
||||
})
|
||||
updated, err := svc.SetAccountSchedulable(ctx, account.ID, true)
|
||||
require.NoError(t, err, "非 ollama 平台的手动启用行为必须保持不变")
|
||||
require.NotNil(t, updated)
|
||||
require.Len(t, repo.schedulableCalls, 1)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package service
|
||||
|
||||
// ollama_cloud 运行时白名单回归测试(钉死独立评审的探针场景):
|
||||
// - 空 model_mapping + extra.allowed_models 清单 → IsModelSupported 只放行
|
||||
// 清单内模型,清单外(含未定价模型名)一律拒绝、调度不选中;
|
||||
// - 空 mapping 且无清单 → deny-all;
|
||||
// - 非 ollama 平台空 mapping 仍放行所有(回归护栏);
|
||||
// - /models 列表路径(GetAvailableModels)并入 allowed_models 清单。
|
||||
//
|
||||
// 与保存期门禁(account_ollama_cloud_pricing_gate_test.go)合起来形成闭环:
|
||||
// 白名单决定能发什么,预检决定发出去的东西是否有价。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newOllamaCloudWhitelistAccount(credentials map[string]any, extra map[string]any) *Account {
|
||||
return &Account{
|
||||
ID: 9101,
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Credentials: credentials,
|
||||
Extra: extra,
|
||||
}
|
||||
}
|
||||
|
||||
// 评审探针场景:空 mapping + 清单只含 gpt-oss:120b → totally-unpriced-model
|
||||
// 必须不被支持、不被调度选中(评审当前观测到「仍 supported」)。
|
||||
func TestOllamaCloudWhitelist_ProbeUnpricedModelNotSupported(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Extra 走 JSON 反序列化的真实形态([]any 元素为 string)。
|
||||
account := newOllamaCloudWhitelistAccount(
|
||||
map[string]any{},
|
||||
map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}},
|
||||
)
|
||||
|
||||
require.False(t, account.IsModelSupported("totally-unpriced-model"),
|
||||
"清单外未定价模型名不得放行(评审探针场景)")
|
||||
require.False(t, account.IsModelSupported("claude-sonnet-4-6"),
|
||||
"其它平台默认模型名同样在清单外")
|
||||
require.True(t, account.IsModelSupported("gpt-oss:120b"), "清单内模型必须放行")
|
||||
|
||||
// 程序化构造形态([]string)语义一致。
|
||||
stringListAccount := newOllamaCloudWhitelistAccount(
|
||||
nil,
|
||||
map[string]any{OllamaCloudAllowedModelsExtraKey: []string{"gpt-oss:120b"}},
|
||||
)
|
||||
require.False(t, stringListAccount.IsModelSupported("totally-unpriced-model"))
|
||||
require.True(t, stringListAccount.IsModelSupported("gpt-oss:120b"))
|
||||
|
||||
// 调度候选过滤同样拒绝:不被选中。
|
||||
ctx := context.Background()
|
||||
reason := openAICompatibleAccountEligibilityFailureReasonBeforeProfit(
|
||||
ctx, account, PlatformOllamaCloud, "totally-unpriced-model", false, OpenAIEndpointCapabilityChatCompletions)
|
||||
require.Equal(t, "model_not_supported", reason)
|
||||
reason = openAICompatibleAccountEligibilityFailureReasonBeforeProfit(
|
||||
ctx, account, PlatformOllamaCloud, "gpt-oss:120b", false, OpenAIEndpointCapabilityChatCompletions)
|
||||
require.Empty(t, reason, "清单内模型必须保持可选中")
|
||||
}
|
||||
|
||||
func TestOllamaCloudWhitelist_EmptyMappingNoListDeniesAll(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
account := newOllamaCloudWhitelistAccount(map[string]any{}, map[string]any{})
|
||||
for _, model := range []string{"gpt-oss:120b", "totally-unpriced-model", "claude-sonnet-4-6", ""} {
|
||||
require.False(t, account.IsModelSupported(model),
|
||||
"空 mapping 且无清单必须 deny-all: %q", model)
|
||||
}
|
||||
|
||||
// 清单存在但全为空白项:视同未提供,仍然 deny-all(与保存期门禁的
|
||||
// 「清单缺失即拒绝」语义一致)。
|
||||
blankAccount := newOllamaCloudWhitelistAccount(
|
||||
nil,
|
||||
map[string]any{OllamaCloudAllowedModelsExtraKey: []any{" ", ""}},
|
||||
)
|
||||
require.False(t, blankAccount.IsModelSupported("gpt-oss:120b"))
|
||||
}
|
||||
|
||||
func TestOllamaCloudWhitelist_NonEmptyMappingKeepsMappingSemantics(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
account := newOllamaCloudWhitelistAccount(
|
||||
map[string]any{"model_mapping": map[string]any{"alias:latest": "gpt-oss:120b"}},
|
||||
nil,
|
||||
)
|
||||
require.True(t, account.IsModelSupported("alias:latest"), "mapping 键即公开白名单")
|
||||
require.False(t, account.IsModelSupported("totally-unpriced-model"))
|
||||
// 既有语义:非 ollama 也一样——mapping 目标值不是公开名,不因本次改动改变。
|
||||
require.False(t, account.IsModelSupported("gpt-oss:120b"), "mapping 目标值不是公开名")
|
||||
}
|
||||
|
||||
// 回归护栏:非 ollama 平台的空 mapping 仍放行所有(钉住 4 处风险面语义)。
|
||||
// 不含 antigravity / grok:这两个平台空 mapping 的既有语义是注入平台默认映射
|
||||
// (resolveModelMapping),从来不是「放行所有」,与本次改动无关。
|
||||
// 不含 deepseek:其空 mapping 的模型能力由 DeepSeek 自身的名单测试守护,
|
||||
// 本护栏只钉住 ollama_cloud 白名单改动不误伤其它平台,不替其它平台的能力
|
||||
// 定义背书。
|
||||
func TestOllamaCloudWhitelist_NonOllamaEmptyMappingStillAllowsAll(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, platform := range []string{
|
||||
"", PlatformAnthropic, PlatformOpenAI, PlatformGemini,
|
||||
PlatformKimi, PlatformMiniMax, PlatformZhipu, PlatformOpenCodeGo,
|
||||
} {
|
||||
account := &Account{ID: 1, Platform: platform, Type: AccountTypeAPIKey, Credentials: map[string]any{}}
|
||||
require.Truef(t, account.IsModelSupported("totally-unpriced-model"),
|
||||
"平台 %s 空 mapping 必须仍放行所有模型", platform)
|
||||
}
|
||||
}
|
||||
|
||||
// /models 列表路径:GetAvailableModels 并入 ollama_cloud 的 allowed_models 清单。
|
||||
func TestGetAvailableModels_MergesOllamaCloudAllowedModels(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
groupID := int64(9102)
|
||||
repo := &modelsListAccountRepoStub{
|
||||
byGroup: map[int64][]Account{
|
||||
groupID: {
|
||||
{
|
||||
ID: 1,
|
||||
Platform: PlatformOllamaCloud,
|
||||
Credentials: map[string]any{},
|
||||
Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b", "qwen3:32b"}},
|
||||
},
|
||||
{
|
||||
ID: 2,
|
||||
Platform: PlatformOllamaCloud,
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{"alias:latest": "gpt-oss:120b"}},
|
||||
},
|
||||
{
|
||||
ID: 3,
|
||||
Platform: PlatformOllamaCloud,
|
||||
Credentials: map[string]any{},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
svc := &GatewayService{accountRepo: repo}
|
||||
|
||||
models := svc.GetAvailableModels(context.Background(), &groupID, PlatformOllamaCloud)
|
||||
require.Equal(t, []string{"alias:latest", "gpt-oss:120b", "qwen3:32b"}, models)
|
||||
|
||||
// 全部账号都是 deny-all(无 mapping 无清单)→ 无可用模型列表。
|
||||
denyAllGroup := int64(9103)
|
||||
repo.byGroup[denyAllGroup] = []Account{
|
||||
{ID: 4, Platform: PlatformOllamaCloud, Credentials: map[string]any{}},
|
||||
}
|
||||
require.Nil(t, svc.GetAvailableModels(context.Background(), &denyAllGroup, PlatformOllamaCloud))
|
||||
|
||||
// 非 ollama 平台的既有语义不变:无任何 mapping → 仍返回 nil(用默认列表)。
|
||||
nonOllamaGroup := int64(9104)
|
||||
repo.byGroup[nonOllamaGroup] = []Account{
|
||||
{ID: 5, Platform: PlatformDeepseek, Credentials: map[string]any{}},
|
||||
}
|
||||
require.Nil(t, svc.GetAvailableModels(context.Background(), &nonOllamaGroup, PlatformDeepseek))
|
||||
}
|
||||
@@ -60,6 +60,8 @@ func EvaluateAccountSchedulingThreshold(account *Account, thresholds map[string]
|
||||
winner = pickLatestResetSchedulingCandidate(grokThresholdCandidates(account), threshold, now)
|
||||
case PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode:
|
||||
winner = pickLatestResetSchedulingCandidate(cnProviderThresholdCandidates(account, decision.Platform), threshold, now)
|
||||
case PlatformOllamaCloud:
|
||||
winner = pickLatestResetSchedulingCandidate(ollamaCloudThresholdCandidates(account), threshold, now)
|
||||
default:
|
||||
return decision
|
||||
}
|
||||
@@ -413,6 +415,40 @@ func cnThresholdCandidate(extra map[string]any, provider, window string) *accoun
|
||||
}
|
||||
}
|
||||
|
||||
// ollamaCloudThresholdCandidates 读取 ollama_cloud 账号 5h / 7d 滚动窗口的用量快照
|
||||
// (由 OllamaCloudUsageService 写入 account.Extra,经 decodeOllamaCloudUsageSnapshot
|
||||
// 解出嵌套 struct —— 与 CN 的扁平 extra 键不同构,不复用 cnThresholdCandidate)。
|
||||
//
|
||||
// 仅 legacy 账号有滚动窗口;credits 型是月度美元信用池、没有窗口 reset 可等,
|
||||
// 候选恒空(credits 赗欠告警走余额告警通道,不写 TempUnschedulableUntil)。
|
||||
// 快照缺失 / status != ok / 无窗口数据时同样返回 nil —— 宁可不停调也不基于
|
||||
// 坏快照误停。窗口语义与 openai/anthropic/kimi 同类:取最晚 reset。
|
||||
func ollamaCloudThresholdCandidates(account *Account) []*accountSchedulingThresholdCandidate {
|
||||
if account == nil || account.GetOllamaCloudAccountMode() != AccountModeOllamaLegacy {
|
||||
return nil
|
||||
}
|
||||
snapshot := decodeOllamaCloudUsageSnapshot(account.Extra)
|
||||
if snapshot == nil || snapshot.Status != OllamaCloudUsageStatusOK || snapshot.Data == nil {
|
||||
return nil
|
||||
}
|
||||
return []*accountSchedulingThresholdCandidate{
|
||||
ollamaCloudThresholdCandidate(snapshot.Data.FiveHour, "5h"),
|
||||
ollamaCloudThresholdCandidate(snapshot.Data.SevenDay, "weekly"),
|
||||
}
|
||||
}
|
||||
|
||||
func ollamaCloudThresholdCandidate(window *OllamaCloudUsageWindow, label string) *accountSchedulingThresholdCandidate {
|
||||
if window == nil {
|
||||
return nil
|
||||
}
|
||||
return &accountSchedulingThresholdCandidate{
|
||||
window: label,
|
||||
scope: PlatformOllamaCloud,
|
||||
usedPercent: window.UsedPercent,
|
||||
until: cloneTimePtr(window.ResetAt),
|
||||
}
|
||||
}
|
||||
|
||||
func pickLatestResetSchedulingCandidate(candidates []*accountSchedulingThresholdCandidate, threshold int, now time.Time) *accountSchedulingThresholdCandidate {
|
||||
var winner *accountSchedulingThresholdCandidate
|
||||
for _, candidate := range candidates {
|
||||
|
||||
@@ -528,3 +528,147 @@ func TestEvaluateAccountSchedulingThreshold_GrokUsesOnlyHeaderQuotaWindow(t *tes
|
||||
require.NotNil(t, decision.Until)
|
||||
require.True(t, headerUntil.Equal(*decision.Until))
|
||||
}
|
||||
|
||||
// ollamaCloudSnapshotExtra 构造 account.Extra 里 ollama_cloud 用量快照的测试夹具,
|
||||
// 形状与 DB JSONB 反序列化后的嵌套 map 一致(decodeOllamaCloudUsageSnapshot 走
|
||||
// marshal/unmarshal 往返,map 形式即生产读取路径)。
|
||||
func ollamaCloudSnapshotExtra(status string, data map[string]any) map[string]any {
|
||||
snapshot := map[string]any{"status": status}
|
||||
if data != nil {
|
||||
snapshot["data"] = data
|
||||
}
|
||||
return map[string]any{OllamaCloudUsageSnapshotExtraKey: snapshot}
|
||||
}
|
||||
|
||||
func ollamaCloudUsageWindowFixture(usedPercent float64, resetAt time.Time) map[string]any {
|
||||
return map[string]any{
|
||||
"used_percent": usedPercent,
|
||||
"reset_at": resetAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateAccountSchedulingThreshold_OllamaCloud(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC)
|
||||
fiveHourReset := now.Add(2 * time.Hour)
|
||||
sevenDayReset := now.Add(5 * 24 * time.Hour)
|
||||
newSnapshotAccount := func(mode string, extra map[string]any) *Account {
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Extra: extra,
|
||||
}
|
||||
if mode != "" {
|
||||
account.Credentials = map[string]any{"account_mode": mode}
|
||||
}
|
||||
return account
|
||||
}
|
||||
okExtra := ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{
|
||||
"five_hour": ollamaCloudUsageWindowFixture(95, fiveHourReset),
|
||||
"seven_day": ollamaCloudUsageWindowFixture(40, sevenDayReset),
|
||||
})
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
account *Account
|
||||
shouldPause bool
|
||||
wantWindow string
|
||||
wantUntil time.Time
|
||||
}{
|
||||
{
|
||||
name: "legacy pauses at exhausted five hour window",
|
||||
account: newSnapshotAccount("ollama_legacy", okExtra),
|
||||
shouldPause: true,
|
||||
wantWindow: "5h",
|
||||
wantUntil: fiveHourReset,
|
||||
},
|
||||
{
|
||||
name: "mode unset defaults to legacy and pauses",
|
||||
account: newSnapshotAccount("", okExtra),
|
||||
shouldPause: true,
|
||||
wantWindow: "5h",
|
||||
wantUntil: fiveHourReset,
|
||||
},
|
||||
{
|
||||
name: "unknown mode value falls back to legacy and pauses",
|
||||
account: newSnapshotAccount("bogus", okExtra),
|
||||
shouldPause: true,
|
||||
wantWindow: "5h",
|
||||
wantUntil: fiveHourReset,
|
||||
},
|
||||
{
|
||||
// 防回归护栏:credits 型是月度美元信用池、没有滚动窗口 reset,
|
||||
// 即使快照里解析出 5h/7d 数据也绝不停调。
|
||||
name: "credits never pauses despite fully populated snapshot",
|
||||
account: newSnapshotAccount("ollama_credits", okExtra),
|
||||
shouldPause: false,
|
||||
},
|
||||
{
|
||||
name: "failed snapshot does not pause",
|
||||
account: newSnapshotAccount("ollama_legacy", ollamaCloudSnapshotExtra(OllamaCloudUsageStatusFailed, nil)),
|
||||
shouldPause: false,
|
||||
},
|
||||
{
|
||||
name: "ok snapshot without window data does not pause",
|
||||
account: newSnapshotAccount("ollama_legacy", ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{})),
|
||||
shouldPause: false,
|
||||
},
|
||||
{
|
||||
// 防回归护栏:A6 纳入白名单后,无快照的账号同样不得停调。
|
||||
name: "missing snapshot does not pause",
|
||||
account: newSnapshotAccount("ollama_legacy", map[string]any{}),
|
||||
shouldPause: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
decision := EvaluateAccountSchedulingThreshold(tc.account, map[string]int{
|
||||
PlatformOllamaCloud: 80,
|
||||
}, now)
|
||||
|
||||
require.Equal(t, tc.shouldPause, decision.ShouldPause)
|
||||
if !tc.shouldPause {
|
||||
return
|
||||
}
|
||||
require.Equal(t, PlatformOllamaCloud, decision.Platform)
|
||||
require.Equal(t, tc.wantWindow, decision.Window)
|
||||
require.Equal(t, PlatformOllamaCloud, decision.Scope)
|
||||
require.NotNil(t, decision.Until)
|
||||
require.True(t, tc.wantUntil.Equal(*decision.Until))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateAccountSchedulingThreshold_OllamaCloudPicksLatestResetWindow(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// 与 openai/anthropic/kimi 同类取最晚 reset(不是 CN 供应商的最早 reset)。
|
||||
now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC)
|
||||
fiveHourReset := now.Add(2 * time.Hour)
|
||||
sevenDayReset := now.Add(5 * 24 * time.Hour)
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"account_mode": "ollama_legacy",
|
||||
},
|
||||
Extra: ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{
|
||||
"five_hour": ollamaCloudUsageWindowFixture(95, fiveHourReset),
|
||||
"seven_day": ollamaCloudUsageWindowFixture(90, sevenDayReset),
|
||||
}),
|
||||
}
|
||||
|
||||
decision := EvaluateAccountSchedulingThreshold(account, map[string]int{
|
||||
PlatformOllamaCloud: 80,
|
||||
}, now)
|
||||
|
||||
require.True(t, decision.ShouldPause)
|
||||
require.Equal(t, "weekly", decision.Window)
|
||||
require.Equal(t, PlatformOllamaCloud, decision.Scope)
|
||||
require.NotNil(t, decision.Until)
|
||||
require.True(t, sevenDayReset.Equal(*decision.Until))
|
||||
}
|
||||
@@ -210,6 +210,8 @@ type UpdateAccountRequest struct {
|
||||
type AccountService struct {
|
||||
accountRepo AccountRepository
|
||||
groupRepo GroupRepository
|
||||
// B2-③ 保存期无价门禁用:ollama_cloud 账号保存时断言可出站模型名全部可定价。
|
||||
billingService *BillingService
|
||||
}
|
||||
|
||||
type groupExistenceBatchChecker interface {
|
||||
@@ -217,10 +219,11 @@ type groupExistenceBatchChecker interface {
|
||||
}
|
||||
|
||||
// NewAccountService 创建账号服务实例
|
||||
func NewAccountService(accountRepo AccountRepository, groupRepo GroupRepository) *AccountService {
|
||||
func NewAccountService(accountRepo AccountRepository, groupRepo GroupRepository, billingService *BillingService) *AccountService {
|
||||
return &AccountService{
|
||||
accountRepo: accountRepo,
|
||||
groupRepo: groupRepo,
|
||||
accountRepo: accountRepo,
|
||||
groupRepo: groupRepo,
|
||||
billingService: billingService,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,6 +258,14 @@ func (s *AccountService) Create(ctx context.Context, req CreateAccountRequest) (
|
||||
} else {
|
||||
account.AutoPauseOnExpired = true
|
||||
}
|
||||
if req.Platform == PlatformOllamaCloud && req.Type != AccountTypeAPIKey {
|
||||
return nil, errors.New("ollama_cloud accounts only support apikey credentials")
|
||||
}
|
||||
|
||||
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.accountRepo.Create(ctx, account); err != nil {
|
||||
return nil, fmt.Errorf("create account: %w", err)
|
||||
@@ -326,6 +337,11 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount
|
||||
return nil, fmt.Errorf("get account: %w", err)
|
||||
}
|
||||
|
||||
// B2-③ 保存期无价门禁的触发判定快照:必须在应用本次请求的变更之前采集。
|
||||
prevPlatform := account.Platform
|
||||
prevOutboundSet := append([]string(nil), ollamaCloudOutboundModelNames(account)...)
|
||||
prevSchedulable := ollamaCloudSchedulableBySave(account)
|
||||
|
||||
// 更新字段
|
||||
if req.Name != nil {
|
||||
account.Name = *req.Name
|
||||
@@ -380,6 +396,16 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount
|
||||
}
|
||||
}
|
||||
|
||||
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
|
||||
// 只在可能改变可出站模型集合(platform / model_mapping / allowed_models)
|
||||
// 或影响调度准入(启用)的更新上重验;name、notes、并发数、状态等维护性
|
||||
// 更新放行,避免锁死缺 mapping/清单的存量账号。
|
||||
if ollamaCloudPricingGateRevalidationNeeded(prevPlatform, prevOutboundSet, prevSchedulable, account) {
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// 执行更新
|
||||
if err := s.accountRepo.Update(ctx, account); err != nil {
|
||||
return nil, fmt.Errorf("update account: %w", err)
|
||||
|
||||
@@ -388,6 +388,12 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int
|
||||
}
|
||||
|
||||
// Route to platform-specific test method
|
||||
// Ollama Cloud 有专属测试路径(默认测试模型取账号可出站模型、原生 Responses 探针),
|
||||
// 须先于下面按入站协议分流的通用分支。
|
||||
if account.IsOllamaCloud() {
|
||||
return s.testOllamaCloudAccountConnection(c, account, modelID, prompt)
|
||||
}
|
||||
|
||||
// 按入站协议分流的多协议供应商(国产厂商等):按账号协议选测试路径。
|
||||
if account.RoutesProtocolByInbound() {
|
||||
switch account.GetAPIProtocol() {
|
||||
@@ -459,24 +465,65 @@ func (s *AccountTestService) testModelRoutedAccountConnection(c *gin.Context, ac
|
||||
case APIProtocolAnthropic:
|
||||
return s.testCNProviderAnthropicConnection(c, account, testModelID)
|
||||
case APIProtocolResponses:
|
||||
return s.testModelRoutedResponsesConnection(c, account, testModelID)
|
||||
return s.testNativeResponsesConnection(c, account, testModelID)
|
||||
default:
|
||||
return s.testCNProviderChatCompletionsConnection(c, account, testModelID, prompt)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AccountTestService) testModelRoutedResponsesConnection(c *gin.Context, account *Account, testModelID string) error {
|
||||
// testNativeResponsesConnection probes a multi-protocol API-key account's
|
||||
// native Responses endpoint (the same probe the adaptive path uses, including
|
||||
// the stateless body normalization). Shared by OpenCode Go and Ollama Cloud.
|
||||
func (s *AccountTestService) testNativeResponsesConnection(c *gin.Context, account *Account, testModelID string) error {
|
||||
authToken := strings.TrimSpace(account.GetOpenAIProtocolAPIKey())
|
||||
if authToken == "" {
|
||||
return s.sendErrorAndEnd(c, "No API key available")
|
||||
}
|
||||
mappedModelID := account.GetMappedModel(testModelID)
|
||||
c.Writer.Header().Set("Content-Type", "text/event-stream")
|
||||
c.Writer.Header().Set("Cache-Control", "no-cache")
|
||||
c.Writer.Header().Set("Connection", "keep-alive")
|
||||
c.Writer.Header().Set("X-Accel-Buffering", "no")
|
||||
c.Writer.Flush()
|
||||
s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID})
|
||||
return s.testCNProviderAdaptiveResponsesConnection(c, account, testModelID, authToken)
|
||||
s.sendEvent(c, TestEvent{Type: "test_start", Model: mappedModelID})
|
||||
return s.testCNProviderAdaptiveResponsesConnection(c, account, mappedModelID, authToken)
|
||||
}
|
||||
|
||||
// testOllamaCloudAccountConnection probes an Ollama Cloud account's native
|
||||
// endpoints per GetAPIProtocol. Falling through to the generic Claude tester
|
||||
// sent Claude Code payloads to {base}/v1/messages?beta=true, so ollama accounts
|
||||
// always failed the connection test regardless of account health. Adaptive
|
||||
// (the default protocol for ollama_cloud) probes Chat Completions + Anthropic
|
||||
// + native Responses in sequence; a pinned protocol probes that single endpoint.
|
||||
func (s *AccountTestService) testOllamaCloudAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
|
||||
testModelID := strings.TrimSpace(modelID)
|
||||
if testModelID == "" {
|
||||
// 无静态目录:默认探测账号自身的第一个可出站模型(保存期门禁保证
|
||||
// mapping 或 allowed_models 至少其一非空)。
|
||||
testModelID = defaultOllamaCloudTestModel(account)
|
||||
}
|
||||
switch account.GetAPIProtocol() {
|
||||
case APIProtocolAdaptive:
|
||||
// 复用 CN adaptive 三端点探针:base_url 解析、Anthropic Bearer 头与
|
||||
// Responses 无状态归一化均已按 ollama_cloud 适配。
|
||||
return s.testCNProviderAdaptiveConnection(c, account, testModelID, prompt)
|
||||
case APIProtocolAnthropic:
|
||||
return s.testCNProviderAnthropicConnection(c, account, testModelID)
|
||||
case APIProtocolResponses:
|
||||
return s.testNativeResponsesConnection(c, account, testModelID)
|
||||
default:
|
||||
return s.testCNProviderChatCompletionsConnection(c, account, testModelID, prompt)
|
||||
}
|
||||
}
|
||||
|
||||
// defaultOllamaCloudTestModel 返回 ollama_cloud 账号连接测试的默认模型:
|
||||
// model_mapping 目标优先,其次 extra.allowed_models 首项;两者皆空时退回
|
||||
// OpenAI 测试模型(仅出现在未过保存期门禁的账号上,由上游报错暴露)。
|
||||
func defaultOllamaCloudTestModel(account *Account) string {
|
||||
if models := ollamaCloudOutboundModelNames(account); len(models) > 0 {
|
||||
return models[0]
|
||||
}
|
||||
return openai.DefaultTestModel
|
||||
}
|
||||
|
||||
func (s *AccountTestService) testCNProviderChatCompletionsConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
|
||||
|
||||
@@ -68,7 +68,7 @@ func (s *AccountTestService) testCNProviderAdaptiveAnthropicConnection(c *gin.Co
|
||||
if err != nil {
|
||||
return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid adaptive Anthropic base URL: %s", err.Error()))
|
||||
}
|
||||
apiURL := strings.TrimRight(baseURL, "/") + "/v1/messages"
|
||||
apiURL := nativeAnthropicMessagesURL(account, baseURL)
|
||||
|
||||
payload, err := createTestPayload(testModelID)
|
||||
if err != nil {
|
||||
@@ -163,18 +163,25 @@ func (s *AccountTestService) processCNProviderAdaptiveAnthropicStream(c *gin.Con
|
||||
|
||||
func (s *AccountTestService) testCNProviderAdaptiveResponsesConnection(c *gin.Context, account *Account, testModelID string, authToken string) error {
|
||||
ctx := c.Request.Context()
|
||||
baseURL, err := s.validateUpstreamBaseURL(account.GetCNProtocolBaseURL(APIProtocolResponses))
|
||||
rawBaseURL := account.GetOpenAIBaseURL()
|
||||
if account.IsAdaptiveAPIProtocol() {
|
||||
rawBaseURL = account.GetCNProtocolBaseURL(APIProtocolResponses)
|
||||
}
|
||||
baseURL, err := s.validateUpstreamBaseURL(rawBaseURL)
|
||||
if err != nil {
|
||||
return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid adaptive Responses base URL: %s", err.Error()))
|
||||
}
|
||||
apiURL := buildOpenAIResponsesURLForPlatform(account.Platform, baseURL)
|
||||
|
||||
payload := createOpenAITestPayload(testModelID, false)
|
||||
// DeepSeek / Kimi native Responses endpoints are stateless and do not need
|
||||
// the OpenAI probe's synthetic instructions.
|
||||
// DeepSeek / Kimi / Ollama Cloud native Responses endpoints are stateless and
|
||||
// do not need the OpenAI probe's synthetic instructions.
|
||||
delete(payload, "instructions")
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
payloadBytes = normalizeDeepSeekResponsesRequestBody(account, payloadBytes)
|
||||
payloadBytes, payloadErr := normalizeDeepSeekResponsesRequestBody(account, payloadBytes)
|
||||
if payloadErr != nil {
|
||||
return s.sendErrorAndEnd(c, fmt.Sprintf("Adaptive Responses payload rejected: %s", payloadErr.Error()))
|
||||
}
|
||||
|
||||
s.sendEvent(c, TestEvent{Type: "status", Text: "正在通过原生 /responses 测试自适应 Responses 端点"})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(payloadBytes))
|
||||
@@ -244,7 +251,7 @@ func (s *AccountTestService) testCNProviderAnthropicConnection(c *gin.Context, a
|
||||
if err != nil {
|
||||
return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid Anthropic base URL: %s", err.Error()))
|
||||
}
|
||||
if hint := cnAnthropicBaseURLMisconfigHint(baseURL, account.routesByModel()); hint != "" {
|
||||
if hint := cnAnthropicBaseURLMisconfigHint(baseURL, account.routesByModel() || account.IsOllamaCloud()); hint != "" {
|
||||
return s.sendErrorAndEnd(c, hint)
|
||||
}
|
||||
apiURL := nativeAnthropicMessagesURL(account, baseURL)
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// ollamaCloudTestAccount 构造官方默认 base_url(credentials 不带 base_url)的
|
||||
// ollama_cloud 账号,让测试同时钉住「正确回落平台默认端点」这件事。
|
||||
func ollamaCloudTestAccount(id int64, credentials map[string]any) *Account {
|
||||
base := map[string]any{
|
||||
"api_key": "sk-ollama-test",
|
||||
}
|
||||
for key, value := range credentials {
|
||||
base[key] = value
|
||||
}
|
||||
return &Account{
|
||||
ID: id,
|
||||
Name: "ollama-cloud-test",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Concurrency: 1,
|
||||
Credentials: base,
|
||||
Extra: map[string]any{
|
||||
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// C36 核心验收:adaptive(ollama_cloud 默认协议)账号依次探测 CC → Anthropic →
|
||||
// Responses 三个原生端点,URL 正确、无 ?beta=true,不再落入 Claude 测试路径。
|
||||
func TestAccountTestService_OllamaCloudAdaptiveProbesAllThreeEndpoints(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(501, map[string]any{"api_protocol": APIProtocolAdaptive})
|
||||
svc, upstream := adaptiveCNAccountTestService(
|
||||
account,
|
||||
adaptiveCNChatTestResponse(),
|
||||
adaptiveCNAnthropicTestResponse(),
|
||||
adaptiveCNResponsesTestResponse(),
|
||||
)
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 3)
|
||||
require.Equal(t, "https://ollama.com/v1/chat/completions", upstream.requests[0].URL.String())
|
||||
require.Equal(t, "https://ollama.com/v1/messages", upstream.requests[1].URL.String())
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.requests[2].URL.String())
|
||||
for i, req := range upstream.requests {
|
||||
require.Empty(t, req.URL.RawQuery, "request %d must not carry the Claude tester ?beta=true suffix", i)
|
||||
}
|
||||
// ollama 官方 host 的 Anthropic 端点强制 Bearer(非 CN 的 x-api-key)。
|
||||
require.Equal(t, "Bearer sk-ollama-test", upstream.requests[1].Header.Get("Authorization"))
|
||||
require.Empty(t, upstream.requests[1].Header.Get("x-api-key"))
|
||||
// Responses 探针按无状态端点归一化:store=false。
|
||||
require.False(t, gjson.GetBytes(upstream.bodies[2], "store").Bool())
|
||||
|
||||
require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_start"`))
|
||||
require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_complete"`))
|
||||
require.Contains(t, recorder.Body.String(), "已通过原生 /responses 验证")
|
||||
}
|
||||
|
||||
// 空模型默认取账号 allowed_models 首项(保存期门禁保证非空清单存在)。
|
||||
func TestAccountTestService_OllamaCloudEmptyModelDefaultsToAllowedModels(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(502, map[string]any{"api_protocol": APIProtocolChatCompletions})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "gpt-oss:120b-cloud", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
require.Contains(t, recorder.Body.String(), "gpt-oss:120b-cloud")
|
||||
}
|
||||
|
||||
// 钉 chat_completions:单端点探测,不触发 Anthropic/Responses。
|
||||
func TestAccountTestService_OllamaCloudPinnedChatProtocol(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(503, map[string]any{"api_protocol": APIProtocolChatCompletions})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "https://ollama.com/v1/chat/completions", upstream.requests[0].URL.String())
|
||||
require.Equal(t, "Bearer sk-ollama-test", upstream.requests[0].Header.Get("Authorization"))
|
||||
require.NotContains(t, upstream.requests[0].URL.Path, "/messages")
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
|
||||
// 钉 anthropic:官方默认 Anthropic base(https://ollama.com)+ /v1/messages,
|
||||
// 无 ?beta=true,Bearer 鉴权。
|
||||
func TestAccountTestService_OllamaCloudPinnedAnthropicProtocol(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(504, map[string]any{"api_protocol": APIProtocolAnthropic})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNAnthropicTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "", "", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
req := upstream.requests[0]
|
||||
require.Equal(t, "https://ollama.com/v1/messages", req.URL.String())
|
||||
require.Empty(t, req.URL.RawQuery)
|
||||
require.Equal(t, "Bearer sk-ollama-test", req.Header.Get("Authorization"))
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
|
||||
// 带 /v1 后缀的自定义基址与线上 nativeAnthropicMessagesURL 对齐:不报误配,且不拼出 /v1/v1/messages。
|
||||
accountWithV1 := ollamaCloudTestAccount(506, map[string]any{
|
||||
"api_protocol": APIProtocolAnthropic,
|
||||
"base_url": "https://ollama.com/v1",
|
||||
})
|
||||
svcV1, upstreamV1 := adaptiveCNAccountTestService(accountWithV1, adaptiveCNAnthropicTestResponse())
|
||||
cV1, recorderV1 := newTestContext()
|
||||
require.NoError(t, svcV1.TestAccountConnection(cV1, accountWithV1.ID, "", "", AccountTestModeDefault))
|
||||
require.Len(t, upstreamV1.requests, 1)
|
||||
require.Equal(t, "https://ollama.com/v1/messages", upstreamV1.requests[0].URL.String())
|
||||
require.Contains(t, recorderV1.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
|
||||
// 钉 responses:单端点 /v1/responses + 无状态归一化(store=false)。
|
||||
func TestAccountTestService_OllamaCloudPinnedResponsesProtocol(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(505, map[string]any{"api_protocol": APIProtocolResponses})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNResponsesTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
req := upstream.requests[0]
|
||||
require.Equal(t, "https://ollama.com/v1/responses", req.URL.String())
|
||||
require.Equal(t, HTTPUpstreamProfileOpenAI, HTTPUpstreamProfileFromContext(req.Context()))
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool())
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
@@ -264,3 +264,25 @@ func TestFixedCNResponsesProtocolOverridesStaleChatMode(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdaptiveProtocolRoutesOllamaCloudResponsesToNativeResponses 验证 C31 的连锁
|
||||
// 语义:SupportsNativeCNResponses 纳入 ollama_cloud 后,/v1/responses 入站不再被
|
||||
// C32 判定降级为 raw CC(https://ollama.com/v1/chat/completions),而是走平台原生
|
||||
// /v1/responses 端点;且 normalizeDeepSeekResponsesRequestBody 对 ollama 生效——
|
||||
// store 强制 false、previous_response_id 被剥离(Ollama /v1/responses 为
|
||||
// non-stateful,透传状态字段会被上游 400)。
|
||||
func TestAdaptiveProtocolRoutesOllamaCloudResponsesToNativeResponses(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
body := []byte(`{"model":"gpt-oss:120b-cloud","input":"hello","store":true,"previous_response_id":"resp_old","stream":false}`)
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
// api_base_urls 为空 → adaptive 解析到平台默认端点 https://ollama.com/v1。
|
||||
account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil)
|
||||
|
||||
_, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", body), account, body)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String())
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "previous_response_id").Exists())
|
||||
require.True(t, gjson.GetBytes(upstream.lastBody, "input").Exists())
|
||||
}
|
||||
@@ -337,6 +337,12 @@ func (s *adminServiceImpl) DuplicateAccount(ctx context.Context, id int64, actor
|
||||
}
|
||||
// A copied credential must be reviewed before it can share live traffic with its source.
|
||||
duplicate.Schedulable = false
|
||||
// B2-③ 保存期无价门禁:复制是创建路径的变体,产物与手工创建同样必须过门禁
|
||||
// (评审收口)——否则不合规的存量账号可以被无限复制放大。用「将要创建的账号」
|
||||
// 校验,credentials/extra 此时已是深拷贝后的最终形态。
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, duplicate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.accountDuplicateRepo == nil {
|
||||
return nil, errors.New("account duplicate repository is not configured")
|
||||
}
|
||||
@@ -419,6 +425,9 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an
|
||||
if input.Platform == PlatformTypeSafe && input.Type != AccountTypeAPIKey {
|
||||
return nil, errors.New("typesafe accounts only support apikey credentials")
|
||||
}
|
||||
if input.Platform == PlatformOllamaCloud && input.Type != AccountTypeAPIKey {
|
||||
return nil, errors.New("ollama_cloud accounts only support apikey credentials")
|
||||
}
|
||||
// Probe/session state is system-managed. Only explicit account settings can enable it.
|
||||
delete(accountExtra, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(accountExtra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
@@ -548,6 +557,10 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.ValidateAccountGroupBindings(ctx, groupIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -600,6 +613,13 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if account.Platform == PlatformTypeSafe && input.Type != "" && input.Type != AccountTypeAPIKey {
|
||||
return nil, errors.New("typesafe accounts only support apikey credentials")
|
||||
}
|
||||
if account.Platform == PlatformOllamaCloud && input.Type != "" && input.Type != AccountTypeAPIKey {
|
||||
return nil, errors.New("ollama_cloud accounts only support apikey credentials")
|
||||
}
|
||||
// B2-③ 保存期无价门禁的触发判定快照:必须在应用本次请求的变更之前采集。
|
||||
prevPlatform := account.Platform
|
||||
prevOutboundSet := append([]string(nil), ollamaCloudOutboundModelNames(account)...)
|
||||
prevSchedulable := ollamaCloudSchedulableBySave(account)
|
||||
var normalizedExtra map[string]any
|
||||
if input.Extra != nil {
|
||||
normalizedExtra, err = normalizeOpenAILongContextBillingUpdateExtra(account, input)
|
||||
@@ -903,6 +923,19 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
}
|
||||
}
|
||||
|
||||
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
|
||||
// 放在全部字段/Extra 变更应用完、任何写操作之前,credentials(含
|
||||
// model_mapping)与 extra(含 allowed_models)读到的都是本次请求生效后的状态。
|
||||
// 只在可能改变可出站模型集合(platform / model_mapping / allowed_models)
|
||||
// 或影响调度准入(启用)的更新上重验;name、notes、并发数、状态等维护性
|
||||
// 更新放行,避免锁死缺 mapping/清单的存量账号(全对象 PUT 编辑会原样带回
|
||||
// credentials/extra,集合未变时不重验)。
|
||||
if ollamaCloudPricingGateRevalidationNeeded(prevPlatform, prevOutboundSet, prevSchedulable, account) {
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
billingSettingsAppliedAtomically := false
|
||||
updater := s.accountBillingRepo
|
||||
if updater == nil {
|
||||
@@ -991,6 +1024,22 @@ func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, upd
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, exists := updates[OllamaCloudAllowedModelsExtraKey]; exists {
|
||||
account, err := s.accountRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if account != nil && account.IsOllamaCloud() {
|
||||
next := *account
|
||||
next.Extra = mergeMap(nil, account.Extra)
|
||||
for key, value := range updates {
|
||||
next.Extra[key] = value
|
||||
}
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, &next); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(updates) == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -1045,9 +1094,11 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
|
||||
needMixedChannelCheck := input.GroupIDs != nil && !input.SkipMixedChannelCheck
|
||||
|
||||
// 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查共用,避免多次 DB 查询。
|
||||
// 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查/ollama_cloud 保存期门禁共用,
|
||||
// 避免多次 DB 查询。ollama_cloud 门禁需要读到「变更后状态」(credentials/extra 合并、
|
||||
// status/schedulable 切换),所以携带这些输入时也必须预取。
|
||||
var cachedTargets []*Account
|
||||
if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil {
|
||||
if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil || input.Schedulable != nil || input.Status != "" || len(input.Extra) > 0 {
|
||||
loaded, err := s.accountRepo.GetByIDs(ctx, input.AccountIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -1222,6 +1273,15 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
repoUpdates.Schedulable = input.Schedulable
|
||||
}
|
||||
|
||||
// B2-③ 保存期无价门禁:批量路径同样不可绕过(评审收口)。先按仓库的同款合并
|
||||
// 语义(JSONB 顶层 key 合并 + 列覆盖)算出每个受影响 ollama_cloud 账号「本次
|
||||
// 请求生效后的状态」,再复用与单账号 UpdateAccount 相同的门禁与触发收窄判定。
|
||||
// 任何账号不合规即整批拒绝、不落库,错误信息点名账号与未定价模型,便于批量
|
||||
// 操作定位。
|
||||
if err := s.validateOllamaCloudPricingGateForBulkUpdate(input.AccountIDs, targetsByID, repoUpdates); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Run bulk update for column/jsonb fields first.
|
||||
if _, err := s.accountRepo.BulkUpdate(ctx, input.AccountIDs, repoUpdates); err != nil {
|
||||
return nil, err
|
||||
@@ -1264,6 +1324,48 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// validateOllamaCloudPricingGateForBulkUpdate 把保存期无价门禁应用到批量更新:
|
||||
// 对每个受影响的 ollama_cloud 账号,先把 AccountBulkUpdate 按仓库 BulkUpdate 的
|
||||
// 实际生效方式模拟到「变更后的账号」上(credentials/extra 顶层 key 合并,status/
|
||||
// schedulable 列覆盖),再复用 ollamaCloudPricingGateRevalidationNeeded + 门禁本体,
|
||||
// 与单账号 UpdateAccount 保持同一判定,不另写一份规则。命中不合规时收集全部
|
||||
// 违规项,由调用方整批拒绝(不产生任何写入)。
|
||||
func (s *adminServiceImpl) validateOllamaCloudPricingGateForBulkUpdate(accountIDs []int64, targetsByID map[int64]*Account, updates AccountBulkUpdate) error {
|
||||
var failures []string
|
||||
for _, id := range accountIDs {
|
||||
current, ok := targetsByID[id]
|
||||
if !ok || !current.IsOllamaCloud() {
|
||||
continue
|
||||
}
|
||||
next := *current
|
||||
next.Credentials = mergeMap(nil, current.Credentials)
|
||||
for key, value := range updates.Credentials {
|
||||
next.Credentials[key] = value
|
||||
}
|
||||
next.Extra = mergeMap(nil, current.Extra)
|
||||
for key, value := range updates.Extra {
|
||||
next.Extra[key] = value
|
||||
}
|
||||
if updates.Status != nil {
|
||||
next.Status = *updates.Status
|
||||
}
|
||||
if updates.Schedulable != nil {
|
||||
next.Schedulable = *updates.Schedulable
|
||||
}
|
||||
if !ollamaCloudPricingGateRevalidationNeeded(current.Platform, ollamaCloudOutboundModelNames(current), ollamaCloudSchedulableBySave(current), &next) {
|
||||
continue
|
||||
}
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, &next); err != nil {
|
||||
failures = append(failures, fmt.Sprintf("#%d(%s): %s", id, current.Name, infraerrors.Message(err)))
|
||||
}
|
||||
}
|
||||
if len(failures) == 0 {
|
||||
return nil
|
||||
}
|
||||
return infraerrors.BadRequest("MODEL_PRICING_MISSING",
|
||||
fmt.Sprintf("批量更新被 ollama_cloud 保存期门禁拒绝,整批未写入(不合规账号: %s)", strings.Join(failures, "; ")))
|
||||
}
|
||||
|
||||
func updatesUpstreamBillingProbeIdentity(credentials map[string]any) bool {
|
||||
for _, key := range []string{"api_key", "base_url", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} {
|
||||
if _, ok := credentials[key]; ok {
|
||||
@@ -1365,6 +1467,15 @@ func (s *adminServiceImpl) RefreshAccountCredentials(ctx context.Context, id int
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) ClearAccountError(ctx context.Context, id int64) (*Account, error) {
|
||||
current, err := s.accountRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if current != nil && current.IsOllamaCloud() && current.Schedulable && !ollamaCloudSchedulableBySave(current) {
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, current); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := s.accountRepo.ClearError(ctx, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1397,6 +1508,21 @@ func (s *adminServiceImpl) SetAccountError(ctx context.Context, id int64, errorM
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) SetAccountSchedulable(ctx context.Context, id int64, schedulable bool) (*Account, error) {
|
||||
// B2-③ 保存期无价门禁:手动启用调度(false→true)与保存路径的「启用」是同一
|
||||
// 调度准入开关,ollama_cloud 账号必须先过门禁,否则存量不合规账号可被一键放量
|
||||
// (评审收口)。判定复用 ollamaCloudSchedulableBySave(active + Schedulable),
|
||||
// 与单账号 Update 的启用语义一致;停用(true→false)属维护性操作,放行不校验。
|
||||
if schedulable {
|
||||
account, err := s.accountRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if account.IsOllamaCloud() && !ollamaCloudSchedulableBySave(account) {
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := s.accountRepo.SetSchedulable(ctx, id, schedulable); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -300,6 +300,8 @@ func defaultModelsListCandidateIDs(platform string) []string {
|
||||
return DefaultOpenCodeGoModelIDs()
|
||||
case PlatformTypeSafe:
|
||||
return []string{typesafe.JevLatestModel}
|
||||
case PlatformOllamaCloud:
|
||||
return DefaultOllamaCloudModelIDs()
|
||||
case PlatformComposite:
|
||||
return compositeDefaultModelsListCandidateIDs()
|
||||
default:
|
||||
|
||||
@@ -725,7 +725,9 @@ type adminServiceImpl struct {
|
||||
affiliateService adminRechargeAffiliateAccruer
|
||||
compositeRouteRepo CompositeModelRouteRepository
|
||||
compositeResolver *CompositeRouteResolver
|
||||
|
||||
// B2-③ 保存期无价门禁用:ollama_cloud 账号保存时断言可出站模型名全部可定价。
|
||||
// 生产 wire 注入;直接构造 struct 的单测可为 nil(门禁对 nil 跳过)。
|
||||
billingService *BillingService
|
||||
userPlatformQuotaRepo UserPlatformQuotaRepository
|
||||
// 分组平台变更后用来失效渠道缓存;可为 nil(缓存会在 TTL 到期后自然重建)
|
||||
channelCacheInvalidator ChannelCacheInvalidator
|
||||
@@ -770,6 +772,7 @@ func NewAdminService(
|
||||
compositeRouteRepo CompositeModelRouteRepository,
|
||||
compositeResolver *CompositeRouteResolver,
|
||||
channelCacheInvalidator ChannelCacheInvalidator,
|
||||
billingService *BillingService,
|
||||
userPlatformQuotaRepo UserPlatformQuotaRepository,
|
||||
) AdminService {
|
||||
return &adminServiceImpl{
|
||||
@@ -799,6 +802,7 @@ func NewAdminService(
|
||||
affiliateService: affiliateService,
|
||||
compositeRouteRepo: compositeRouteRepo,
|
||||
compositeResolver: compositeResolver,
|
||||
billingService: billingService,
|
||||
|
||||
channelCacheInvalidator: channelCacheInvalidator,
|
||||
userPlatformQuotaRepo: userPlatformQuotaRepo,
|
||||
|
||||
@@ -171,7 +171,7 @@ func TestAdminService_CreateUser_SnapshotsDefaultPlatformQuotas(t *testing.T) {
|
||||
SettingKeyAuthSourceDefaultEmailGrantOnSignup: "true",
|
||||
SettingKeyAuthSourcePlatformQuotas("email"): `{"openai":{"daily":3}}`,
|
||||
}}, &config.Config{})
|
||||
svc := NewAdminService(nil, users, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, settings, nil, nil, nil, nil, nil, nil, nil, nil, quotas)
|
||||
svc := NewAdminService(nil, users, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, settings, nil, nil, nil, nil, nil, nil, nil, nil, nil, quotas)
|
||||
|
||||
user, err := svc.CreateUser(context.Background(), &CreateUserInput{
|
||||
Email: "quota-defaults@example.test",
|
||||
|
||||
@@ -16,7 +16,10 @@ const (
|
||||
// Anthropic API-key accounts. Missing or invalid values keep the historical
|
||||
// x-api-key behavior. CN providers using their native Anthropic endpoints
|
||||
// (api_protocol=anthropic) share the same override knob — Kimi/DeepSeek default
|
||||
// to x-api-key, Zhipu can opt into Authorization: Bearer.
|
||||
// to x-api-key, Zhipu can opt into Authorization: Bearer. Ollama Cloud accounts
|
||||
// may read the knob too: it only matters for relay bases (the official
|
||||
// ollama.com base is forced to Bearer by host in setAnthropicAPIKeyAuthHeader
|
||||
// regardless of this value).
|
||||
func (a *Account) GetAnthropicAPIKeyAuthScheme() string {
|
||||
if a == nil || a.Type != AccountTypeAPIKey {
|
||||
return AnthropicAPIKeyAuthSchemeXAPIKey
|
||||
@@ -39,7 +42,7 @@ func (a *Account) GetAnthropicAPIKeyAuthScheme() string {
|
||||
// 与 '.../v1' 均合理),再复用既有严格 host helper isOllamaCloudBaseURL(精确
|
||||
// host、https、无 query/fragment、路径仅空或 /v1),不按 substring 匹配。
|
||||
func isOllamaCloudAnthropicAuthBaseURL(baseURL string) bool {
|
||||
return isOllamaCloudBaseURL(strings.TrimRight(strings.TrimSpace(baseURL), "/"))
|
||||
return isOllamaCloudOutboundBaseURL(baseURL)
|
||||
}
|
||||
|
||||
// setAnthropicAPIKeyAuthHeader 写入上游认证头。除 extra 覆写外,Ollama Cloud
|
||||
|
||||
@@ -142,6 +142,60 @@ func TestSetAnthropicAPIKeyAuthHeader_OllamaCloudForcesBearer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetAnthropicAPIKeyAuthScheme_OllamaCloudRelayOverride:C34 残余——平台化
|
||||
// 的 ollama_cloud 账号挂反代 base 时可经 extra 显式选 Bearer;缺省仍 x-api-key;
|
||||
// 官方 ollama.com base 的强制 Bearer 不经本函数、不受影响(host 分支先行)。
|
||||
func TestGetAnthropicAPIKeyAuthScheme_OllamaCloudRelayOverride(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
base string
|
||||
extra map[string]any
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "反代 base + extra 显式 Bearer → Bearer",
|
||||
base: "https://relay.example.com",
|
||||
extra: map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer},
|
||||
want: AnthropicAPIKeyAuthSchemeAuthorizationBearer,
|
||||
},
|
||||
{
|
||||
name: "反代 base 无 extra → 保持 x-api-key",
|
||||
base: "https://relay.example.com",
|
||||
want: AnthropicAPIKeyAuthSchemeXAPIKey,
|
||||
},
|
||||
{
|
||||
name: "官方 ollama.com base 也读 extra(强制 Bearer 由 host 分支保证)",
|
||||
base: "https://ollama.com",
|
||||
extra: map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer},
|
||||
want: AnthropicAPIKeyAuthSchemeAuthorizationBearer,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
account := newOllamaCloudAnthropicAuthAccount(tt.base, tt.extra)
|
||||
account.Platform = PlatformOllamaCloud
|
||||
require.Equal(t, tt.want, account.GetAnthropicAPIKeyAuthScheme())
|
||||
})
|
||||
}
|
||||
|
||||
// 官方 base 恒 Bearer 不受 extra 影响:ollama_cloud 账号 + 显式 x_api_key
|
||||
// extra,host 分支仍强制 Bearer。
|
||||
account := newOllamaCloudAnthropicAuthAccount("https://ollama.com", map[string]any{
|
||||
anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeXAPIKey,
|
||||
})
|
||||
account.Platform = PlatformOllamaCloud
|
||||
header := http.Header{}
|
||||
setAnthropicAPIKeyAuthHeader(header, account, "ollama-cloud-key", "https://ollama.com")
|
||||
require.Equal(t, "Bearer ollama-cloud-key", header.Get("Authorization"))
|
||||
require.Empty(t, header.Get("x-api-key"))
|
||||
|
||||
// Anthropic 平台回归:显式 x_api_key extra → x-api-key 不变。
|
||||
anthropicAccount := newOllamaCloudAnthropicAuthAccount("https://api.anthropic.com", map[string]any{
|
||||
anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeXAPIKey,
|
||||
})
|
||||
require.Equal(t, AnthropicAPIKeyAuthSchemeXAPIKey, anthropicAccount.GetAnthropicAPIKeyAuthScheme())
|
||||
}
|
||||
|
||||
// TestSetAnthropicAPIKeyAuthHeader_CNAdaptiveBaseURLResolution:adaptive 账号经
|
||||
// GetCNProtocolBaseURL(anthropic) / GetAnthropicProtocolBaseURL 选出的分协议地址
|
||||
// 才是判定依据,Chat Completions 地址(GetOpenAIBaseURL 选到的 CC base)不参与。
|
||||
|
||||
@@ -1515,3 +1515,30 @@ func (s *BillingCacheService) HasUserPlatformQuotaLimit(ctx context.Context, use
|
||||
}
|
||||
return entry.DailyLimitUSD != nil || entry.WeeklyLimitUSD != nil || entry.MonthlyLimitUSD != nil
|
||||
}
|
||||
|
||||
// CheckUserPlatformQuotaEligibilityForRequest 是 checkUserPlatformQuotaEligibility
|
||||
// 的导出薄包装,供 composite 账号池在账号选定后按实际 platform 补做 user×platform
|
||||
// 配额预检(准入 CheckBillingEligibility 时池请求还没有 resolved 平台,传空跳过了
|
||||
// 该维度),不得只后扣不预检。
|
||||
//
|
||||
// 语义约束:
|
||||
// - 纯检查 + cache 回填:不写 RPM 计数、不触碰熔断器、不扣费、不写任何请求持久
|
||||
// 状态。调用方绝不能用 CheckBillingEligibility 代替本检查——那会二次计数 RPM。
|
||||
// - 豁免条件与 CheckBillingEligibility 完全一致:simple 模式跳过;订阅分组且
|
||||
// subscription 非 nil 跳过(user×platform quota 仅在 standard 余额模式生效)。
|
||||
// - platform 为空或 repo 未装配时放行(与内部实现同一守卫)。
|
||||
func (s *BillingCacheService) CheckUserPlatformQuotaEligibilityForRequest(ctx context.Context, user *User, group *Group, subscription *UserSubscription, platform string) error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
if s.cfg.RunMode == config.RunModeSimple {
|
||||
return nil
|
||||
}
|
||||
if group != nil && group.IsSubscriptionType() && subscription != nil {
|
||||
return nil
|
||||
}
|
||||
if user == nil {
|
||||
return nil
|
||||
}
|
||||
return s.checkUserPlatformQuotaEligibility(ctx, user.ID, platform)
|
||||
}
|
||||
@@ -404,8 +404,8 @@ type inflightEstimateDeps struct {
|
||||
type inflightSnapshotLister func(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) ([]Account, error)
|
||||
|
||||
// inflightAccountMappedModelsFromSnapshot 基于调度器快照在内存中匹配账号级映射(支持通配规则)。
|
||||
// resolvePlatform 返回与调度器一致的平台;无分组 API Key 使用调度器的未分组账号池(groupID=nil)。
|
||||
func inflightAccountMappedModelsFromSnapshot(list inflightSnapshotLister, resolvePlatform func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool)) func(ctx context.Context, apiKey *APIKey, model string) []string {
|
||||
// resolvePlatform 返回可能携带 composite 池决策的 ctx 及目标平台;无分组 API Key 使用调度器的未分组账号池(groupID=nil)。
|
||||
func inflightAccountMappedModelsFromSnapshot(list inflightSnapshotLister, resolvePlatform func(ctx context.Context, apiKey *APIKey, model string) (context.Context, string, bool, bool)) func(ctx context.Context, apiKey *APIKey, model string) []string {
|
||||
if list == nil || resolvePlatform == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -414,11 +414,11 @@ func inflightAccountMappedModelsFromSnapshot(list inflightSnapshotLister, resolv
|
||||
if apiKey == nil || model == "" {
|
||||
return nil
|
||||
}
|
||||
platform, forced, ok := resolvePlatform(ctx, apiKey, model)
|
||||
resolvedCtx, platform, forced, ok := resolvePlatform(ctx, apiKey, model)
|
||||
if !ok || platform == "" {
|
||||
return nil
|
||||
}
|
||||
accounts, err := list(ctx, apiKey.GroupID, platform, forced)
|
||||
accounts, err := list(resolvedCtx, apiKey.GroupID, platform, forced)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -648,6 +648,37 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req
|
||||
// 免费分组:不计费,也无需预留。
|
||||
return 0, true
|
||||
}
|
||||
composite := apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite
|
||||
if composite {
|
||||
if _, resolved := ResolvedTargetPlatformFromContext(ctx); !resolved {
|
||||
if candidates := CompositeCandidatePlatformsFromContext(ctx); len(candidates) > 0 {
|
||||
best := 0.0
|
||||
for _, candPlatform := range candidates {
|
||||
if compositePoolPlatformDenied(ctx, candPlatform) {
|
||||
continue
|
||||
}
|
||||
candCtx := WithResolvedTargetPlatform(ctx, candPlatform)
|
||||
if c := d.estimateForContext(candCtx, apiKey, req, textRate, imageRate, true); c > best {
|
||||
best = c
|
||||
}
|
||||
}
|
||||
if best <= 0 {
|
||||
logInflightUnpriced(req.Model, apiKey.GroupID)
|
||||
return 0, false
|
||||
}
|
||||
return best, true
|
||||
}
|
||||
}
|
||||
}
|
||||
best := d.estimateForContext(ctx, apiKey, req, textRate, imageRate, composite)
|
||||
if best <= 0 {
|
||||
logInflightUnpriced(req.Model, apiKey.GroupID)
|
||||
return 0, false
|
||||
}
|
||||
return best, true
|
||||
}
|
||||
|
||||
func (d inflightEstimateDeps) estimateForContext(ctx context.Context, apiKey *APIKey, req InflightEstimateRequest, textRate, imageRate float64, composite bool) float64 {
|
||||
primary, fallbacks, upstreamInput := inflightBillingModelCandidates(ctx, d, apiKey, req.Model)
|
||||
bestOf := func(models []string) float64 {
|
||||
best := 0.0
|
||||
@@ -661,7 +692,6 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req
|
||||
best := bestOf(primary)
|
||||
// composite 分组:计费侧除非别名有显式渠道价,否则按实际转发的具体模型计费;
|
||||
// 别名本身可能命中家族模糊价(低估),因此与候选具体模型一起取最高。
|
||||
composite := apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite
|
||||
if best <= 0 || composite {
|
||||
// 与 billableModelWithFallback 同口径:首选模型无价时回退到实际转发模型。
|
||||
if c := bestOf(fallbacks); c > best {
|
||||
@@ -674,11 +704,7 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req
|
||||
}
|
||||
}
|
||||
}
|
||||
if best <= 0 {
|
||||
logInflightUnpriced(req.Model, apiKey.GroupID)
|
||||
return 0, false
|
||||
}
|
||||
return best, true
|
||||
return best
|
||||
}
|
||||
|
||||
// EstimateInflightReservationCost 仅用基础定价的简化估算(保留给无 resolver 的调用方/测试)。
|
||||
@@ -721,12 +747,18 @@ func (s *GatewayService) inflightEstimateDeps() inflightEstimateDeps {
|
||||
snap := s.schedulerSnapshot
|
||||
d.accountMappedModels = inflightAccountMappedModelsFromSnapshot(
|
||||
func(ctx context.Context, groupID *int64, platform string, forced bool) ([]Account, error) {
|
||||
if GenericCompositePoolActive(ctx) {
|
||||
return s.listSchedulableAccountsForCompositePool(ctx, groupID, CompositeCandidatePlatformsFromContext(ctx))
|
||||
}
|
||||
if len(CompositeCandidatePlatformsFromContext(ctx)) > 0 {
|
||||
forced = true
|
||||
}
|
||||
accounts, _, err := snap.ListSchedulableAccounts(ctx, groupID, platform, forced)
|
||||
return accounts, err
|
||||
},
|
||||
func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool) {
|
||||
platform, forced, err := s.resolvePlatform(ctx, apiKey.GroupID, apiKey.Group, model)
|
||||
return platform, forced, err == nil
|
||||
func(ctx context.Context, apiKey *APIKey, model string) (context.Context, string, bool, bool) {
|
||||
resolvedCtx, platform, forced, err := s.resolvePlatform(ctx, apiKey.GroupID, apiKey.Group, model)
|
||||
return resolvedCtx, platform, forced, err == nil
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -752,15 +784,24 @@ func (s *OpenAIGatewayService) inflightEstimateDeps() inflightEstimateDeps {
|
||||
snap := s.schedulerSnapshot
|
||||
d.accountMappedModels = inflightAccountMappedModelsFromSnapshot(
|
||||
func(ctx context.Context, groupID *int64, platform string, forced bool) ([]Account, error) {
|
||||
if openAICompositePoolActive(ctx) {
|
||||
return s.listSchedulableAccountsForCompositePool(ctx, groupID, CompositeCandidatePlatformsFromContext(ctx))
|
||||
}
|
||||
accounts, _, err := snap.ListSchedulableAccounts(ctx, groupID, platform, forced)
|
||||
return accounts, err
|
||||
},
|
||||
func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool) {
|
||||
func(ctx context.Context, apiKey *APIKey, model string) (context.Context, string, bool, bool) {
|
||||
platform := PlatformOpenAI
|
||||
if apiKey.Group != nil && apiKey.Group.Platform != "" && apiKey.Group.Platform != PlatformComposite {
|
||||
platform = apiKey.Group.Platform
|
||||
if apiKey.Group != nil && apiKey.Group.Platform != "" {
|
||||
if apiKey.Group.Platform == PlatformComposite {
|
||||
if resolved, ok := ResolvedTargetPlatformFromContext(ctx); ok {
|
||||
platform = resolved
|
||||
}
|
||||
} else {
|
||||
platform = apiKey.Group.Platform
|
||||
}
|
||||
}
|
||||
return NormalizeOpenAICompatiblePlatform(platform), false, true
|
||||
return ctx, NormalizeOpenAICompatiblePlatform(platform), false, true
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1041,6 +1041,69 @@ func (s *BillingService) initFallbackPricing() {
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
|
||||
// ---- Ollama Cloud 托管模型(ollama 独占,别家无同名条目)----
|
||||
// Source: https://ollama.com/pricing(官方定价页,2026-09-12 检索)。
|
||||
// 与别家同名的 ollama 模型(glm-5.3 / kimi-k3 / minimax-m3 / deepseek-v4-pro
|
||||
// 等)复用上方既有同名条目,不在此重复。键名用 /v1/models 的 API id 形态;
|
||||
// 家族匹配规则见 getFallbackPricing 的 Ollama 分支。Ollama 无 priority tier
|
||||
// 公布价,*Priority 字段一律不填;未列出的 ollama 模型名保持 nil(白名单
|
||||
// 语义,getFallbackPricing 末尾 return nil),显式拒绝而非误配。
|
||||
// gpt-oss 两档(120b / 20b)价差约 4 倍,匹配必须按完整 tag 前缀分开,
|
||||
// 禁止裸 "gpt-oss" 前缀(见 getFallbackPricing)。
|
||||
s.fallbackPrices["gpt-oss:120b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.15e-6, // $0.15 per MTok
|
||||
OutputPricePerToken: 0.60e-6, // $0.60 per MTok
|
||||
CacheReadPricePerToken: 0.014e-6, // $0.014 per MTok (cache hit)
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["gpt-oss:20b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.07e-6, // $0.07 per MTok
|
||||
OutputPricePerToken: 0.30e-6, // $0.30 per MTok
|
||||
CacheReadPricePerToken: 0.035e-6, // $0.035 per MTok (cache hit)
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["gemma4:31b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.14e-6, // $0.14 per MTok
|
||||
OutputPricePerToken: 0.40e-6, // $0.40 per MTok
|
||||
CacheReadPricePerToken: 0.05e-6, // $0.05 per MTok (cache hit)
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
// mistral-large-3 / qwen3.5 / nemotron-3-nano 官方未公布 cached-input 档
|
||||
// (定价页标注 "-",非 0)。CacheReadPricePerToken 为 0 的语义是把缓存输入
|
||||
// 按免费计(computeTokenBreakdown 直接乘该字段),为不低估成本,保守取输入价。
|
||||
s.fallbackPrices["mistral-large-3:675b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.50e-6, // $0.50 per MTok
|
||||
OutputPricePerToken: 1.50e-6, // $1.50 per MTok
|
||||
CacheReadPricePerToken: 0.50e-6, // cached-input 未公布,保守按输入价
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["qwen3.5:397b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.60e-6, // $0.60 per MTok
|
||||
OutputPricePerToken: 3.60e-6, // $3.60 per MTok
|
||||
CacheReadPricePerToken: 0.60e-6, // cached-input 未公布,保守按输入价
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
// nemotron 三款价差约 12 倍(输出 $0.24 vs $3.00 per MTok),逐款精确匹配,
|
||||
// 禁止裸 "nemotron" 兜底前缀(见 getFallbackPricing)。
|
||||
s.fallbackPrices["nemotron-3-super"] = &ModelPricing{
|
||||
InputPricePerToken: 0.015e-6, // $0.015 per MTok
|
||||
OutputPricePerToken: 0.60e-6, // $0.60 per MTok
|
||||
CacheReadPricePerToken: 0.015e-6, // $0.015 per MTok (cache hit)
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["nemotron-3-nano:30b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.06e-6, // $0.06 per MTok
|
||||
OutputPricePerToken: 0.24e-6, // $0.24 per MTok
|
||||
CacheReadPricePerToken: 0.06e-6, // cached-input 未公布,保守按输入价
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["nemotron-3-ultra"] = &ModelPricing{
|
||||
InputPricePerToken: 0.10e-6, // $0.10 per MTok
|
||||
OutputPricePerToken: 3.00e-6, // $3.00 per MTok
|
||||
CacheReadPricePerToken: 0.10e-6, // $0.10 per MTok (cache hit)
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
|
||||
// xAI Grok 4.5: $2 input / $0.30 cached input / $6 output below 200k;
|
||||
// long-context rates are $4 / $0.60 / $12 (>=200k prompt tokens).
|
||||
s.fallbackPrices["grok-4.5"] = &ModelPricing{
|
||||
@@ -1368,6 +1431,37 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
|
||||
return s.fallbackPrices["minimax-m2"]
|
||||
}
|
||||
|
||||
// ---- Ollama Cloud 托管模型(ollama 独占,Source: https://ollama.com/pricing)----
|
||||
// gpt-oss 两档(120b/20b)价差约 4 倍,必须按完整 tag 前缀分开匹配,禁止裸
|
||||
// "gpt-oss" 前缀;nemotron 三款价差约 12 倍,逐款精确匹配,禁止裸 "nemotron"
|
||||
// 兜底。前缀/子串规则天然覆盖 "-cloud" 变体(真实请求形态,见
|
||||
// openai_gateway_ollama_cloud_max_tokens_test.go)与其它 tag 后缀。未列出的
|
||||
// ollama 模型名沿用白名单语义:落到函数末尾 return nil(拒绝计费)。
|
||||
if strings.HasPrefix(modelLower, "gpt-oss:120b") {
|
||||
return s.fallbackPrices["gpt-oss:120b"]
|
||||
}
|
||||
if strings.HasPrefix(modelLower, "gpt-oss:20b") {
|
||||
return s.fallbackPrices["gpt-oss:20b"]
|
||||
}
|
||||
if strings.Contains(modelLower, "gemma4") {
|
||||
return s.fallbackPrices["gemma4:31b"]
|
||||
}
|
||||
if strings.Contains(modelLower, "mistral-large-3") {
|
||||
return s.fallbackPrices["mistral-large-3:675b"]
|
||||
}
|
||||
if strings.HasPrefix(modelLower, "qwen3.5:397b") {
|
||||
return s.fallbackPrices["qwen3.5:397b"]
|
||||
}
|
||||
if strings.Contains(modelLower, "nemotron-3-super") {
|
||||
return s.fallbackPrices["nemotron-3-super"]
|
||||
}
|
||||
if strings.Contains(modelLower, "nemotron-3-nano") {
|
||||
return s.fallbackPrices["nemotron-3-nano:30b"]
|
||||
}
|
||||
if strings.Contains(modelLower, "nemotron-3-ultra") {
|
||||
return s.fallbackPrices["nemotron-3-ultra"]
|
||||
}
|
||||
|
||||
// 硅基流动 Qwen3-Embedding 系列(纯文本向量化)。
|
||||
// most-specific-first:8b → 4b → 0.6b。仅白名单这三个已知档位,未知档位
|
||||
//(如 qwen3-embedding-2b)不回退,符合本表「未知型号不猜测计价」的语义。
|
||||
@@ -1533,6 +1627,26 @@ func (s *BillingService) HasIdentifiedTokenPricing(model string) bool {
|
||||
return ok && pricing != nil
|
||||
}
|
||||
|
||||
// HasIdentifiedPositiveTokenPricing 判断模型是否在价格表中能被确定性识别且具备正 token 单价。
|
||||
// 用于区分「真实标准模型名(如 claude-sonnet-4-5)」与「未识别公开别名(如 haiku-pro)或
|
||||
// LiteLLM 中的 $0 实验占位条目(如 gemini-flash-experimental)」。
|
||||
func (s *BillingService) HasIdentifiedPositiveTokenPricing(model string) bool {
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
model = strings.ToLower(strings.TrimSpace(model))
|
||||
if model == "" {
|
||||
return false
|
||||
}
|
||||
if s.pricingService != nil {
|
||||
if pricing := s.pricingService.GetIdentifiedModelPricing(model); pricing != nil && !pricing.TokenPricingAbsent {
|
||||
return pricing.InputCostPerToken > 0 || pricing.OutputCostPerToken > 0
|
||||
}
|
||||
}
|
||||
pricing, ok := s.fallbackPrices[model]
|
||||
return ok && pricing != nil && (pricing.InputPricePerToken > 0 || pricing.OutputPricePerToken > 0)
|
||||
}
|
||||
|
||||
// GetModelPricing 获取模型价格配置
|
||||
func (s *BillingService) GetModelPricing(model string) (*ModelPricing, error) {
|
||||
return s.getModelPricingAt(model, timezone.Now())
|
||||
@@ -1552,13 +1666,42 @@ func (s *BillingService) CacheStoragePricePerTokenHour(model string) float64 {
|
||||
|
||||
// getModelPricingAt 保留带计费时点的内部调用接口。DeepSeek 默认低谷价
|
||||
// 仅由模型决定,峰谷倍率由统一计费入口按请求时点处理。
|
||||
//
|
||||
// 两级查价:字面名完整跑一遍查找链(LiteLLM → fallback),未命中且名含
|
||||
// ":tag" 时用剥 tag 名重查一次(pricingAt 原样传递)。字面优先:bedrock
|
||||
// canonical key(如 us.anthropic.claude-sonnet-4-5-20250929-v1:0)本身含 ":0",
|
||||
// 字面命中时绝不剥;剥 tag 仅是 miss 后的第二级,见
|
||||
// normalizePricingModelNameForLookup。
|
||||
//
|
||||
// 第二级只接受确定性命中(目录精确识别 + 回退价表精确键),不走按子串猜系列的
|
||||
// 兜底:剥掉 tag 的名字(如 gpt-oss:latest → gpt-oss)会被家族/OpenAI 末端
|
||||
// catch-all 猜成无关模型的价格,并让计费门禁误判为已定价。
|
||||
func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (*ModelPricing, error) {
|
||||
pricing, err := s.getModelPricingAtOnce(model, pricingAt, false)
|
||||
if err == nil {
|
||||
return pricing, nil
|
||||
}
|
||||
if stripped, ok := normalizePricingModelNameForLookup(model); ok {
|
||||
if retry, retryErr := s.getModelPricingAtOnce(stripped, pricingAt, true); retryErr == nil {
|
||||
return retry, nil
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// getModelPricingAtOnce 跑一遍查找链;identifiedOnly 时只接受确定性命中。
|
||||
func (s *BillingService) getModelPricingAtOnce(model string, pricingAt time.Time, identifiedOnly bool) (*ModelPricing, error) {
|
||||
// 标准化模型名称(转小写)
|
||||
model = strings.ToLower(model)
|
||||
|
||||
// 1. 优先从动态价格服务获取
|
||||
if s.pricingService != nil {
|
||||
litellmPricing := s.pricingService.GetModelPricing(model)
|
||||
var litellmPricing *LiteLLMModelPricing
|
||||
if identifiedOnly {
|
||||
litellmPricing = s.pricingService.GetIdentifiedModelPricing(model)
|
||||
} else {
|
||||
litellmPricing = s.pricingService.GetModelPricing(model)
|
||||
}
|
||||
// 仅有图片价、无 token 价的条目(如 LiteLLM 的 imagen 类模型)不能用于
|
||||
// token 计费:直接返回会把 token 流量按 $0 计费。跳过后走 fallback,
|
||||
// 无 fallback 则 fail-closed(ErrModelPricingUnavailable)。
|
||||
@@ -1601,7 +1744,12 @@ func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (*
|
||||
}
|
||||
|
||||
// 2. 使用硬编码回退价格
|
||||
fallback := s.getFallbackPricing(model)
|
||||
var fallback *ModelPricing
|
||||
if identifiedOnly {
|
||||
fallback = s.fallbackPrices[model]
|
||||
} else {
|
||||
fallback = s.getFallbackPricing(model)
|
||||
}
|
||||
if fallback != nil {
|
||||
// 按模型名去重:每个模型每进程最多打一条 warn,避免热路径每请求刷屏(issue #3394)。
|
||||
// model 在函数入口已 ToLower,故 GLM-5.2 / glm-5.2 视为同一条目。
|
||||
|
||||
@@ -176,6 +176,10 @@ var providerAdapters = map[string]providerAdapter{
|
||||
MonitorProviderZhipu: providerZhipuChatAdapter,
|
||||
MonitorProviderDeepseek: providerDeepseekChatAdapter,
|
||||
MonitorProviderMiniMax: providerMiniMaxChatAdapter,
|
||||
// ollama_cloud:官方 OpenAI 兼容 Chat Completions(/v1/chat/completions),
|
||||
// 与国产 3 家同构;api_mode 仍只支持 chat_completions(responses 探活
|
||||
// 仅 openai,见 validateAPIMode)。
|
||||
MonitorProviderOllamaCloud: providerOllamaCloudChatAdapter,
|
||||
MonitorProviderAnthropic: {
|
||||
buildPath: func(string) string { return providerAnthropicPath },
|
||||
buildBody: func(model, prompt string) ([]byte, error) {
|
||||
@@ -230,6 +234,9 @@ var providerDeepseekChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIP
|
||||
//nolint:gochecknoglobals // 适配器表是只读静态数据,初始化后不变更。
|
||||
var providerMiniMaxChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIPath)
|
||||
|
||||
//nolint:gochecknoglobals // 适配器表是只读静态数据,初始化后不变更。
|
||||
var providerOllamaCloudChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIPath)
|
||||
|
||||
func newOpenAICompatibleChatAdapter(path string) providerAdapter {
|
||||
return providerAdapter{
|
||||
buildPath: func(string) string { return path },
|
||||
@@ -463,6 +470,8 @@ var bodyMergeKeyDenyList = map[string]map[string]bool{
|
||||
MonitorProviderZhipu: {"model": true, "messages": true, "stream": true},
|
||||
MonitorProviderDeepseek: {"model": true, "messages": true, "stream": true},
|
||||
MonitorProviderMiniMax: {"model": true, "messages": true, "stream": true},
|
||||
// ollama_cloud 同为 OpenAI Chat Completions 同构。
|
||||
MonitorProviderOllamaCloud: {"model": true, "messages": true, "stream": true},
|
||||
}
|
||||
|
||||
func checkAPIMode(opts *CheckOptions) string {
|
||||
@@ -484,7 +493,8 @@ func bodyMergeDenyKey(provider, apiMode string) string {
|
||||
func isOpenAICompatibleChatProvider(provider string) bool {
|
||||
switch provider {
|
||||
case MonitorProviderOpenAI, MonitorProviderGrok,
|
||||
MonitorProviderKimi, MonitorProviderZhipu, MonitorProviderDeepseek, MonitorProviderMiniMax:
|
||||
MonitorProviderKimi, MonitorProviderZhipu, MonitorProviderDeepseek, MonitorProviderMiniMax,
|
||||
MonitorProviderOllamaCloud:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
||||
@@ -213,6 +213,14 @@ func TestGrokMonitorConfiguration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// ollama_cloud 探活适配器与 OpenAI Chat 同构:replace 模式的请求体同样必须带 messages,
|
||||
// 否则保存成功后每次探活都失败。
|
||||
func TestValidateReplaceRequestBody_OllamaCloudRequiresMessages(t *testing.T) {
|
||||
if err := validateReplaceRequestBody(MonitorProviderOllamaCloud, MonitorAPIModeChatCompletions, map[string]any{}); err == nil {
|
||||
t.Fatal("ollama_cloud replace-mode body should require messages")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCheckForModel_Grok_DefaultChatRequest(t *testing.T) {
|
||||
h := &openAICaptureHandler{}
|
||||
endpoint := setupFakeOpenAI(t, h)
|
||||
|
||||
@@ -70,6 +70,9 @@ const (
|
||||
MonitorProviderZhipu = "zhipu"
|
||||
MonitorProviderDeepseek = "deepseek"
|
||||
MonitorProviderMiniMax = "minimax"
|
||||
// MonitorProviderOllamaCloud:官方提供 OpenAI 兼容 /v1/chat/completions,
|
||||
// 探活复用通用 OpenAI 兼容 adapter(与国产 3 家同构)。
|
||||
MonitorProviderOllamaCloud = "ollama_cloud"
|
||||
|
||||
// MonitorCheckMode 检测模式(channel_monitors.check_mode)。
|
||||
// probe - LLM 探活(默认,原有行为)
|
||||
@@ -152,7 +155,7 @@ var (
|
||||
"CHANNEL_MONITOR_NOT_FOUND", "channel monitor not found",
|
||||
)
|
||||
ErrChannelMonitorInvalidProvider = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax",
|
||||
"CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax/ollama_cloud",
|
||||
)
|
||||
ErrChannelMonitorInvalidCheckMode = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_INVALID_CHECK_MODE", "check_mode must be one of probe/quota/quota_probe; antigravity only supports quota",
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// --- provider 放行(M-1 的 service 层一半) ---
|
||||
|
||||
func TestOllamaCloudMonitorProviderAllowlists(t *testing.T) {
|
||||
require.NoError(t, validateProvider(MonitorProviderOllamaCloud))
|
||||
require.NoError(t, validateAPIMode(MonitorProviderOllamaCloud, ""))
|
||||
require.NoError(t, validateAPIMode(MonitorProviderOllamaCloud, MonitorAPIModeChatCompletions))
|
||||
// responses 探活仍仅 openai(与所有非 openai provider 一致)。
|
||||
require.ErrorIs(t, validateAPIMode(MonitorProviderOllamaCloud, MonitorAPIModeResponses), ErrChannelMonitorInvalidAPIMode)
|
||||
|
||||
// ollama_cloud 官方有 OpenAI 兼容 Chat Completions → 三种模式全部放行
|
||||
//(对比 antigravity 只允许 quota)。
|
||||
require.True(t, providerSupportsProbe(MonitorProviderOllamaCloud))
|
||||
require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeProbe))
|
||||
require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeQuota))
|
||||
require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeQuotaProbe))
|
||||
}
|
||||
|
||||
// 行为钉:opencode_go 在 handler binding 里放行、但 service 层 monitorProviders
|
||||
// 没有(upstream 有单独修复,本分支尚未合入)——钉住现状,防止被误认为本批回归。
|
||||
func TestOpenCodeGoMonitorProviderStillMissingFromServiceAllowlist(t *testing.T) {
|
||||
require.ErrorIs(t, validateProvider("opencode_go"), ErrChannelMonitorInvalidProvider)
|
||||
}
|
||||
|
||||
// --- 探活 adapter ---
|
||||
|
||||
func TestOllamaCloudMonitorAdapterProbesOpenAIChatCompletions(t *testing.T) {
|
||||
h := &openAICaptureHandler{}
|
||||
endpoint := setupFakeOpenAI(t, h)
|
||||
|
||||
res := runCheckForModel(context.Background(), MonitorProviderOllamaCloud, endpoint+"/v1", "sk-ollama", "gpt-oss:120b-cloud", nil)
|
||||
|
||||
require.Equal(t, MonitorStatusOperational, res.Status)
|
||||
require.Equal(t, providerOpenAIPath, h.lastPath)
|
||||
require.Equal(t, "gpt-oss:120b-cloud", h.lastBody["model"])
|
||||
require.Equal(t, "Bearer sk-ollama", h.lastHeaders.Get("Authorization"))
|
||||
}
|
||||
|
||||
func TestOllamaCloudMonitorMergeDenyListProtectsChallenge(t *testing.T) {
|
||||
adapter, apiMode, ok := providerAdapterFor(MonitorProviderOllamaCloud, "")
|
||||
require.True(t, ok)
|
||||
require.Equal(t, MonitorAPIModeChatCompletions, apiMode)
|
||||
|
||||
body, err := buildRequestBody(adapter, MonitorProviderOllamaCloud, apiMode, "gpt-oss:120b-cloud", "2+2=?", &CheckOptions{
|
||||
BodyOverrideMode: MonitorBodyOverrideModeMerge,
|
||||
BodyOverride: map[string]any{"model": "evil", "temperature": 0.5},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
var parsed map[string]any
|
||||
require.NoError(t, json.Unmarshal(body, &parsed))
|
||||
require.Equal(t, "gpt-oss:120b-cloud", parsed["model"], "model 命中黑名单不得被覆盖")
|
||||
require.InDelta(t, 0.5, parsed["temperature"], 0.0001, "非黑名单 key 应正常合并")
|
||||
}
|
||||
|
||||
// --- quota 取数(C29) ---
|
||||
|
||||
func ollamaCloudQuotaTestAccount(id int64, extra map[string]any) *Account {
|
||||
return &Account{
|
||||
ID: id,
|
||||
Name: "ollama-quota-test",
|
||||
Platform: domain.PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-ollama",
|
||||
"base_url": "https://ollama.com/v1",
|
||||
},
|
||||
Extra: extra,
|
||||
}
|
||||
}
|
||||
|
||||
func ollamaCloudUsageSnapshotExtra(status string, fetchedAt time.Time, data *OllamaCloudUsageData, lastError string) map[string]any {
|
||||
snapshot := map[string]any{
|
||||
"status": status,
|
||||
"last_attempt_at": fetchedAt,
|
||||
"next_refresh_at": fetchedAt,
|
||||
"fetched_at": fetchedAt,
|
||||
}
|
||||
if data != nil {
|
||||
snapshot["data"] = data
|
||||
}
|
||||
if lastError != "" {
|
||||
snapshot["last_error"] = lastError
|
||||
}
|
||||
return map[string]any{
|
||||
OllamaCloudUsageSnapshotExtraKey: snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaFetcher_OllamaCloudOkSnapshotMapsTiersAndBalance(t *testing.T) {
|
||||
fetcher, usage, cnQuota, cnBalance, accounts := newQuotaFetcherTestSetup(t)
|
||||
fetchedAt := time.Now().Add(-2 * time.Hour).UTC().Truncate(time.Second)
|
||||
accounts.accounts[31] = ollamaCloudQuotaTestAccount(31, ollamaCloudUsageSnapshotExtra(
|
||||
OllamaCloudUsageStatusOK, fetchedAt,
|
||||
&OllamaCloudUsageData{
|
||||
Plan: "pro",
|
||||
FiveHour: &OllamaCloudUsageWindow{UsedPercent: 42.5},
|
||||
SevenDay: &OllamaCloudUsageWindow{UsedPercent: 10},
|
||||
Balance: "$9.50",
|
||||
},
|
||||
"",
|
||||
))
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 31)
|
||||
|
||||
require.True(t, snapshot.Success)
|
||||
require.Equal(t, "ollama_quota", snapshot.Source)
|
||||
require.Equal(t, "pro", snapshot.PlanLevel)
|
||||
require.False(t, snapshot.CredentialInvalid)
|
||||
require.Empty(t, snapshot.Error)
|
||||
// 快照是被动抓取的历史值:FetchedAt 沿用真实抓取时间。
|
||||
require.True(t, fetchedAt.Equal(snapshot.FetchedAt))
|
||||
|
||||
require.Len(t, snapshot.Tiers, 2)
|
||||
require.Equal(t, "5h", snapshot.Tiers[0].Window)
|
||||
require.InDelta(t, 42.5, snapshot.Tiers[0].UsedPercent, 0.001)
|
||||
require.Equal(t, "7d", snapshot.Tiers[1].Window)
|
||||
require.InDelta(t, 10, snapshot.Tiers[1].UsedPercent, 0.001)
|
||||
|
||||
require.NotNil(t, snapshot.Balance)
|
||||
require.InDelta(t, 9.5, *snapshot.Balance, 0.001)
|
||||
require.Equal(t, "USD", snapshot.Currency)
|
||||
|
||||
require.Equal(t, 0, usage.getCalls(), "ollama 走快照读取,不得打海外 usage 服务")
|
||||
require.Equal(t, 0, cnQuota.calls)
|
||||
require.Equal(t, 0, cnBalance.calls)
|
||||
require.Equal(t, MonitorStatusOperational, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status)
|
||||
}
|
||||
|
||||
// credits 类账号:只有余额没有窗口 → only-balance 降级(余额文本可解析时透出)。
|
||||
func TestQuotaFetcher_OllamaCloudBalanceOnlySnapshot(t *testing.T) {
|
||||
fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
accounts.accounts[32] = ollamaCloudQuotaTestAccount(32, ollamaCloudUsageSnapshotExtra(
|
||||
OllamaCloudUsageStatusOK, time.Now(),
|
||||
&OllamaCloudUsageData{Balance: "USD$12"},
|
||||
"",
|
||||
))
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 32)
|
||||
|
||||
require.True(t, snapshot.Success)
|
||||
require.Empty(t, snapshot.Tiers)
|
||||
require.NotNil(t, snapshot.Balance)
|
||||
require.InDelta(t, 12, *snapshot.Balance, 0.001)
|
||||
}
|
||||
|
||||
// 无法解析的余额文本跳过(余额仅展示,不做停调判定)。
|
||||
func TestQuotaFetcher_OllamaCloudUnparsableBalanceSkipped(t *testing.T) {
|
||||
_, ok := parseOllamaCloudBalanceUSD("")
|
||||
require.False(t, ok)
|
||||
_, ok = parseOllamaCloudBalanceUSD("$9.50 / $20.00")
|
||||
require.False(t, ok)
|
||||
|
||||
value, ok := parseOllamaCloudBalanceUSD("USD$1,234.50")
|
||||
require.True(t, ok)
|
||||
require.InDelta(t, 1234.5, value, 0.001)
|
||||
}
|
||||
|
||||
// status!=ok(unauthorized/failed)→ 错误快照,带 last_error 与 fetched_at;
|
||||
// unauthorized 是抓取通道(settings 页会话)过期,不判凭据失效 → 推导 error 而非 failed。
|
||||
func TestQuotaFetcher_OllamaCloudFailedSnapshotsYieldErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status string
|
||||
wantSub string
|
||||
}{
|
||||
{name: "unauthorized session", status: OllamaCloudUsageStatusUnauthorized, wantSub: "session expired"},
|
||||
{name: "scrape failed", status: OllamaCloudUsageStatusFailed, wantSub: "usage page unreachable"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
fetchedAt := time.Now().Add(-3 * time.Hour).UTC()
|
||||
accounts.accounts[33] = ollamaCloudQuotaTestAccount(33, ollamaCloudUsageSnapshotExtra(
|
||||
tc.status, fetchedAt, nil, tc.wantSub,
|
||||
))
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 33)
|
||||
|
||||
require.False(t, snapshot.Success)
|
||||
require.False(t, snapshot.CredentialInvalid)
|
||||
require.Contains(t, snapshot.Error, tc.wantSub)
|
||||
require.Contains(t, snapshot.Error, "fetched at")
|
||||
require.Contains(t, snapshot.Error, fetchedAt.Format("2006-01-02"))
|
||||
require.Equal(t, MonitorStatusError, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// eligible=false(host 门禁:反代域名)→ 带原因码的可解释错误,不是笼统报错。
|
||||
func TestQuotaFetcher_OllamaCloudIneligibleBaseURLYieldsExplainableError(t *testing.T) {
|
||||
fetcher, usage, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
account := ollamaCloudQuotaTestAccount(34, nil)
|
||||
account.Credentials["base_url"] = "https://proxy.example.com/v1"
|
||||
accounts.accounts[34] = account
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 34)
|
||||
|
||||
require.False(t, snapshot.Success)
|
||||
require.Contains(t, snapshot.Error, "unsupported_base_url")
|
||||
require.Equal(t, 0, usage.getCalls())
|
||||
}
|
||||
|
||||
// 尚无快照(未配置会话或还没有请求活动)→ 可解释错误。
|
||||
func TestQuotaFetcher_OllamaCloudNoSnapshotYieldsExplainableError(t *testing.T) {
|
||||
fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
accounts.accounts[35] = ollamaCloudQuotaTestAccount(35, nil)
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 35)
|
||||
|
||||
require.False(t, snapshot.Success)
|
||||
require.Contains(t, snapshot.Error, "no ollama cloud usage snapshot yet")
|
||||
}
|
||||
|
||||
// 回归:opencode_go 仍走 CN quota 路由,kimi coding 仍走 CN quota(kimi 已有
|
||||
// 独立用例,这里钉 opencode_go 与 ollama 互不串线)。
|
||||
func TestQuotaFetcher_OpenCodeGoStillRoutesToCNQuota(t *testing.T) {
|
||||
fetcher, usage, cnQuota, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
accounts.accounts[36] = &Account{ID: 36, Platform: domain.PlatformOpenCodeGo, Type: AccountTypeAPIKey}
|
||||
cnQuota.result = &CNProviderQuotaProbeResult{Success: true}
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 36)
|
||||
|
||||
require.True(t, snapshot.Success)
|
||||
require.Equal(t, "cn_quota", snapshot.Source)
|
||||
require.Equal(t, 1, cnQuota.calls)
|
||||
require.Equal(t, 0, usage.getCalls())
|
||||
}
|
||||
|
||||
func TestParseOllamaCloudBalanceUSD_RejectsNonFiniteValues(t *testing.T) {
|
||||
for _, raw := range []string{"NaN", "Inf", "+Inf", "-Inf", "Infinity", "$NaN", "USD$Inf", "--$1.50"} {
|
||||
val, ok := parseOllamaCloudBalanceUSD(raw)
|
||||
require.False(t, ok, "raw=%q", raw)
|
||||
require.Zero(t, val)
|
||||
}
|
||||
val, ok := parseOllamaCloudBalanceUSD("$12.50")
|
||||
require.True(t, ok)
|
||||
require.InDelta(t, 12.50, val, 1e-9)
|
||||
|
||||
for _, raw := range []string{"-$1.50", "-USD$1.50", "$-1.50", "-$1,234.50"} {
|
||||
neg, negOK := parseOllamaCloudBalanceUSD(raw)
|
||||
require.True(t, negOK, "raw=%q", raw)
|
||||
if raw == "-$1,234.50" {
|
||||
require.InDelta(t, -1234.50, neg, 1e-9)
|
||||
} else {
|
||||
require.InDelta(t, -1.50, neg, 1e-9)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaFetcher_OllamaCloudCreditsModeSuppressesWindowTiers(t *testing.T) {
|
||||
fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
account := ollamaCloudQuotaTestAccount(37, ollamaCloudUsageSnapshotExtra(
|
||||
OllamaCloudUsageStatusOK, time.Now().UTC(),
|
||||
&OllamaCloudUsageData{
|
||||
Plan: "credits",
|
||||
FiveHour: &OllamaCloudUsageWindow{UsedPercent: 98.0},
|
||||
SevenDay: &OllamaCloudUsageWindow{UsedPercent: 95.0},
|
||||
Balance: "$42.00",
|
||||
},
|
||||
"",
|
||||
))
|
||||
account.Credentials["account_mode"] = AccountModeOllamaCredits
|
||||
accounts.accounts[37] = account
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 37)
|
||||
require.True(t, snapshot.Success)
|
||||
require.Empty(t, snapshot.Tiers, "credits 账号不应透出残留 5h/7d 窗口触发误告警")
|
||||
require.NotNil(t, snapshot.Balance)
|
||||
require.InDelta(t, 42.0, *snapshot.Balance, 1e-9)
|
||||
require.Equal(t, MonitorStatusOperational, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status)
|
||||
}
|
||||
|
||||
func TestMonitorAccountQuotaCapability_OllamaCloudEligibility(t *testing.T) {
|
||||
official := ollamaCloudQuotaTestAccount(38, nil)
|
||||
require.NoError(t, monitorAccountQuotaCapability(official))
|
||||
|
||||
relay := ollamaCloudQuotaTestAccount(39, nil)
|
||||
relay.Credentials["base_url"] = "https://relay.example.com/v1"
|
||||
require.ErrorIs(t, monitorAccountQuotaCapability(relay), ErrChannelMonitorAccountNotSupportable)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -23,6 +24,8 @@ import (
|
||||
// - 国产 coding plan(kimi/zhipu/deepseek)→ CNProviderQuotaService.QueryUsageForAccount
|
||||
// - 国产 payg(kimi/deepseek)→ CNProviderBalanceService.QueryBalanceForAccount
|
||||
// (zhipu payg 无公开余额端点,探测会返回该错误,原样透出)
|
||||
// - ollama_cloud → 账号 extra 里的官方用量快照(OllamaCloudUsageService 随请求
|
||||
// 活动被动维护,此处只读取、不实时探测;数据可能陈旧,FetchedAt 如实透出)
|
||||
// 数据源统一接受已加载的 *Account:fetchUncached 路由前 GetByID 一次并传下去,
|
||||
// 下游服务不再各自重载(每次 GetByID 含 proxies/groups 联查)。
|
||||
//
|
||||
@@ -223,6 +226,8 @@ func (f *ChannelMonitorQuotaFetcher) fetchUncached(ctx context.Context, accountI
|
||||
return f.fetchCNBalance(ctx, account, now)
|
||||
case domain.PlatformOpenCodeGo:
|
||||
return f.fetchCNQuota(ctx, account, now)
|
||||
case domain.PlatformOllamaCloud:
|
||||
return f.fetchOllamaCloudQuota(account, now)
|
||||
default:
|
||||
return f.fetchUsage(ctx, account, now)
|
||||
}
|
||||
@@ -455,6 +460,131 @@ func (f *ChannelMonitorQuotaFetcher) fetchCNBalance(ctx context.Context, account
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// fetchOllamaCloudQuota ollama_cloud:读取 OllamaCloudUsageService 维护在账号
|
||||
// extra 里的官方用量快照(请求活动驱动的被动抓取,此处不做实时探测),映射为
|
||||
// 配额快照;FetchedAt 沿用快照真实抓取时间——静默账号的数据会陈旧,时间戳
|
||||
// 如实透出,不伪装成刚刚抓取。eligible=false(如 base_url 为反代域名)或
|
||||
// 快照缺失/失败时返回带可解释原因的错误快照,而不是笼统的「不支持用量查询」。
|
||||
func (f *ChannelMonitorQuotaFetcher) fetchOllamaCloudQuota(account *Account, now time.Time) *domain.MonitorQuotaSnapshot {
|
||||
if reason := ollamaCloudUsageEligibilityReason(account); reason != "" {
|
||||
return quotaErrorSnapshot("ollama_quota", "ollama cloud usage unavailable: "+ollamaCloudUsageReasonHint(reason), now)
|
||||
}
|
||||
snapshot := decodeOllamaCloudUsageSnapshot(account.Extra)
|
||||
if snapshot == nil {
|
||||
return quotaErrorSnapshot("ollama_quota",
|
||||
"no ollama cloud usage snapshot yet; snapshots are captured from the official ollama.com usage page on request activity", now)
|
||||
}
|
||||
fetchedAt := now
|
||||
if snapshot.FetchedAt != nil {
|
||||
fetchedAt = *snapshot.FetchedAt
|
||||
}
|
||||
if snapshot.Status != OllamaCloudUsageStatusOK {
|
||||
return &domain.MonitorQuotaSnapshot{
|
||||
Source: "ollama_quota",
|
||||
// 401 是 settings 页会话过期(抓取通道凭据),不是账号 API key 失效,
|
||||
// 不置 CredentialInvalid——渠道本身可能仍然健康。
|
||||
Success: false,
|
||||
Error: truncateMessage(sanitizeErrorMessage(fmt.Sprintf(
|
||||
"ollama cloud usage snapshot status %s (fetched at %s): %s",
|
||||
snapshot.Status, formatOllamaCloudFetchedAt(snapshot.FetchedAt),
|
||||
firstNonEmpty(snapshot.LastError, "unknown error")))),
|
||||
FetchedAt: now,
|
||||
}
|
||||
}
|
||||
if snapshot.Data == nil {
|
||||
return quotaErrorSnapshot("ollama_quota",
|
||||
fmt.Sprintf("ollama cloud usage snapshot has no data (fetched at %s)", formatOllamaCloudFetchedAt(snapshot.FetchedAt)), now)
|
||||
}
|
||||
out := &domain.MonitorQuotaSnapshot{
|
||||
Source: "ollama_quota",
|
||||
Success: true,
|
||||
PlanLevel: snapshot.Data.Plan,
|
||||
FetchedAt: fetchedAt,
|
||||
}
|
||||
if account.GetOllamaCloudAccountMode() == AccountModeOllamaLegacy {
|
||||
out.Tiers = ollamaCloudQuotaTiers(snapshot.Data)
|
||||
}
|
||||
if balance, ok := parseOllamaCloudBalanceUSD(snapshot.Data.Balance); ok {
|
||||
out.Balance = &balance
|
||||
out.Currency = "USD"
|
||||
if account.GetOllamaCloudAccountMode() == AccountModeOllamaCredits {
|
||||
out.BalanceLow = balance <= 0 || (f.balanceThreshold > 0 && balance < f.balanceThreshold)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ollamaCloudQuotaTiers 把官方用量窗口归一为 tier 列表(窗口缺失时跳过)。
|
||||
func ollamaCloudQuotaTiers(data *OllamaCloudUsageData) []domain.MonitorQuotaTier {
|
||||
if data == nil {
|
||||
return nil
|
||||
}
|
||||
tiers := make([]domain.MonitorQuotaTier, 0, 2)
|
||||
appendOllamaCloudQuotaTier(&tiers, "5h", data.FiveHour)
|
||||
appendOllamaCloudQuotaTier(&tiers, "7d", data.SevenDay)
|
||||
if len(tiers) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tiers
|
||||
}
|
||||
|
||||
func appendOllamaCloudQuotaTier(tiers *[]domain.MonitorQuotaTier, window string, w *OllamaCloudUsageWindow) {
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
tier := domain.MonitorQuotaTier{Window: window, UsedPercent: w.UsedPercent}
|
||||
if w.ResetAt != nil {
|
||||
tier.ResetAt = w.ResetAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
*tiers = append(*tiers, tier)
|
||||
}
|
||||
|
||||
// parseOllamaCloudBalanceUSD 把官方页面抓到的余额文本(如 "$9.50" / "USD$9.50")
|
||||
// 解析为美元数值;解析失败返回 false(余额仅作展示,无月度信用总额可用于
|
||||
// 派生百分比,故 credits 账号只透出余额,不参与 used_percent 告警)。
|
||||
func parseOllamaCloudBalanceUSD(raw string) (float64, bool) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
sign := 1.0
|
||||
switch {
|
||||
case strings.HasPrefix(raw, "-"):
|
||||
sign = -1.0
|
||||
raw = strings.TrimSpace(raw[1:])
|
||||
case strings.HasPrefix(raw, "+"):
|
||||
raw = strings.TrimSpace(raw[1:])
|
||||
}
|
||||
raw = strings.TrimSpace(strings.TrimPrefix(raw, "USD"))
|
||||
raw = strings.TrimSpace(strings.TrimPrefix(raw, "$"))
|
||||
raw = strings.ReplaceAll(raw, ",", "")
|
||||
if raw == "" || (sign < 0 && (strings.HasPrefix(raw, "-") || strings.HasPrefix(raw, "+"))) {
|
||||
return 0, false
|
||||
}
|
||||
value, err := strconv.ParseFloat(raw, 64)
|
||||
if err != nil || math.IsNaN(value) || math.IsInf(value, 0) {
|
||||
return 0, false
|
||||
}
|
||||
return sign * value, true
|
||||
}
|
||||
|
||||
// ollamaCloudUsageReasonHint 把 EligibleReason 原因码翻译成运维可读的提示
|
||||
// (原因码语义见 OllamaCloudUsageState.EligibleReason)。
|
||||
func ollamaCloudUsageReasonHint(reason string) string {
|
||||
switch reason {
|
||||
case ollamaCloudUsageIneligibleBaseURL:
|
||||
return "unsupported_base_url (base_url is not the official ollama.com host; usage snapshots are only captured for official-host accounts)"
|
||||
case ollamaCloudUsageIneligibleAccountType:
|
||||
return "wrong_account_type (usage snapshots require an apikey account)"
|
||||
default:
|
||||
return reason
|
||||
}
|
||||
}
|
||||
|
||||
func formatOllamaCloudFetchedAt(t *time.Time) string {
|
||||
if t == nil {
|
||||
return "unknown"
|
||||
}
|
||||
return t.UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
// quotaErrorSnapshot 构造统一错误快照。
|
||||
func quotaErrorSnapshot(source, message string, now time.Time) *domain.MonitorQuotaSnapshot {
|
||||
return &domain.MonitorQuotaSnapshot{
|
||||
|
||||
@@ -55,7 +55,7 @@ var (
|
||||
"CHANNEL_MONITOR_TEMPLATE_NOT_FOUND", "channel monitor request template not found",
|
||||
)
|
||||
ErrChannelMonitorTemplateInvalidProvider = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_TEMPLATE_INVALID_PROVIDER", "template provider must be one of openai/anthropic/gemini/grok",
|
||||
"CHANNEL_MONITOR_TEMPLATE_INVALID_PROVIDER", "template provider must be one of openai/anthropic/gemini/grok/ollama_cloud",
|
||||
)
|
||||
ErrChannelMonitorTemplateInvalidAPIMode = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_TEMPLATE_INVALID_API_MODE", "template api_mode must be chat_completions or responses; responses is only supported for openai",
|
||||
|
||||
@@ -23,6 +23,7 @@ var monitorProviders = map[string]struct{}{
|
||||
MonitorProviderZhipu: {},
|
||||
MonitorProviderDeepseek: {},
|
||||
MonitorProviderMiniMax: {},
|
||||
MonitorProviderOllamaCloud: {},
|
||||
}
|
||||
|
||||
// probeCapableProviders 支持探活(probe / quota_probe)的 provider。
|
||||
@@ -38,6 +39,8 @@ var probeCapableProviders = map[string]struct{}{
|
||||
MonitorProviderZhipu: {},
|
||||
MonitorProviderDeepseek: {},
|
||||
MonitorProviderMiniMax: {},
|
||||
// ollama_cloud 官方提供 OpenAI 兼容 /v1/chat/completions,可真实探活。
|
||||
MonitorProviderOllamaCloud: {},
|
||||
}
|
||||
|
||||
// validateProvider 校验 provider 字符串。
|
||||
@@ -219,6 +222,11 @@ func monitorAccountQuotaCapability(account *Account) error {
|
||||
switch account.Platform {
|
||||
case PlatformOpenCodeGo:
|
||||
return nil
|
||||
case PlatformOllamaCloud:
|
||||
if ollamaCloudUsageEligibilityReason(account) != "" {
|
||||
return ErrChannelMonitorAccountNotSupportable
|
||||
}
|
||||
return nil
|
||||
case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax:
|
||||
if account.IsCodingPlan() {
|
||||
if p := account.GetCodingPlanProvider(); p != PlatformKimi && p != PlatformZhipu && p != PlatformMiniMax {
|
||||
|
||||
@@ -647,16 +647,26 @@ func resolveMapping(lk *channelLookup, groupID int64, model string) ChannelMappi
|
||||
}
|
||||
|
||||
// checkRestricted 基于已查找的渠道信息检查模型是否被限制。
|
||||
// 只在本平台的定价列表中查找。
|
||||
// 只在本平台的定价列表中查找;匹配顺序与 lookupChannelPricingNormalized 对齐
|
||||
// (字面 → Codex 归一 → 剥 ":tag"),避免基础名渠道价能计费却被模型限制误拦截。
|
||||
func checkRestricted(lk *channelLookup, groupID int64, model string) bool {
|
||||
if !lk.channel.RestrictModels {
|
||||
return false
|
||||
}
|
||||
modelLower := strings.ToLower(model)
|
||||
// 使用与查找定价相同的跨平台逻辑
|
||||
modelLower := strings.ToLower(strings.TrimSpace(model))
|
||||
if lookupPricingAcrossPlatforms(lk.cache, groupID, lk.platform, modelLower) != nil {
|
||||
return false
|
||||
}
|
||||
if normalized := normalizeKnownOpenAICodexModel(model); normalized != "" && !strings.EqualFold(normalized, strings.TrimSpace(model)) {
|
||||
if lookupPricingAcrossPlatforms(lk.cache, groupID, lk.platform, strings.ToLower(normalized)) != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if stripped, ok := normalizePricingModelNameForLookup(model); ok {
|
||||
if lookupPricingAcrossPlatforms(lk.cache, groupID, lk.platform, strings.ToLower(stripped)) != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -2127,7 +2127,7 @@ func TestMatchingPlatforms(t *testing.T) {
|
||||
{"anthropic returns itself", PlatformAnthropic, []string{PlatformAnthropic}},
|
||||
{"gemini returns itself", PlatformGemini, []string{PlatformGemini}},
|
||||
{"openai returns itself", PlatformOpenAI, []string{PlatformOpenAI}},
|
||||
{"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformCommandCode, PlatformCline}},
|
||||
{"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformCommandCode, PlatformCline, PlatformOllamaCloud}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
@@ -762,6 +762,9 @@ func TestNormalizeOpenAICompatiblePlatform_SchedulerExactMatch(t *testing.T) {
|
||||
require.Equal(t, PlatformZhipu, NormalizeOpenAICompatiblePlatform(PlatformZhipu))
|
||||
require.Equal(t, PlatformDeepseek, NormalizeOpenAICompatiblePlatform(PlatformDeepseek))
|
||||
require.Equal(t, PlatformOpenCodeGo, NormalizeOpenAICompatiblePlatform(PlatformOpenCodeGo))
|
||||
// ollama_cloud 同样保留原值:归一为 openai 会让 ollama_cloud 分组查 openai
|
||||
// 候选桶 → 静默空池(调度不到账号)。
|
||||
require.Equal(t, PlatformOllamaCloud, NormalizeOpenAICompatiblePlatform(PlatformOllamaCloud))
|
||||
// 其他平台(含空、anthropic、未知)一律归一为 openai。
|
||||
require.Equal(t, PlatformOpenAI, NormalizeOpenAICompatiblePlatform(""))
|
||||
require.Equal(t, PlatformOpenAI, NormalizeOpenAICompatiblePlatform(PlatformAnthropic))
|
||||
@@ -873,6 +876,8 @@ func TestGetAPIProtocol(t *testing.T) {
|
||||
require.Equal(t, APIProtocolChatCompletions, (&Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}).GetAPIProtocol(), "非 CN 供应商恒为默认")
|
||||
require.Equal(t, APIProtocolAdaptive, mk(PlatformOpenCodeGo, "").GetAPIProtocol(), "opencode go 默认 adaptive")
|
||||
require.Equal(t, APIProtocolResponses, mk(PlatformOpenCodeGo, APIProtocolResponses).GetAPIProtocol())
|
||||
require.Equal(t, APIProtocolAdaptive, mk(PlatformOllamaCloud, "").GetAPIProtocol(), "ollama cloud 默认 adaptive")
|
||||
require.Equal(t, APIProtocolResponses, mk(PlatformOllamaCloud, APIProtocolResponses).GetAPIProtocol(), "ollama cloud 原生 Responses 端点,显式 responses 不被吞成 adaptive")
|
||||
}
|
||||
|
||||
func TestSupportsNativeCNResponses(t *testing.T) {
|
||||
@@ -882,6 +887,7 @@ func TestSupportsNativeCNResponses(t *testing.T) {
|
||||
require.True(t, (&Account{Platform: PlatformKimi, Credentials: map[string]any{"account_mode": AccountModeCoding}}).SupportsNativeCNResponses())
|
||||
require.True(t, (&Account{Platform: PlatformMiniMax}).SupportsNativeCNResponses())
|
||||
require.True(t, (&Account{Platform: PlatformOpenCodeGo}).SupportsNativeCNResponses())
|
||||
require.True(t, (&Account{Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey}).SupportsNativeCNResponses(), "ollama cloud 有原生 /v1/responses 端点")
|
||||
require.False(t, (&Account{Platform: PlatformZhipu}).SupportsNativeCNResponses())
|
||||
require.False(t, (&Account{Platform: PlatformOpenAI}).SupportsNativeCNResponses())
|
||||
}
|
||||
@@ -1044,7 +1050,8 @@ func TestBuildOpenAIResponsesURLForPlatform(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestNormalizeDeepSeekResponsesRequestBody 无状态适配:强制 store=false、
|
||||
// 清除 previous_response_id;非原生 CN Responses 协议原样返回。
|
||||
// 清除 previous_response_id;携带 conversation 显式报错且不改写 body;
|
||||
// 非原生 CN Responses 协议原样返回(conversation 也不拦)。
|
||||
func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -1053,7 +1060,8 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) {
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolResponses},
|
||||
}
|
||||
body := []byte(`{"model":"deepseek-v4-pro","store":true,"previous_response_id":"resp_123","input":"hi"}`)
|
||||
normalized := normalizeDeepSeekResponsesRequestBody(deepseekResponses, body)
|
||||
normalized, err := normalizeDeepSeekResponsesRequestBody(deepseekResponses, body)
|
||||
require.NoError(t, err)
|
||||
require.False(t, gjson.GetBytes(normalized, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(normalized, "previous_response_id").Exists())
|
||||
require.Equal(t, "deepseek-v4-pro", gjson.GetBytes(normalized, "model").String())
|
||||
@@ -1062,12 +1070,14 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) {
|
||||
Platform: PlatformDeepseek, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolAdaptive},
|
||||
}
|
||||
adaptiveNormalized := normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body)
|
||||
adaptiveNormalized, err := normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body)
|
||||
require.NoError(t, err)
|
||||
require.False(t, gjson.GetBytes(adaptiveNormalized, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(adaptiveNormalized, "previous_response_id").Exists())
|
||||
|
||||
mediaBody := []byte(`{"model":"deepseek-v4.1-flash","store":true,"input":[{"type":"function_call","call_id":"call_image","name":"view_image","arguments":"{}"},{"type":"function_call_output","call_id":"call_image","output":[{"type":"input_image","image_url":"data:image/png;base64,AQID"}]}]}`)
|
||||
mediaNormalized := normalizeDeepSeekResponsesRequestBody(deepseekResponses, mediaBody)
|
||||
mediaNormalized, err := normalizeDeepSeekResponsesRequestBody(deepseekResponses, mediaBody)
|
||||
require.NoError(t, err)
|
||||
require.False(t, gjson.GetBytes(mediaNormalized, "store").Bool())
|
||||
require.Equal(t, gjson.String, gjson.GetBytes(mediaNormalized, "input.1.output").Type)
|
||||
require.NotContains(t, gjson.GetBytes(mediaNormalized, "input.1.output").String(), "data:image/png")
|
||||
@@ -1078,13 +1088,16 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) {
|
||||
|
||||
// 非 responses 协议(deepseek CC 账号)原样返回
|
||||
deepseekCC := &Account{Platform: PlatformDeepseek, Type: AccountTypeAPIKey}
|
||||
require.Equal(t, string(body), string(normalizeDeepSeekResponsesRequestBody(deepseekCC, body)))
|
||||
untouched, err := normalizeDeepSeekResponsesRequestBody(deepseekCC, body)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(body), string(untouched))
|
||||
|
||||
kimiResponses := &Account{
|
||||
Platform: PlatformKimi, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolResponses},
|
||||
}
|
||||
kimiNormalized := normalizeDeepSeekResponsesRequestBody(kimiResponses, body)
|
||||
kimiNormalized, err := normalizeDeepSeekResponsesRequestBody(kimiResponses, body)
|
||||
require.NoError(t, err)
|
||||
require.False(t, gjson.GetBytes(kimiNormalized, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(kimiNormalized, "previous_response_id").Exists())
|
||||
|
||||
@@ -1092,13 +1105,55 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) {
|
||||
Platform: PlatformKimi, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolAdaptive, "account_mode": AccountModeCoding},
|
||||
}
|
||||
kimiCodingNormalized := normalizeDeepSeekResponsesRequestBody(kimiCodingAdaptive, body)
|
||||
kimiCodingNormalized, err := normalizeDeepSeekResponsesRequestBody(kimiCodingAdaptive, body)
|
||||
require.NoError(t, err)
|
||||
require.False(t, gjson.GetBytes(kimiCodingNormalized, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(kimiCodingNormalized, "previous_response_id").Exists())
|
||||
|
||||
// openai 账号原样返回
|
||||
openai := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}
|
||||
require.Equal(t, string(body), string(normalizeDeepSeekResponsesRequestBody(openai, body)))
|
||||
untouched, err = normalizeDeepSeekResponsesRequestBody(openai, body)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(body), string(untouched))
|
||||
|
||||
// ollama cloud adaptive(原生 non-stateful /v1/responses):
|
||||
// store=false + 剥离 previous_response_id。
|
||||
ollamaAdaptive := &Account{
|
||||
Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolAdaptive},
|
||||
}
|
||||
ollamaNormalized, err := normalizeDeepSeekResponsesRequestBody(ollamaAdaptive, body)
|
||||
require.NoError(t, err)
|
||||
require.False(t, gjson.GetBytes(ollamaNormalized, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(ollamaNormalized, "previous_response_id").Exists())
|
||||
|
||||
// ollama cloud + conversation:显式报错(无状态端点不支持服务端状态字段),
|
||||
// body 必须保持原样——不是静默剥离。
|
||||
conversationBody := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi"}`)
|
||||
rejected, err := normalizeDeepSeekResponsesRequestBody(ollamaAdaptive, conversationBody)
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "conversation")
|
||||
require.Equal(t, string(conversationBody), string(rejected), "conversation 字段不得被剥离")
|
||||
|
||||
// conversation 与 previous_response_id 并存时同样报错,不做部分清洗。
|
||||
mixed := []byte(`{"model":"deepseek-v4-pro","store":true,"previous_response_id":"resp_1","conversation":"conv_x","input":"hi"}`)
|
||||
rejected, err = normalizeDeepSeekResponsesRequestBody(deepseekResponses, mixed)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, string(mixed), string(rejected))
|
||||
|
||||
// 无 conversation 时 err 恒为 nil(存量剥离语义不受签名变化影响)。
|
||||
_, err = normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 门禁只对原生 Responses 账号生效:zhipu(无 Responses 端点)带
|
||||
// conversation 原样返回、无错误。
|
||||
zhipu := &Account{
|
||||
Platform: PlatformZhipu, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolAdaptive},
|
||||
}
|
||||
untouched, err = normalizeDeepSeekResponsesRequestBody(zhipu, conversationBody)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(conversationBody), string(untouched))
|
||||
}
|
||||
|
||||
// TestGetAnthropicAPIKeyAuthScheme_CNProvider CN 账号可经 extra 覆写鉴权方案,
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
)
|
||||
|
||||
// CompositeClaimStrength 表达账号对某模型的声明强度。ownership 据此分层:
|
||||
// 存在强声明平台时池/单平台仅由强声明平台构成,完全无强声明才回退通配命中
|
||||
// 平台集合,避免 catch-all 通配账号与显式声明平台混池(如 grok 精确别名被
|
||||
// openai 的 "*" 通配冒领改写模型)。
|
||||
type CompositeClaimStrength int
|
||||
|
||||
const (
|
||||
// CompositeClaimNone 无声明。
|
||||
CompositeClaimNone CompositeClaimStrength = iota
|
||||
// CompositeClaimWildcard 弱声明:model_mapping 通配命中(fallback 语义,
|
||||
// 仅在无任何强声明平台时参与池/单平台判定)。
|
||||
CompositeClaimWildcard
|
||||
// CompositeClaimExplicit 强声明:mapping 精确键命中(含平台既有归一化后的
|
||||
// 精确键),或受控 native(空 mapping 且 detector 平台一致且 IsModelSupported
|
||||
// 通过)。精确与受控 native 同为强等级。
|
||||
CompositeClaimExplicit
|
||||
)
|
||||
|
||||
// CompositeAccountClaimStrength 返回 account 在「配置态」对 model 的声明强度。
|
||||
// 只依赖持久化配置(mapping / 平台 / 目录),不读取限流等瞬态运行状态。
|
||||
func CompositeAccountClaimStrength(account *Account, model string) CompositeClaimStrength {
|
||||
if account == nil {
|
||||
return CompositeClaimNone
|
||||
}
|
||||
model = strings.TrimSpace(model)
|
||||
if model == "" {
|
||||
return CompositeClaimNone
|
||||
}
|
||||
|
||||
mapping := account.GetModelMapping()
|
||||
if account.IsOpenAIPassthroughEnabled() && !account.IsOpenAIPassthroughModelFilterEnabled() {
|
||||
// 未开启按模型筛选的 OpenAI 透传账号忽略残留旧 model_mapping(#4936):
|
||||
// 按空 mapping 进入下方受控 native 规则——对 OpenAI 原生模型(IsModelSupported 通过)
|
||||
// 给强声明,避免同组存在空映射号时被 account_model_not_owned 误踢;对非原生模型或
|
||||
// 自定义别名不声明(CompositeClaimNone),不冒领其它平台或未知别名。
|
||||
mapping = nil
|
||||
} else if account.Platform == PlatformAntigravity {
|
||||
// antigravity 只有管理员在账号上显式配置的映射构成 composite 声明。平台默认映射
|
||||
// (Claude / Gemini 模型)属于混合调度语义:开启混合调度时由 detector 判出的
|
||||
// anthropic / gemini 单目标经混合调度展开服务这些模型(配额、渠道定价与分组模型
|
||||
// 路由仍按该平台),与 main 及非 composite 分组一致;若默认映射也算声明,
|
||||
// 「anthropic + 混合调度 antigravity」会被静默改成账号池,antigravity 按自身
|
||||
// 平台计配额,绕过 anthropic 配额。
|
||||
mapping = stringMappingFromRaw(account.Credentials["model_mapping"])
|
||||
}
|
||||
if len(mapping) == 0 {
|
||||
if account.IsOllamaCloud() {
|
||||
// ollama_cloud 空 mapping:extra.allowed_models 是管理员逐名声明的出站白名单
|
||||
// (DetectModelPlatform 刻意不识别 ollama,受控 native 永不成立)。清单精确
|
||||
// 命中(IsModelSupported 的 ollama 运行时白名单)即强声明,与 /v1/models
|
||||
// 列表同一语义;无清单为 deny-all。
|
||||
if account.IsModelSupported(model) {
|
||||
return CompositeClaimExplicit
|
||||
}
|
||||
return CompositeClaimNone
|
||||
}
|
||||
// 规则B:空 mapping 仅受控 native 声明。OpenAI OAuth 空 mapping 仍受
|
||||
// isOpenAIOAuthServableModel 约束(IsModelSupported 内部处理)。
|
||||
if platform, ok := DetectModelPlatform(model); !ok || platform != account.Platform {
|
||||
return CompositeClaimNone
|
||||
}
|
||||
if account.IsModelSupported(model) {
|
||||
return CompositeClaimExplicit
|
||||
}
|
||||
return CompositeClaimNone
|
||||
}
|
||||
return compositeMappingClaimStrength(account, mapping, model)
|
||||
}
|
||||
|
||||
// compositeMappingClaimStrength 按账号映射的实际命中路径分级,与
|
||||
// ResolveMappedModel 的匹配顺序一致:原始模型精确 → 原始通配 → 归一化精确 →
|
||||
// 归一化通配;命中即终止。映射目标为空的条目沿用既有 strict claim 语义:不构
|
||||
// 成声明,也不回落通配(显式条目对通配具有遮蔽性,转发阶段同样走不到通配)。
|
||||
func compositeMappingClaimStrength(account *Account, mapping map[string]string, model string) CompositeClaimStrength {
|
||||
// 快路径:原始 mapping 精确键命中即返回显式声明。等价性前提是 stringMappingFromRaw
|
||||
// 的原始 mapping 是 GetModelMapping 结果的子集(非空原始 mapping 逐键保留 string 值,
|
||||
// 平台默认映射只向并集追加条目且不产生空目标),故此处命中必然等价于下方首个精确
|
||||
// 分支返回的 Explicit,其余键走原有匹配顺序。
|
||||
if explicitModelMappingClaims(*account, model) {
|
||||
return CompositeClaimExplicit
|
||||
}
|
||||
if mapped, exists := mapping[model]; exists {
|
||||
return compositeClaimStrengthForTarget(mapped, true)
|
||||
}
|
||||
if mapped, matched := matchWildcardMappingResult(mapping, model); matched {
|
||||
return compositeClaimStrengthForTarget(mapped, false)
|
||||
}
|
||||
normalized := normalizeRequestedModelForLookup(account.Platform, model)
|
||||
if normalized != model {
|
||||
if mapped, exists := mapping[normalized]; exists {
|
||||
return compositeClaimStrengthForTarget(mapped, true)
|
||||
}
|
||||
if mapped, matched := matchWildcardMappingResult(mapping, normalized); matched {
|
||||
return compositeClaimStrengthForTarget(mapped, false)
|
||||
}
|
||||
}
|
||||
return CompositeClaimNone
|
||||
}
|
||||
|
||||
func compositeClaimStrengthForTarget(mapped string, exact bool) CompositeClaimStrength {
|
||||
if strings.TrimSpace(mapped) == "" {
|
||||
return CompositeClaimNone
|
||||
}
|
||||
if exact {
|
||||
return CompositeClaimExplicit
|
||||
}
|
||||
return CompositeClaimWildcard
|
||||
}
|
||||
|
||||
// CompositeAccountClaimsModel 报告 account 在「配置态」是否能提供 model,是
|
||||
// composite 候选平台选择期与后续构建期共用的统一能力谓词(任意强度命中均为
|
||||
// true:通配账号在其平台入池后仍可被 selector 选中,与转发阶段映射一致)。
|
||||
//
|
||||
// 规则(评审收敛版):
|
||||
// - A. 有效 model_mapping 非空:精确 / 既有通配(最长优先,含平台既有归一化
|
||||
// 回退)命中且映射目标非空才可 claim;未命中不 native fallback。
|
||||
// Grok / Antigravity / Gemini GoogleOne 的默认映射经 GetModelMapping 生效,
|
||||
// 归入本规则,与转发阶段账号级映射保持一致。
|
||||
// - B. 有效 model_mapping 为空:仅当 DetectModelPlatform(model) 与账号平台
|
||||
// 一致且既有 IsModelSupported 通过才可 claim。opencode_go 无 detector 分支,
|
||||
// 空 mapping 永不入池,仅显式 mapping 命中可入池。
|
||||
//
|
||||
// 空 mapping 账号不得凭 IsModelSupported 的 allow-all 语义冒领其他平台的模型。
|
||||
// ownership 的池构成按 CompositeAccountClaimStrength 分层:有强声明平台时仅强
|
||||
// 声明平台入池,完全无强声明才使用通配命中平台集合。
|
||||
func CompositeAccountClaimsModel(account *Account, model string) bool {
|
||||
return CompositeAccountClaimStrength(account, model) != CompositeClaimNone
|
||||
}
|
||||
|
||||
// CompositeAccountMeetsClaimTier 是选号期的 composite 归属判定(account_model 否决与
|
||||
// 账号池模型门共用):账号对公开模型的声明强度须达到构成本次归属时采用的层级。存在
|
||||
// 强声明平台时只有强声明账号可承接,通配 catch-all 账号不得冒领显式绑定的公开模型;
|
||||
// ctx 无层级信息时任意强度均可(等价 CompositeAccountClaimsModel)。
|
||||
func CompositeAccountMeetsClaimTier(ctx context.Context, account *Account, model string) bool {
|
||||
strength := CompositeAccountClaimStrength(account, model)
|
||||
if strength == CompositeClaimNone {
|
||||
return false
|
||||
}
|
||||
if ctx == nil {
|
||||
return true
|
||||
}
|
||||
required, ok := ctx.Value(ctxkey.CompositeRequiredClaimStrength).(CompositeClaimStrength)
|
||||
return !ok || strength >= required
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 统一能力谓词 CompositeAccountClaimsModel 的契约测试(评审C收敛规则)。
|
||||
|
||||
func TestCompositeAccountClaimsModel_NilAndEmptyInputs(t *testing.T) {
|
||||
require.False(t, CompositeAccountClaimsModel(nil, "gpt-5"))
|
||||
account := &Account{Platform: PlatformOpenAI}
|
||||
require.False(t, CompositeAccountClaimsModel(account, ""))
|
||||
require.False(t, CompositeAccountClaimsModel(account, " "))
|
||||
}
|
||||
|
||||
// 规则A:非空 mapping 仅精确/既有通配命中才 claim。
|
||||
func TestCompositeAccountClaimsModel_ExplicitMappingExactAndWildcard(t *testing.T) {
|
||||
account := &Account{
|
||||
Platform: PlatformOpenAI,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{
|
||||
"my-gpt": "gpt-5",
|
||||
"team-*": "gpt-5.1",
|
||||
"empty-target": "",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
require.True(t, CompositeAccountClaimsModel(account, "my-gpt"))
|
||||
require.True(t, CompositeAccountClaimsModel(account, "team-alpha"))
|
||||
// 非空 mapping 未命中 → 不允许 native fallback(测试 d)。
|
||||
require.False(t, CompositeAccountClaimsModel(account, "gpt-5"))
|
||||
require.False(t, CompositeAccountClaimsModel(account, "unknown-alias"))
|
||||
// 映射目标为空的条目不构成可路由声明。
|
||||
require.False(t, CompositeAccountClaimsModel(account, "empty-target"))
|
||||
}
|
||||
|
||||
// 规则A(归一化回退):既有平台归一化后的命中仍算 claim。
|
||||
func TestCompositeAccountClaimsModel_NormalizedLookupHit(t *testing.T) {
|
||||
account := &Account{
|
||||
Platform: PlatformGemini,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"gemini-3.1-pro-preview": "gemini-3.1-pro-preview"},
|
||||
},
|
||||
}
|
||||
require.True(t, CompositeAccountClaimsModel(account, "gemini-3.1-pro-preview-customtools"))
|
||||
}
|
||||
|
||||
// 规则B:空 mapping 仅当 detector 平台一致且 IsModelSupported 通过。
|
||||
func TestCompositeAccountClaimsModel_EmptyMappingNativeOnly(t *testing.T) {
|
||||
deepseek := &Account{Platform: PlatformDeepseek}
|
||||
// 使用受支持的 DeepSeek 模型名(空 mapping native claim 受官方白名单约束)。
|
||||
require.True(t, CompositeAccountClaimsModel(deepseek, "deepseek-flash"))
|
||||
|
||||
// detector 平台不一致的空 mapping 账号不得冒领(测试 b 的谓词面)。
|
||||
openAI := &Account{Platform: PlatformOpenAI}
|
||||
require.False(t, CompositeAccountClaimsModel(openAI, "deepseek-flash"))
|
||||
zhipu := &Account{Platform: PlatformZhipu}
|
||||
require.False(t, CompositeAccountClaimsModel(zhipu, "deepseek-flash"))
|
||||
|
||||
// detector 不认识的模型,空 mapping 任何平台都不得 claim。
|
||||
require.False(t, CompositeAccountClaimsModel(deepseek, "unknown-alias"))
|
||||
}
|
||||
|
||||
// opencode_go 无 detector 分支:空 mapping 永不入池(评审C修正,测试 c),
|
||||
// 仅显式 mapping 命中可入池。
|
||||
func TestCompositeAccountClaimsModel_OpenCodeGoRequiresExplicitMapping(t *testing.T) {
|
||||
opencode := &Account{Platform: PlatformOpenCodeGo}
|
||||
require.False(t, CompositeAccountClaimsModel(opencode, "deepseek-chat"))
|
||||
require.False(t, CompositeAccountClaimsModel(opencode, "gpt-5"))
|
||||
require.False(t, CompositeAccountClaimsModel(opencode, "unknown-alias"))
|
||||
|
||||
mapped := &Account{
|
||||
Platform: PlatformOpenCodeGo,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"deepseek-chat": "deepseek-chat"},
|
||||
},
|
||||
}
|
||||
require.True(t, CompositeAccountClaimsModel(mapped, "deepseek-chat"))
|
||||
require.False(t, CompositeAccountClaimsModel(mapped, "gpt-5"))
|
||||
}
|
||||
|
||||
// OpenAI OAuth 空 mapping 保持既有 foreign-model / servable 限制。
|
||||
func TestCompositeAccountClaimsModel_OpenAIOAuthKeepsServableRestriction(t *testing.T) {
|
||||
oauth := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
|
||||
require.True(t, CompositeAccountClaimsModel(oauth, "gpt-5"))
|
||||
require.False(t, CompositeAccountClaimsModel(oauth, "deepseek-v4-pro"))
|
||||
|
||||
// 显式映射命中仍按规则A claim。
|
||||
mapped := &Account{
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeOAuth,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"deepseek-v4-pro": "deepseek-v4-pro"},
|
||||
},
|
||||
}
|
||||
require.True(t, CompositeAccountClaimsModel(mapped, "deepseek-v4-pro"))
|
||||
}
|
||||
|
||||
// Grok 默认映射经 GetModelMapping 生效,归入规则A(与转发阶段映射一致)。
|
||||
func TestCompositeAccountClaimsModel_GrokDefaultMappingUsesRuleA(t *testing.T) {
|
||||
grok := &Account{Platform: PlatformGrok}
|
||||
require.True(t, CompositeAccountClaimsModel(grok, "grok-4.3"))
|
||||
// detector 识别为 grok 但不在有效映射中的模型不 claim。
|
||||
require.False(t, CompositeAccountClaimsModel(grok, "grok-future-unknown"))
|
||||
}
|
||||
|
||||
// 声明强度分级:精确/受控 native 为强声明,通配为弱声明,空目标显式条目
|
||||
// 无声明且不回落通配。
|
||||
func TestCompositeAccountClaimStrength(t *testing.T) {
|
||||
exact := &Account{
|
||||
Platform: PlatformDeepseek,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"deepseek-chat": "deepseek-chat"},
|
||||
},
|
||||
}
|
||||
require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(exact, "deepseek-chat"))
|
||||
require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(exact, "deepseek-v4"))
|
||||
|
||||
wildcard := &Account{
|
||||
Platform: PlatformOpenAI,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"*": "gpt-5", "gpt-*": "gpt-5.1"},
|
||||
},
|
||||
}
|
||||
require.Equal(t, CompositeClaimWildcard, CompositeAccountClaimStrength(wildcard, "any-alias"))
|
||||
// 精确键优先于通配(同为 mapping 命中时精确是强声明)。
|
||||
withExact := &Account{
|
||||
Platform: PlatformOpenAI,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"*": "gpt-5", "gpt-5": "gpt-5"},
|
||||
},
|
||||
}
|
||||
require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(withExact, "gpt-5"))
|
||||
|
||||
// 空目标显式条目遮蔽通配:不构成声明也不回落(与转发匹配顺序一致)。
|
||||
emptyTarget := &Account{
|
||||
Platform: PlatformOpenAI,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"empty-alias": "", "*": "gpt-5"},
|
||||
},
|
||||
}
|
||||
require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(emptyTarget, "empty-alias"))
|
||||
|
||||
// 受控 native 空 mapping 与精确同强等级(模型名须在 deepseek 官方白名单内)。
|
||||
native := &Account{Platform: PlatformDeepseek}
|
||||
require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(native, "deepseek-flash"))
|
||||
// detector 不认识的模型无声明。
|
||||
require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(native, "unknown-alias"))
|
||||
require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(nil, "gpt-5"))
|
||||
}
|
||||
|
||||
// 通配一致性(测试 g):同一通配映射在 claim 与既有 IsModelSupported 语义一致。
|
||||
func TestCompositeAccountClaimsModel_WildcardConsistentWithSupport(t *testing.T) {
|
||||
account := &Account{
|
||||
Platform: PlatformDeepseek,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"deepseek-v4*": "deepseek-v4"},
|
||||
},
|
||||
}
|
||||
for _, model := range []string{"deepseek-v4", "deepseek-v4-flash", "deepseek-v4-pro"} {
|
||||
require.True(t, CompositeAccountClaimsModel(account, model), "model=%s", model)
|
||||
require.True(t, account.IsModelSupported(model), "model=%s", model)
|
||||
}
|
||||
require.False(t, CompositeAccountClaimsModel(account, "deepseek-v3"))
|
||||
}
|
||||
|
||||
// 瞬态字段不参与能力判定(测试 f 的谓词面):限流/过载中的账号能力不变。
|
||||
func TestCompositeAccountClaimsModel_IgnoresTransientState(t *testing.T) {
|
||||
now := time.Now()
|
||||
account := &Account{
|
||||
Platform: PlatformDeepseek,
|
||||
RateLimitedAt: &now,
|
||||
RateLimitResetAt: &now,
|
||||
OverloadUntil: &now,
|
||||
}
|
||||
require.True(t, CompositeAccountClaimsModel(account, "deepseek-flash"))
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// antigravity 账号只有管理员显式配置的映射构成 composite 声明;平台默认映射(Claude /
|
||||
// Gemini 模型)属于混合调度语义,无论是否开启混合调度都不构成声明。
|
||||
func TestCompositeClaimAntigravityOnlyExplicitMappingClaims(t *testing.T) {
|
||||
const model = "claude-sonnet-4-5"
|
||||
mixedOff := &Account{ID: 1, Platform: PlatformAntigravity, Type: AccountTypeOAuth}
|
||||
require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(mixedOff, model))
|
||||
require.False(t, CompositeAccountClaimsModel(mixedOff, model))
|
||||
|
||||
mixedOn := &Account{ID: 2, Platform: PlatformAntigravity, Type: AccountTypeOAuth, Extra: map[string]any{"mixed_scheduling": true}}
|
||||
require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(mixedOn, model),
|
||||
"混合调度开启时默认映射也不构成声明,否则与 anthropic 静默成池")
|
||||
|
||||
explicitMixedOff := &Account{ID: 3, Platform: PlatformAntigravity, Type: AccountTypeOAuth,
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{"team-alias": "claude-opus-4-8"}}}
|
||||
require.Equal(t, CompositeClaimExplicit, CompositeAccountClaimStrength(explicitMixedOff, "team-alias"))
|
||||
require.Equal(t, CompositeClaimNone, CompositeAccountClaimStrength(explicitMixedOff, model), "默认映射条目不因存在自定义映射而生效")
|
||||
}
|
||||
|
||||
// 「anthropic 原生账号 + 开启混合调度的 antigravity」分组:归属解析为 anthropic 单目标
|
||||
// (不成池),antigravity 经混合调度展开服务——配额、渠道定价与分组模型路由仍按
|
||||
// anthropic,与 main 一致;混合调度展开的账号不受 account_model 归属层级否决。
|
||||
func TestCompositeAnthropicWithMixedAntigravityStaysSingleTarget(t *testing.T) {
|
||||
const (
|
||||
group = int64(21)
|
||||
model = "claude-sonnet-4-5"
|
||||
)
|
||||
antigravity := Account{ID: 212, Platform: PlatformAntigravity, Type: AccountTypeOAuth, Extra: map[string]any{"mixed_scheduling": true}}
|
||||
resolver, _ := newOllamaOwnershipResolver(
|
||||
compositeOwnershipScopedRecord{groupID: group, platform: PlatformAnthropic, schedulable: true,
|
||||
account: Account{ID: 211, Platform: PlatformAnthropic, Type: AccountTypeAPIKey}},
|
||||
compositeOwnershipScopedRecord{groupID: group, platform: PlatformAntigravity, schedulable: true, account: antigravity},
|
||||
)
|
||||
|
||||
decision, err := resolver.Resolve(context.Background(), group, model, CompositeRouteEndpointMessages)
|
||||
require.NoError(t, err)
|
||||
require.True(t, decision.Matched)
|
||||
require.Equal(t, PlatformAnthropic, decision.TargetPlatform)
|
||||
require.Empty(t, decision.CandidatePlatforms, "不得与混合调度 antigravity 构成账号池")
|
||||
|
||||
ctx := WithCompositeRouteDecision(context.Background(), decision)
|
||||
require.Equal(t, CompositeRouteSourceAccount, ctx.Value(ctxkey.CompositeRouteSource))
|
||||
svc := &GatewayService{}
|
||||
require.True(t, svc.isModelSupportedByAccountWithContext(ctx, &antigravity, model),
|
||||
"混合调度展开的 antigravity 账号按映射判定可服务,不被归属层级否决")
|
||||
|
||||
mixedOff := antigravity
|
||||
mixedOff.Extra = nil
|
||||
require.False(t, compositeMixedSchedulingExpandedAccount(ctx, &mixedOff), "未开启混合调度不属于展开账号")
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 存在强声明平台时,account_model 否决与池模型门只放行强声明账号:同平台的通配
|
||||
// catch-all 账号不得冒领管理员显式绑定的公开模型(main 上该否决为精确匹配)。
|
||||
func TestCompositeAccountMeetsClaimTierFollowsOwnershipTier(t *testing.T) {
|
||||
const publicModel = "grok-public"
|
||||
explicit := &Account{ID: 1, Platform: PlatformGrok, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{publicModel: "grok-4.3"}}}
|
||||
wildcard := &Account{ID: 2, Platform: PlatformGrok, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{"*": "grok-3-mini"}}}
|
||||
none := &Account{ID: 3, Platform: PlatformGrok, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{"other": "grok-3"}}}
|
||||
|
||||
strongCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{
|
||||
Matched: true, Source: CompositeRouteSourceAccount, PublicModel: publicModel,
|
||||
TargetPlatform: PlatformGrok, UpstreamModel: publicModel, RequiredClaimStrength: CompositeClaimExplicit,
|
||||
})
|
||||
require.True(t, CompositeAccountMeetsClaimTier(strongCtx, explicit, publicModel))
|
||||
require.False(t, CompositeAccountMeetsClaimTier(strongCtx, wildcard, publicModel))
|
||||
require.False(t, CompositeAccountMeetsClaimTier(strongCtx, none, publicModel))
|
||||
|
||||
// 无强声明、按通配回退构成归属时,通配账号可承接。
|
||||
wildcardCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{
|
||||
Matched: true, Source: CompositeRouteSourceAccount, PublicModel: publicModel,
|
||||
TargetPlatform: PlatformGrok, UpstreamModel: publicModel, RequiredClaimStrength: CompositeClaimWildcard,
|
||||
})
|
||||
require.True(t, CompositeAccountMeetsClaimTier(wildcardCtx, wildcard, publicModel))
|
||||
require.False(t, CompositeAccountMeetsClaimTier(wildcardCtx, none, publicModel))
|
||||
|
||||
// 无层级信息:任意强度均可(等价 CompositeAccountClaimsModel)。
|
||||
require.True(t, CompositeAccountMeetsClaimTier(context.Background(), wildcard, publicModel))
|
||||
|
||||
// 池决策同样携带层级。
|
||||
poolCtx := WithCompositeRouteDecision(context.Background(), CompositeRouteDecision{
|
||||
Matched: true, Source: CompositeRouteSourceAccountPool, PublicModel: publicModel,
|
||||
CandidatePlatforms: []string{PlatformGrok, PlatformOpenAI}, RequiredClaimStrength: CompositeClaimExplicit,
|
||||
})
|
||||
require.False(t, CompositeAccountMeetsClaimTier(poolCtx, wildcard, publicModel))
|
||||
}
|
||||
|
||||
func TestResolveCompositeModelOwnershipRecordsClaimTier(t *testing.T) {
|
||||
const group = int64(11)
|
||||
strongRepo := &compositeOwnershipScopedRepo{records: []compositeOwnershipScopedRecord{
|
||||
{groupID: group, platform: PlatformGrok, schedulable: true, account: mappingAccount(1, PlatformGrok, "alias", "grok-4.3")},
|
||||
{groupID: group, platform: PlatformOpenAI, schedulable: true, account: Account{ID: 2, Platform: PlatformOpenAI, Credentials: map[string]any{"model_mapping": map[string]any{"*": "gpt-5"}}}},
|
||||
}}
|
||||
ownership, err := (&GatewayService{accountRepo: strongRepo}).resolveCompositeModelOwnership(context.Background(), group, "alias")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, PlatformGrok, ownership.TargetPlatform)
|
||||
require.Equal(t, CompositeClaimExplicit, ownership.RequiredClaimStrength)
|
||||
|
||||
wildcardRepo := &compositeOwnershipScopedRepo{records: []compositeOwnershipScopedRecord{
|
||||
{groupID: group, platform: PlatformOpenAI, schedulable: true, account: Account{ID: 2, Platform: PlatformOpenAI, Credentials: map[string]any{"model_mapping": map[string]any{"*": "gpt-5"}}}},
|
||||
}}
|
||||
ownership, err = (&GatewayService{accountRepo: wildcardRepo}).resolveCompositeModelOwnership(context.Background(), group, "alias")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, PlatformOpenAI, ownership.TargetPlatform)
|
||||
require.Equal(t, CompositeClaimWildcard, ownership.RequiredClaimStrength)
|
||||
}
|
||||
|
||||
func TestCompositeRouteResolverPropagatesClaimTier(t *testing.T) {
|
||||
const group = int64(12)
|
||||
resolver, _ := newOllamaOwnershipResolver(
|
||||
compositeOwnershipScopedRecord{groupID: group, platform: PlatformGrok, schedulable: true,
|
||||
account: mappingAccount(1, PlatformGrok, "alias", "grok-4.3")},
|
||||
compositeOwnershipScopedRecord{groupID: group, platform: PlatformGrok, schedulable: true,
|
||||
account: Account{ID: 2, Platform: PlatformGrok, Credentials: map[string]any{"model_mapping": map[string]any{"*": "grok-3-mini"}}}},
|
||||
)
|
||||
decision, err := resolver.Resolve(context.Background(), group, "alias", CompositeRouteEndpointResponses)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, CompositeRouteSourceAccount, decision.Source)
|
||||
require.Equal(t, CompositeClaimExplicit, decision.RequiredClaimStrength)
|
||||
|
||||
ctx := WithCompositeRouteDecision(context.Background(), decision)
|
||||
require.True(t, CompositeAccountMeetsClaimTier(ctx, &Account{ID: 1, Platform: PlatformGrok,
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{"alias": "grok-4.3"}}}, "alias"))
|
||||
require.False(t, CompositeAccountMeetsClaimTier(ctx, &Account{ID: 2, Platform: PlatformGrok,
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{"*": "grok-3-mini"}}}, "alias"))
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
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
|
||||
}
|
||||
// 本次请求被策略 deny 的平台整平台排除(与 OpenAI 族调度门同语义),覆盖
|
||||
// 不经 listSchedulableAccountsForCompositePool 取号的 sticky / 路由 / legacy 路径。
|
||||
if compositePoolPlatformDenied(ctx, account.Platform) {
|
||||
return false
|
||||
}
|
||||
// 委派 OpenAI 网关链的 openai / grok 账号不经 OpenAI 调度资格门,沿用其配额自动暂停。
|
||||
if paused, _ := shouldAutoPauseOpenAIAccountByQuota(ctx, account); paused {
|
||||
return false
|
||||
}
|
||||
if paused, _ := shouldAutoPauseGrokAccountByQuota(account); paused {
|
||||
return false
|
||||
}
|
||||
for _, platform := range CompositeCandidatePlatformsFromContext(ctx) {
|
||||
if platform == account.Platform {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// withCompositePoolQuotaAutoPauseContext 为 generic 账号池选号注入 OpenAI 配额自动暂停
|
||||
// 的全局默认阈值(与 OpenAI 调度器同源,SettingService 内存缓存,不读库)。
|
||||
func (s *GatewayService) withCompositePoolQuotaAutoPauseContext(ctx context.Context) context.Context {
|
||||
if s == nil || s.settingService == nil || !GenericCompositePoolActive(ctx) {
|
||||
return ctx
|
||||
}
|
||||
return withOpenAIQuotaAutoPauseSettings(ctx, s.settingService.GetOpenAIQuotaAutoPauseSettings(ctx))
|
||||
}
|
||||
|
||||
// genericCompositePoolAccountServable 报告账号能否被 generic messages 路径服务。
|
||||
// 纯能力判定,不依赖候选池:
|
||||
// - PlatformAnthropic:generic 网关原生账号(OAuth/APIKey/ServiceAccount);
|
||||
// - gemini / antigravity:既有 generic 调度支持的平台;
|
||||
// - anthropic-协议 / adaptive 多协议账号:要求 APIKey 类型且能解析出 Anthropic 协议
|
||||
// 上游 base(GetAnthropicProtocolBaseURL 非空,含 api_base_urls.anthropic 与供应商×
|
||||
// 模式默认端点),避免入池后转发期才发现无端点可用或回落官方 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.RequiresOpenAIProtocolChain() {
|
||||
// 由 handler 层委派 OpenAI 网关链转发(按模型分流 / 协议转换),不要求
|
||||
// Anthropic 协议上游 base。
|
||||
return true
|
||||
}
|
||||
if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() {
|
||||
// generic Forward 只对 APIKey 账号使用协议化 base(buildUpstreamRequest),其余
|
||||
// 类型回落官方 api.anthropic.com:非 APIKey 的多协议账号(异常配置)入池会把
|
||||
// 自身凭据发往 Anthropic,一律不可服务。
|
||||
return account.Type == AccountTypeAPIKey && 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
|
||||
}
|
||||
if account.RequiresOpenAIProtocolChain() {
|
||||
return false
|
||||
}
|
||||
return account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol()
|
||||
}
|
||||
|
||||
// RequiresOpenAIProtocolChain 报告 adaptive 多协议账号在跨族账号池中是否只能由
|
||||
// OpenAI 网关链转发:按模型分流的聚合平台(OpenCode、Command Code)须按
|
||||
// protocol_rules / 模型目录逐模型选协议,只有该链(resolveUpstreamProtocol)实现了
|
||||
// 这一分流;没有 Anthropic 原生端点的供应商(如 Cline 只有 Chat Completions)须由
|
||||
// 该链做协议转换。其余 adaptive 账号(国产厂商、Ollama Cloud)具备 Anthropic 原生
|
||||
// 端点,仍走 generic 转发。
|
||||
func (a *Account) RequiresOpenAIProtocolChain() bool {
|
||||
if a == nil || !a.IsMultiProtocolAPIKey() || !a.IsAdaptiveAPIProtocol() {
|
||||
return false
|
||||
}
|
||||
return a.routesByModel() || strings.TrimSpace(a.GetAnthropicProtocolBaseURL()) == ""
|
||||
}
|
||||
@@ -0,0 +1,674 @@
|
||||
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)
|
||||
}
|
||||
|
||||
// ---- e1. 委派 OpenAI 链的账号沿用配额自动暂停 ----
|
||||
|
||||
func TestGenericCompositePool_SkipsQuotaAutoPausedOpenAIAccount(t *testing.T) {
|
||||
groupID := int64(41007)
|
||||
group := newGenericPoolTestGroup(groupID)
|
||||
model := "my-model"
|
||||
ctx := genericPoolTestContext([]string{PlatformAnthropic, PlatformOpenAI})
|
||||
|
||||
build := func(usedPercent float64) *GatewayService {
|
||||
openai := genericPoolTestAccount(44601, PlatformOpenAI, groupID, 0,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "gpt-5.4"}},
|
||||
map[string]any{"codex_5h_used_percent": usedPercent, "auto_pause_5h_threshold": 0.95})
|
||||
anthropic := genericPoolTestAccount(44602, PlatformAnthropic, groupID, 5,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil)
|
||||
svc, _ := newGenericPoolTestService([]Account{openai, anthropic}, group, &compositePoolTestCache{}, nil)
|
||||
return svc
|
||||
}
|
||||
|
||||
selected, err := build(50).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44601, selected.ID, "未达阈值时 openai 按 priority 获胜")
|
||||
|
||||
selected, err = build(95).SelectAccountForModelWithExclusions(ctx, &groupID, "", model, nil)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 44602, selected.ID, "达到自动暂停阈值的 openai 账号不得被池选中")
|
||||
|
||||
// SelectAccountWithLoadAwareness 在内部经 resolvePlatform 解析出候选池时(入参 ctx
|
||||
// 尚未携带 CompositeCandidatePlatforms),同样须注入全局默认配额暂停阈值。
|
||||
loadCfg := &config.Config{}
|
||||
loadCfg.Gateway.Scheduling.LoadBatchEnabled = true
|
||||
openaiGlobalPaused := genericPoolTestAccount(44603, PlatformOpenAI, groupID, 0,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "gpt-5.4"}},
|
||||
map[string]any{"codex_5h_used_percent": 95.0})
|
||||
anthropicBackup := genericPoolTestAccount(44604, PlatformAnthropic, groupID, 5,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "claude-sonnet-4-5"}}, nil)
|
||||
svcLoadAware, _ := newGenericPoolTestService([]Account{openaiGlobalPaused, anthropicBackup}, group, &compositePoolTestCache{}, loadCfg)
|
||||
svcLoadAware.concurrencyService = NewConcurrencyService(schedulerTestConcurrencyCache{})
|
||||
svcLoadAware.compositeResolver = NewCompositeRouteResolver(nil)
|
||||
svcLoadAware.compositeResolver.SetModelOwnershipResolver(func(_ context.Context, _ int64, _ string) (CompositeModelOwnership, error) {
|
||||
return CompositeModelOwnership{
|
||||
Matched: true,
|
||||
CandidatePlatforms: []string{PlatformAnthropic, PlatformOpenAI},
|
||||
RequiredClaimStrength: CompositeClaimExplicit,
|
||||
}, nil
|
||||
})
|
||||
settingSvc := &SettingService{}
|
||||
settingSvc.openAIQuotaAutoPauseSettingsCache.Store(&cachedOpenAIQuotaAutoPauseSettings{
|
||||
settings: OpsOpenAIAccountQuotaAutoPauseSettings{DefaultThreshold5h: 0.90},
|
||||
expiresAt: time.Now().Add(time.Hour).UnixNano(),
|
||||
})
|
||||
svcLoadAware.settingService = settingSvc
|
||||
res, err := svcLoadAware.SelectAccountWithLoadAwareness(context.Background(), &groupID, "", model, nil, "", 0)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, res)
|
||||
require.EqualValues(t, 44604, res.Account.ID, "内部解析候选池时全局 5h 配额暂停阈值同样生效")
|
||||
|
||||
// generic 池模型能力门保留平台特定约束(如 Antigravity thinking 后缀与 OpenAI 退役模型)。
|
||||
poolCtx := genericPoolTestContext([]string{PlatformAntigravity, PlatformOpenAI})
|
||||
agNoThinking := genericPoolTestAccount(44605, PlatformAntigravity, groupID, 0,
|
||||
map[string]any{"model_mapping": map[string]any{"claude-sonnet-4-5": "claude-sonnet-4-5"}}, nil)
|
||||
thinkingCtx := WithThinkingEnabled(poolCtx, true, false)
|
||||
require.False(t, svcLoadAware.gatewaySchedulingModelSupported(thinkingCtx, &agNoThinking, "claude-sonnet-4-5"))
|
||||
oauthRetired := genericPoolTestAccount(44606, PlatformOpenAI, groupID, 0,
|
||||
map[string]any{"model_mapping": map[string]any{"my-model": "gpt-5.5"}}, nil)
|
||||
oauthRetired.Type = AccountTypeOAuth
|
||||
require.False(t, svcLoadAware.gatewaySchedulingModelSupported(poolCtx, &oauthRetired, "my-model"))
|
||||
}
|
||||
|
||||
// ---- 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))
|
||||
|
||||
// 非 APIKey 的多协议账号(异常配置):generic Forward 不用协议化 base、回落官方
|
||||
// api.anthropic.com,入池会把自身凭据发往 Anthropic,不可服务。
|
||||
zhipuAnthropicOAuth := zhipuAnthropic
|
||||
zhipuAnthropicOAuth.Type = AccountTypeOAuth
|
||||
require.False(t, genericCompositePoolAccountServable(&zhipuAnthropicOAuth))
|
||||
kimiAdaptiveOAuth := kimiAdaptive
|
||||
kimiAdaptiveOAuth.Type = AccountTypeOAuth
|
||||
require.False(t, genericCompositePoolAccountServable(&kimiAdaptiveOAuth))
|
||||
|
||||
// 池成员资格:平台 ∈ 候选池为准;池外平台一律拒绝。
|
||||
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")
|
||||
deniedCtx := WithCompositePoolDeniedPlatforms(poolCtx, []string{PlatformOpenAI})
|
||||
require.False(t, genericCompositePoolAllowsAccount(deniedCtx, &openai), "被 deny 的平台整平台排除(含 sticky 复检)")
|
||||
require.True(t, genericCompositePoolAllowsAccount(deniedCtx, &anthropicNative))
|
||||
|
||||
// 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"))
|
||||
}
|
||||
Loaded 100 of 245 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user