mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-01 23:42:12 +00:00
fix(groups): merge main and resolve model allowlist conflicts
This commit is contained in:
252 files changed
+11371
-1598
No files matched your search
@@ -17,6 +17,7 @@ import (
|
||||
// upstreamModel 是最终发往上游的模型 ID。
|
||||
// totalCost 是本次请求的客户计费(倍率前),用于优先级 2。
|
||||
// serviceTier 是最终参与用户计费的 OpenAI 服务层级,用于优先级 3。
|
||||
// reasoningEffort 是最终转发等级;Fable 5.1 max 默认按 3 倍额度消耗。
|
||||
func resolveAccountStatsCost(
|
||||
ctx context.Context,
|
||||
channelService *ChannelService,
|
||||
@@ -28,7 +29,12 @@ func resolveAccountStatsCost(
|
||||
requestCount int,
|
||||
totalCost float64,
|
||||
serviceTier string,
|
||||
reasoningEfforts ...string,
|
||||
) *float64 {
|
||||
reasoningEffort := ""
|
||||
if len(reasoningEfforts) > 0 {
|
||||
reasoningEffort = reasoningEfforts[0]
|
||||
}
|
||||
if channelService == nil || upstreamModel == "" {
|
||||
return nil
|
||||
}
|
||||
@@ -40,7 +46,7 @@ func resolveAccountStatsCost(
|
||||
platform := channelService.GetGroupPlatform(ctx, groupID)
|
||||
|
||||
// 优先级 1:自定义规则(始终尝试)
|
||||
if cost := tryCustomRules(channel, accountID, groupID, platform, upstreamModel, tokens, requestCount); cost != nil {
|
||||
if cost := tryCustomRules(channel, accountID, groupID, platform, upstreamModel, tokens, requestCount, reasoningEffort); cost != nil {
|
||||
return cost
|
||||
}
|
||||
|
||||
@@ -55,7 +61,7 @@ func resolveAccountStatsCost(
|
||||
|
||||
// 优先级 3:模型定价文件(LiteLLM)默认价格
|
||||
if billingService != nil {
|
||||
return tryModelFilePricing(billingService, upstreamModel, tokens, serviceTier)
|
||||
return tryModelFilePricing(billingService, upstreamModel, tokens, serviceTier, reasoningEffort)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -65,13 +71,18 @@ func resolveAccountStatsCost(
|
||||
// 与用户计费共用同一条定价管线,避免这里维护第二份"单价 × token 数"实现后,
|
||||
// 每加一个定价特性都要手工镜像一次。channelPricing 为 nil,保持优先级 3 的
|
||||
// 语义:只取模型定价文件,不引入渠道自定义定价。
|
||||
func tryModelFilePricing(billingService *BillingService, model string, tokens UsageTokens, serviceTier string) *float64 {
|
||||
func tryModelFilePricing(billingService *BillingService, model string, tokens UsageTokens, serviceTier string, reasoningEfforts ...string) *float64 {
|
||||
reasoningEffort := ""
|
||||
if len(reasoningEfforts) > 0 {
|
||||
reasoningEffort = reasoningEfforts[0]
|
||||
}
|
||||
breakdown, err := billingService.CalculateCostWithServiceTier(
|
||||
model, tokens, 1, normalizeBillingServiceTier(serviceTier),
|
||||
)
|
||||
if err != nil || breakdown == nil || breakdown.TotalCost <= 0 {
|
||||
return nil
|
||||
}
|
||||
applyCostBreakdownMultiplier(breakdown, maxReasoningEffortBillingMultiplier(model, reasoningEffort, nil))
|
||||
return &breakdown.TotalCost
|
||||
}
|
||||
|
||||
@@ -79,7 +90,12 @@ func tryModelFilePricing(billingService *BillingService, model string, tokens Us
|
||||
func tryCustomRules(
|
||||
channel *Channel, accountID, groupID int64,
|
||||
platform, model string, tokens UsageTokens, requestCount int,
|
||||
reasoningEfforts ...string,
|
||||
) *float64 {
|
||||
reasoningEffort := ""
|
||||
if len(reasoningEfforts) > 0 {
|
||||
reasoningEffort = reasoningEfforts[0]
|
||||
}
|
||||
modelLower := strings.ToLower(model)
|
||||
for _, rule := range channel.AccountStatsPricingRules {
|
||||
if !matchAccountStatsRule(&rule, accountID, groupID) {
|
||||
@@ -89,7 +105,11 @@ func tryCustomRules(
|
||||
if pricing == nil {
|
||||
continue // 规则匹配但模型不在规则定价中,继续下一条
|
||||
}
|
||||
return calculateStatsCost(pricing, tokens, requestCount)
|
||||
cost := calculateStatsCost(pricing, tokens, requestCount)
|
||||
if cost != nil {
|
||||
*cost *= maxReasoningEffortBillingMultiplier(model, reasoningEffort, nil)
|
||||
}
|
||||
return cost
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -243,10 +263,14 @@ func applyAccountStatsCost(
|
||||
requestCount = usageLog.ImageCount
|
||||
}
|
||||
serviceTier := ""
|
||||
reasoningEffort := ""
|
||||
if usageLog != nil && usageLog.ServiceTier != nil {
|
||||
serviceTier = *usageLog.ServiceTier
|
||||
}
|
||||
if usageLog != nil && usageLog.ReasoningEffort != nil {
|
||||
reasoningEffort = *usageLog.ReasoningEffort
|
||||
}
|
||||
usageLog.AccountStatsCost = resolveAccountStatsCost(
|
||||
ctx, cs, bs, accountID, groupID, model, tokens, requestCount, totalCost, serviceTier,
|
||||
ctx, cs, bs, accountID, groupID, model, tokens, requestCount, totalCost, serviceTier, reasoningEffort,
|
||||
)
|
||||
}
|
||||
@@ -478,6 +478,18 @@ func TestTryModelFilePricing_Success(t *testing.T) {
|
||||
require.InDelta(t, 0.2, *result, 1e-12)
|
||||
}
|
||||
|
||||
func TestTryModelFilePricing_Fable51MaxEffortUsesTripleQuota(t *testing.T) {
|
||||
bs := newTestBillingServiceWithPrices(map[string]*ModelPricing{
|
||||
"claude-fable-5-1": {InputPricePerToken: 0.001},
|
||||
})
|
||||
tokens := UsageTokens{InputTokens: 100}
|
||||
standard := tryModelFilePricing(bs, "claude-fable-5-1", tokens, "", "xhigh")
|
||||
max := tryModelFilePricing(bs, "claude-fable-5-1", tokens, "", "max")
|
||||
require.NotNil(t, standard)
|
||||
require.NotNil(t, max)
|
||||
require.InDelta(t, *standard*3, *max, 1e-12)
|
||||
}
|
||||
|
||||
func TestTryModelFilePricing_AppliesLongContextPricing(t *testing.T) {
|
||||
bs := newTestBillingServiceWithPrices(map[string]*ModelPricing{
|
||||
"gpt-5.6-sol": {
|
||||
|
||||
@@ -151,6 +151,7 @@ type AccountTestService struct {
|
||||
modelMetadataRegistry map[string]modelsDevProvider
|
||||
modelMetadataRegistryAt time.Time
|
||||
pluginManager *PluginManager
|
||||
openaiGatewayService *OpenAIGatewayService
|
||||
agentIdentityTaskMu sync.Mutex
|
||||
agentIdentityWS agentIdentityWSConnectionInvalidator
|
||||
// grokWSDialer is optional; realtime account tests use the default OpenAI-style
|
||||
@@ -170,6 +171,30 @@ func (s *AccountTestService) SetPluginManager(pluginManager *PluginManager) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AccountTestService) SetOpenAIGatewayService(gateway *OpenAIGatewayService) {
|
||||
if s != nil {
|
||||
s.openaiGatewayService = gateway
|
||||
}
|
||||
}
|
||||
|
||||
// FetchOpenAIAccountModels uses the shared cached discovery path for the test picker.
|
||||
func (s *AccountTestService) FetchOpenAIAccountModels(ctx context.Context, account *Account) ([]openai.Model, error) {
|
||||
if s == nil || s.openaiGatewayService == nil {
|
||||
return nil, errors.New("OpenAI model discovery service is unavailable")
|
||||
}
|
||||
response, err := s.openaiGatewayService.FetchOpenAIModelsList(ctx, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var payload struct {
|
||||
Data []openai.Model `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body, &payload); err != nil {
|
||||
return nil, fmt.Errorf("decode OpenAI account models: %w", err)
|
||||
}
|
||||
return payload.Data, nil
|
||||
}
|
||||
|
||||
// NewAccountTestService creates a new AccountTestService
|
||||
func NewAccountTestService(
|
||||
accountRepo AccountRepository,
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
@@ -21,6 +22,11 @@ import (
|
||||
|
||||
// Account management implementations
|
||||
func (s *adminServiceImpl) ListAccounts(ctx context.Context, page, pageSize int, platform, accountType, status, search string, groupID int64, privacyMode string, sortBy, sortOrder string) ([]Account, int64, error) {
|
||||
if groupID > 0 {
|
||||
if err := s.ValidateAccountGroupBindings(ctx, []int64{groupID}); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
}
|
||||
params := pagination.PaginationParams{Page: page, PageSize: pageSize, SortBy: sortBy, SortOrder: sortOrder}
|
||||
accounts, result, err := s.accountRepo.ListWithFilters(ctx, params, platform, accountType, status, search, groupID, privacyMode)
|
||||
if err != nil {
|
||||
@@ -284,6 +290,9 @@ func (s *adminServiceImpl) DuplicateAccount(ctx context.Context, id int64, actor
|
||||
}
|
||||
autoPauseOnExpired := source.AutoPauseOnExpired
|
||||
groups, groupIDs := duplicateAccountGroups(source)
|
||||
if err := s.ValidateAccountGroupBindings(ctx, groupIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
proxyID := source.ProxyID
|
||||
if source.ProxyFallbackOriginID != nil {
|
||||
// Proxy fallback is transient runtime state; duplicate the configured origin.
|
||||
@@ -512,6 +521,9 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.ValidateAccountGroupBindings(ctx, groupIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.accountRepo.Create(ctx, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -804,6 +816,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if err := s.validateGroupIDsExist(ctx, *input.GroupIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.ValidateAccountGroupBindings(ctx, *input.GroupIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 检查混合渠道风险(除非用户已确认)
|
||||
if !input.SkipMixedChannelCheck {
|
||||
@@ -935,6 +950,9 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
if err := s.validateGroupIDsExist(ctx, *input.GroupIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.ValidateAccountGroupBindings(ctx, *input.GroupIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
openAISettings, err := normalizeBulkOpenAISettings(input)
|
||||
if err != nil {
|
||||
@@ -1352,6 +1370,9 @@ func (s *adminServiceImpl) CreateShadow(ctx context.Context, parentID int64, opt
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := s.ValidateAccountGroupBindings(ctx, groupIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 4. 构造影子账号(安全不变量:Credentials 恒不含 auth token,仅含 model_mapping)。
|
||||
// name 为空时默认 "<母账号名> (Spark)"——否则空 name 会在 ent(name NotEmpty)处变成裸 500
|
||||
@@ -1524,6 +1545,35 @@ func (s *adminServiceImpl) validateGroupIDsExist(ctx context.Context, groupIDs [
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateAccountGroupBindings is the shared fail-closed policy boundary for
|
||||
// every account path that accepts explicit group bindings.
|
||||
func (s *adminServiceImpl) ValidateAccountGroupBindings(ctx context.Context, groupIDs []int64) error {
|
||||
if len(groupIDs) == 0 || s.cfg == nil || s.cfg.RunMode != config.RunModeSimple {
|
||||
return nil
|
||||
}
|
||||
if s.groupRepo == nil {
|
||||
return errors.New("group repository not configured")
|
||||
}
|
||||
seen := make(map[int64]struct{}, len(groupIDs))
|
||||
for _, groupID := range groupIDs {
|
||||
if groupID <= 0 {
|
||||
return fmt.Errorf("get group: %w", ErrGroupNotFound)
|
||||
}
|
||||
if _, ok := seen[groupID]; ok {
|
||||
continue
|
||||
}
|
||||
seen[groupID] = struct{}{}
|
||||
group, err := s.groupRepo.GetByIDLite(ctx, groupID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get group: %w", err)
|
||||
}
|
||||
if !IsGroupBindableInSimpleMode(group) {
|
||||
return infraerrors.BadRequest("SIMPLE_MODE_GROUP_NOT_BINDABLE", "composite groups cannot be bound in simple mode")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckMixedChannelRisk checks whether target groups contain mixed channels for the current account platform.
|
||||
func (s *adminServiceImpl) CheckMixedChannelRisk(ctx context.Context, currentAccountID int64, currentAccountPlatform string, groupIDs []int64) error {
|
||||
return s.checkMixedChannelRisk(ctx, currentAccountID, currentAccountPlatform, groupIDs)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
@@ -20,9 +21,26 @@ import (
|
||||
)
|
||||
|
||||
// Group management implementations
|
||||
func (s *adminServiceImpl) ValidateSimpleModeGroupOperation(operation AdminGroupOperation) error {
|
||||
return ValidateSimpleModeGroupOperation(s.cfg, operation)
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) ListGroups(ctx context.Context, page, pageSize int, platform, status, search string, isExclusive *bool, sortBy, sortOrder string) ([]Group, int64, error) {
|
||||
params := pagination.PaginationParams{Page: page, PageSize: pageSize, SortBy: sortBy, SortOrder: sortOrder}
|
||||
groups, result, err := s.groupRepo.ListWithFilters(ctx, params, platform, status, search, isExclusive)
|
||||
var groups []Group
|
||||
var result *pagination.PaginationResult
|
||||
var err error
|
||||
if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple {
|
||||
repo, ok := s.groupRepo.(interface {
|
||||
ListBindableWithFilters(context.Context, pagination.PaginationParams, string, string, string, *bool) ([]Group, *pagination.PaginationResult, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, 0, errors.New("group repository does not support simple-mode filtering")
|
||||
}
|
||||
groups, result, err = repo.ListBindableWithFilters(ctx, params, platform, status, search, isExclusive)
|
||||
} else {
|
||||
groups, result, err = s.groupRepo.ListWithFilters(ctx, params, platform, status, search, isExclusive)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
@@ -45,7 +63,21 @@ func (s *adminServiceImpl) GetAllGroupsIncludingInactive(ctx context.Context) ([
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) GetGroup(ctx context.Context, id int64) (*Group, error) {
|
||||
return s.groupRepo.GetByID(ctx, id)
|
||||
group, err := s.groupRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.validateSimpleModeGroupAccess(group); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return group, nil
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) validateSimpleModeGroupAccess(group *Group) error {
|
||||
if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple && !IsGroupBindableInSimpleMode(group) {
|
||||
return infraerrors.BadRequest("SIMPLE_MODE_GROUP_NOT_BINDABLE", "composite groups are not supported in simple mode")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) GetGroupModelsListCandidates(ctx context.Context, id int64, platform string) ([]string, error) {
|
||||
@@ -101,6 +133,9 @@ func (s *adminServiceImpl) GetGroupModelsListCandidates(ctx context.Context, id
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) ListCompositeRoutes(ctx context.Context, groupID int64) ([]CompositeModelRoute, error) {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationCompositeRoute); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.requireCompositeGroup(ctx, groupID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -111,6 +146,9 @@ func (s *adminServiceImpl) ListCompositeRoutes(ctx context.Context, groupID int6
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) CreateCompositeRoute(ctx context.Context, groupID int64, input CompositeRouteInput) (*CompositeModelRoute, error) {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationCompositeRoute); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.requireCompositeGroup(ctx, groupID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -128,6 +166,9 @@ func (s *adminServiceImpl) CreateCompositeRoute(ctx context.Context, groupID int
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) UpdateCompositeRoute(ctx context.Context, groupID, routeID int64, input CompositeRouteInput) (*CompositeModelRoute, error) {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationCompositeRoute); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.requireCompositeGroup(ctx, groupID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -151,6 +192,9 @@ func (s *adminServiceImpl) UpdateCompositeRoute(ctx context.Context, groupID, ro
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) DeleteCompositeRoute(ctx context.Context, groupID, routeID int64) error {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationCompositeRoute); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.requireCompositeGroup(ctx, groupID); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -166,6 +210,9 @@ func (s *adminServiceImpl) DeleteCompositeRoute(ctx context.Context, groupID, ro
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) PreviewCompositeRoute(ctx context.Context, groupID int64, input CompositeRoutePreviewRequest) (*CompositeRouteDecision, error) {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationCompositeRoute); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.requireCompositeGroup(ctx, groupID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -308,7 +355,30 @@ func sanitizeGroupOpenAIFast(group *Group) {
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeCreateGroupInputForSimpleMode(input *CreateGroupInput) {
|
||||
if input == nil {
|
||||
return
|
||||
}
|
||||
*input = CreateGroupInput{
|
||||
Name: input.Name, Description: input.Description, Platform: input.Platform,
|
||||
RateMultiplier: 1, SubscriptionType: SubscriptionTypeStandard,
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeUpdateGroupInputForSimpleMode(input *UpdateGroupInput) {
|
||||
if input == nil {
|
||||
return
|
||||
}
|
||||
*input = UpdateGroupInput{Name: input.Name, Description: input.Description}
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupInput) (*Group, error) {
|
||||
if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple && NormalizeGroupPlatform(input.Platform) == PlatformComposite {
|
||||
return nil, infraerrors.BadRequest("SIMPLE_MODE_GROUP_NOT_BINDABLE", "composite groups are not supported in simple mode")
|
||||
}
|
||||
if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple {
|
||||
normalizeCreateGroupInputForSimpleMode(input)
|
||||
}
|
||||
if input.RateMultiplier <= 0 {
|
||||
return nil, errors.New("rate_multiplier must be > 0")
|
||||
}
|
||||
@@ -675,6 +745,15 @@ func (s *adminServiceImpl) UpdateGroup(ctx context.Context, id int64, input *Upd
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.validateSimpleModeGroupAccess(group); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple && input.Platform == PlatformComposite {
|
||||
return nil, infraerrors.BadRequest("SIMPLE_MODE_GROUP_NOT_BINDABLE", "composite groups are not supported in simple mode")
|
||||
}
|
||||
if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple {
|
||||
normalizeUpdateGroupInputForSimpleMode(input)
|
||||
}
|
||||
|
||||
// 渠道缓存里存了 groupID → platform 的映射,改了平台要让它失效(见函数末尾)
|
||||
previousPlatform := group.Platform
|
||||
@@ -1080,6 +1159,27 @@ func normalizeGroupModelPricing(platform string, pricing []ChannelModelPricing)
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) DeleteGroup(ctx context.Context, id int64) error {
|
||||
return s.deleteGroup(ctx, id, false)
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) DeleteGroupIfEmpty(ctx context.Context, id int64) error {
|
||||
return s.deleteGroup(ctx, id, true)
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) deleteGroup(ctx context.Context, id int64, requireEmpty bool) error {
|
||||
if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple {
|
||||
group, err := s.groupRepo.GetByIDLite(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.validateSimpleModeGroupAccess(group); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if requireEmpty && s.emptyGroupDeleteRepo == nil {
|
||||
return fmt.Errorf("guarded group deletion is unavailable")
|
||||
}
|
||||
|
||||
var groupKeys []string
|
||||
if s.authCacheInvalidator != nil {
|
||||
keys, err := s.apiKeyRepo.ListKeysByGroupID(ctx, id)
|
||||
@@ -1088,7 +1188,13 @@ func (s *adminServiceImpl) DeleteGroup(ctx context.Context, id int64) error {
|
||||
}
|
||||
}
|
||||
|
||||
affectedUserIDs, err := s.groupRepo.DeleteCascade(ctx, id)
|
||||
var affectedUserIDs []int64
|
||||
var err error
|
||||
if requireEmpty {
|
||||
affectedUserIDs, err = s.emptyGroupDeleteRepo.DeleteCascadeIfEmpty(ctx, id)
|
||||
} else {
|
||||
affectedUserIDs, err = s.groupRepo.DeleteCascade(ctx, id)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1126,6 +1232,9 @@ func (s *adminServiceImpl) GetGroupAPIKeys(ctx context.Context, groupID int64, p
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) GetGroupRateMultipliers(ctx context.Context, groupID int64) ([]UserGroupRateEntry, error) {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationMultiplier); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.userGroupRateRepo == nil {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -1133,6 +1242,9 @@ func (s *adminServiceImpl) GetGroupRateMultipliers(ctx context.Context, groupID
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) ClearGroupRateMultipliers(ctx context.Context, groupID int64) error {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationMultiplier); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.userGroupRateRepo == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -1140,6 +1252,9 @@ func (s *adminServiceImpl) ClearGroupRateMultipliers(ctx context.Context, groupI
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) BatchSetGroupRateMultipliers(ctx context.Context, groupID int64, entries []GroupRateMultiplierInput) error {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationMultiplier); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.userGroupRateRepo == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -1152,6 +1267,9 @@ func (s *adminServiceImpl) BatchSetGroupRateMultipliers(ctx context.Context, gro
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) ClearGroupRPMOverrides(ctx context.Context, groupID int64) error {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationRPMOverride); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.userGroupRateRepo == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -1166,6 +1284,9 @@ func (s *adminServiceImpl) ClearGroupRPMOverrides(ctx context.Context, groupID i
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) BatchSetGroupRPMOverrides(ctx context.Context, groupID int64, entries []GroupRPMOverrideInput) error {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationRPMOverride); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.userGroupRateRepo == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -1185,6 +1306,9 @@ func (s *adminServiceImpl) BatchSetGroupRPMOverrides(ctx context.Context, groupI
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) UpdateGroupSortOrders(ctx context.Context, updates []GroupSortOrderUpdate) error {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationSort); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.groupRepo.UpdateSortOrders(ctx, updates)
|
||||
}
|
||||
|
||||
|
||||
@@ -166,6 +166,9 @@ func cloneGroupForDuplicate(source *Group, operationID string) *Group {
|
||||
// RecoverDuplicateGroup performs a read-only lookup for a copy that was already
|
||||
// committed for the same actor, source group, and idempotency key.
|
||||
func (s *adminServiceImpl) RecoverDuplicateGroup(ctx context.Context, id int64, actorScope, operationKey string) (*Group, error) {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationDuplicate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
operationID := duplicateGroupOperationID(id, actorScope, operationKey)
|
||||
if operationID == "" {
|
||||
return nil, nil
|
||||
@@ -191,6 +194,9 @@ func (s *adminServiceImpl) RecoverDuplicateGroup(ctx context.Context, id int64,
|
||||
// account priorities. The repository commits the group, bindings, and outbox
|
||||
// event atomically so a failed binding never leaves an orphan group.
|
||||
func (s *adminServiceImpl) DuplicateGroup(ctx context.Context, id int64, actorScope, operationKey string) (*Group, error) {
|
||||
if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationDuplicate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
existing, err := s.RecoverDuplicateGroup(ctx, id, actorScope, operationKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
)
|
||||
|
||||
@@ -48,6 +49,7 @@ type AdminService interface {
|
||||
RecoverDuplicateGroup(ctx context.Context, id int64, actorScope, operationKey string) (*Group, error)
|
||||
UpdateGroup(ctx context.Context, id int64, input *UpdateGroupInput) (*Group, error)
|
||||
DeleteGroup(ctx context.Context, id int64) error
|
||||
DeleteGroupIfEmpty(ctx context.Context, id int64) error
|
||||
ListCompositeRoutes(ctx context.Context, groupID int64) ([]CompositeModelRoute, error)
|
||||
CreateCompositeRoute(ctx context.Context, groupID int64, input CompositeRouteInput) (*CompositeModelRoute, error)
|
||||
UpdateCompositeRoute(ctx context.Context, groupID, routeID int64, input CompositeRouteInput) (*CompositeModelRoute, error)
|
||||
@@ -79,6 +81,7 @@ type AdminService interface {
|
||||
GetAccount(ctx context.Context, id int64) (*Account, error)
|
||||
GetAccountsByIDs(ctx context.Context, ids []int64) ([]*Account, error)
|
||||
CreateAccount(ctx context.Context, input *CreateAccountInput) (*Account, error)
|
||||
ValidateAccountGroupBindings(ctx context.Context, groupIDs []int64) error
|
||||
// DuplicateAccount creates an independent account from an existing account's configuration.
|
||||
// First-class runtime columns are intentionally reset by the normal account creation path.
|
||||
DuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*Account, error)
|
||||
@@ -137,6 +140,24 @@ type AdminService interface {
|
||||
ResetAccountQuota(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
type AdminGroupOperation string
|
||||
|
||||
const (
|
||||
AdminGroupOperationBasic AdminGroupOperation = "basic"
|
||||
AdminGroupOperationDuplicate AdminGroupOperation = "duplicate"
|
||||
AdminGroupOperationCompositeRoute AdminGroupOperation = "composite_route"
|
||||
AdminGroupOperationMultiplier AdminGroupOperation = "multiplier"
|
||||
AdminGroupOperationRPMOverride AdminGroupOperation = "rpm_override"
|
||||
AdminGroupOperationSort AdminGroupOperation = "sort"
|
||||
)
|
||||
|
||||
func ValidateSimpleModeGroupOperation(cfg *config.Config, operation AdminGroupOperation) error {
|
||||
if cfg != nil && cfg.RunMode == config.RunModeSimple && operation != AdminGroupOperationBasic {
|
||||
return infraerrors.New(http.StatusForbidden, "SIMPLE_MODE_OPERATION_UNSUPPORTED", "This operation is not supported in simple mode")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateUserInput represents input for creating a new user via admin operations.
|
||||
type CreateUserInput struct {
|
||||
Email string
|
||||
@@ -277,11 +298,11 @@ type CreateGroupInput struct {
|
||||
CodexModelsManifestConfig GroupCodexModelsManifestConfig
|
||||
// RPMLimit 分组 RPM 上限(0 = 不限制)
|
||||
RPMLimit int
|
||||
// MaxReasoningEffort OpenAI/Codex 请求的推理强度上限,空字符串表示不限制。
|
||||
// MaxReasoningEffort Anthropic/OpenAI 请求的推理强度上限,空字符串表示不限制。
|
||||
MaxReasoningEffort string
|
||||
// MaxReasoningEffortOverLimit 超过上限时的访问控制:downgrade(默认)或 deny。
|
||||
MaxReasoningEffortOverLimit string
|
||||
// ReasoningEffortMappings OpenAI/Codex 推理强度精确映射。
|
||||
// ReasoningEffortMappings Anthropic/OpenAI 推理强度映射,可按模型精确名、前缀或后缀限定。
|
||||
ReasoningEffortMappings []ReasoningEffortMapping
|
||||
// 分组利润控制(五个 token 平台分组可启用;margin/buffer 为小数,nil 按 0 处理)
|
||||
ProfitControlEnabled bool
|
||||
@@ -658,9 +679,11 @@ var ErrRPMStatusUnavailable = infraerrors.New(http.StatusNotImplemented, "RPM_ST
|
||||
|
||||
// adminServiceImpl implements AdminService
|
||||
type adminServiceImpl struct {
|
||||
cfg *config.Config
|
||||
userRepo UserRepository
|
||||
groupRepo GroupRepository
|
||||
groupDuplicateRepo GroupDuplicateRepository
|
||||
emptyGroupDeleteRepo EmptyGroupDeleteRepository
|
||||
accountRepo AccountRepository
|
||||
accountDuplicateRepo AccountDuplicateRepository
|
||||
accountBillingRepo AccountBillingSettingsRepository
|
||||
@@ -702,6 +725,7 @@ type userGroupRateBatchReader interface {
|
||||
|
||||
// NewAdminService creates a new AdminService
|
||||
func NewAdminService(
|
||||
cfg *config.Config,
|
||||
userRepo UserRepository,
|
||||
groupRepo AdminGroupRepository,
|
||||
accountRepo AdminAccountRepository,
|
||||
@@ -726,9 +750,11 @@ func NewAdminService(
|
||||
channelCacheInvalidator ChannelCacheInvalidator,
|
||||
) AdminService {
|
||||
return &adminServiceImpl{
|
||||
cfg: cfg,
|
||||
userRepo: userRepo,
|
||||
groupRepo: groupRepo,
|
||||
groupDuplicateRepo: groupRepo,
|
||||
emptyGroupDeleteRepo: groupRepo,
|
||||
accountRepo: accountRepo,
|
||||
accountDuplicateRepo: accountRepo,
|
||||
accountBillingRepo: accountRepo,
|
||||
|
||||
@@ -247,6 +247,7 @@ type groupRepoStub struct {
|
||||
affectedUserIDs []int64
|
||||
deleteErr error
|
||||
deleteCalls []int64
|
||||
guardedCalls []int64
|
||||
}
|
||||
|
||||
func (s *groupRepoStub) Create(ctx context.Context, group *Group) error {
|
||||
@@ -274,6 +275,11 @@ func (s *groupRepoStub) DeleteCascade(ctx context.Context, id int64) ([]int64, e
|
||||
return s.affectedUserIDs, s.deleteErr
|
||||
}
|
||||
|
||||
func (s *groupRepoStub) DeleteCascadeIfEmpty(ctx context.Context, id int64) ([]int64, error) {
|
||||
s.guardedCalls = append(s.guardedCalls, id)
|
||||
return s.affectedUserIDs, s.deleteErr
|
||||
}
|
||||
|
||||
func (s *groupRepoStub) List(ctx context.Context, params pagination.PaginationParams) ([]Group, *pagination.PaginationResult, error) {
|
||||
panic("unexpected List call")
|
||||
}
|
||||
@@ -703,6 +709,22 @@ func TestAdminService_DeleteGroup_Error(t *testing.T) {
|
||||
require.ErrorIs(t, err, deleteErr)
|
||||
}
|
||||
|
||||
func TestAdminService_DeleteGroupIfEmpty_UsesGuardedCascade(t *testing.T) {
|
||||
repo := &groupRepoStub{deleteErr: ErrGroupNotEmpty}
|
||||
svc := &adminServiceImpl{groupRepo: repo, emptyGroupDeleteRepo: repo}
|
||||
|
||||
err := svc.DeleteGroupIfEmpty(context.Background(), 42)
|
||||
require.ErrorIs(t, err, ErrGroupNotEmpty)
|
||||
require.Equal(t, []int64{42}, repo.guardedCalls)
|
||||
require.Empty(t, repo.deleteCalls)
|
||||
}
|
||||
|
||||
func TestAdminService_DeleteGroupIfEmpty_MissingCapabilityReturnsError(t *testing.T) {
|
||||
svc := &adminServiceImpl{groupRepo: &groupRepoStub{}}
|
||||
|
||||
require.ErrorContains(t, svc.DeleteGroupIfEmpty(context.Background(), 42), "guarded group deletion is unavailable")
|
||||
}
|
||||
|
||||
func TestAdminService_DeleteProxy_Success(t *testing.T) {
|
||||
repo := &proxyRepoStub{}
|
||||
svc := &adminServiceImpl{proxyRepo: repo}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -266,6 +267,28 @@ func TestDuplicateAccountPreservesUngroupedState(t *testing.T) {
|
||||
require.NotContains(t, repo.groupsOf, duplicate.ID)
|
||||
}
|
||||
|
||||
func TestDuplicateAccountSimpleModeRejectsCompositeGroupBinding(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newDuplicateAccountRepoStub()
|
||||
groupRepo := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{
|
||||
9: {ID: 9, Platform: PlatformComposite},
|
||||
}}
|
||||
svc := &adminServiceImpl{
|
||||
cfg: &config.Config{RunMode: config.RunModeSimple}, groupRepo: groupRepo,
|
||||
accountRepo: repo, accountDuplicateRepo: repo,
|
||||
}
|
||||
source := &Account{
|
||||
Name: "composite-bound", Platform: PlatformAnthropic, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "secret"}, GroupIDs: []int64{9},
|
||||
}
|
||||
require.NoError(t, repo.Create(ctx, source))
|
||||
|
||||
_, err := svc.DuplicateAccount(ctx, source.ID, "admin:1", "")
|
||||
|
||||
require.Equal(t, "SIMPLE_MODE_GROUP_NOT_BINDABLE", infraerrors.Reason(err))
|
||||
require.Len(t, repo.accounts, 1)
|
||||
}
|
||||
|
||||
func TestDuplicateAccountAtomicCreateFailureLeavesNoOrphan(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := newDuplicateAccountRepoStub()
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -89,6 +90,10 @@ func (s *groupRepoStubForAdmin) DeleteCascade(_ context.Context, _ int64) ([]int
|
||||
panic("unexpected DeleteCascade call")
|
||||
}
|
||||
|
||||
func (s *groupRepoStubForAdmin) DeleteCascadeIfEmpty(_ context.Context, _ int64) ([]int64, error) {
|
||||
panic("unexpected DeleteCascadeIfEmpty call")
|
||||
}
|
||||
|
||||
func (s *groupRepoStubForAdmin) List(_ context.Context, _ pagination.PaginationParams) ([]Group, *pagination.PaginationResult, error) {
|
||||
panic("unexpected List call")
|
||||
}
|
||||
@@ -117,6 +122,178 @@ func (s *groupRepoStubForAdmin) ListWithFilters(_ context.Context, params pagina
|
||||
return s.listWithFiltersGroups, result, nil
|
||||
}
|
||||
|
||||
func (s *groupRepoStubForAdmin) ListBindableWithFilters(ctx context.Context, params pagination.PaginationParams, platform, status, search string, isExclusive *bool) ([]Group, *pagination.PaginationResult, error) {
|
||||
return s.ListWithFilters(ctx, params, platform, status, search, isExclusive)
|
||||
}
|
||||
|
||||
func TestAdminServiceSimpleModeValidatesRequestedGroupIDsDirectly(t *testing.T) {
|
||||
groups := make(map[int64]*Group, 1002)
|
||||
for id := int64(1); id <= 1001; id++ {
|
||||
groups[id] = &Group{ID: id, Platform: PlatformAnthropic}
|
||||
}
|
||||
groups[1002] = &Group{ID: 1002, Platform: PlatformComposite}
|
||||
svc := &adminServiceImpl{cfg: &config.Config{RunMode: config.RunModeSimple}, groupRepo: &groupRepoStubForAdmin{getByIDByID: groups}}
|
||||
|
||||
require.Error(t, svc.ValidateAccountGroupBindings(context.Background(), []int64{1, 1002}))
|
||||
require.ErrorIs(t, svc.ValidateAccountGroupBindings(context.Background(), []int64{1, 2000}), ErrGroupNotFound)
|
||||
require.NoError(t, svc.ValidateAccountGroupBindings(context.Background(), []int64{1, 1001}))
|
||||
}
|
||||
|
||||
func TestAdminServiceSimpleModeRejectsDirectCompositeGroupAccess(t *testing.T) {
|
||||
repo := &groupRepoStubForAdmin{getByID: &Group{ID: 9, Platform: PlatformComposite}}
|
||||
svc := &adminServiceImpl{cfg: &config.Config{RunMode: config.RunModeSimple}, groupRepo: repo, emptyGroupDeleteRepo: repo}
|
||||
|
||||
_, err := svc.GetGroup(context.Background(), 9)
|
||||
require.Error(t, err)
|
||||
_, err = svc.UpdateGroup(context.Background(), 9, &UpdateGroupInput{})
|
||||
require.Error(t, err)
|
||||
require.Nil(t, repo.updated)
|
||||
require.Error(t, svc.DeleteGroupIfEmpty(context.Background(), 9))
|
||||
}
|
||||
|
||||
func TestAdminServiceSimpleModeRejectsAccountListCompositeFilter(t *testing.T) {
|
||||
repo := &groupRepoStubForAdmin{getByID: &Group{ID: 9, Platform: PlatformComposite}}
|
||||
svc := &adminServiceImpl{cfg: &config.Config{RunMode: config.RunModeSimple}, groupRepo: repo}
|
||||
_, _, err := svc.ListAccounts(context.Background(), 1, 20, "", "", "", "", 9, "", "", "")
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestAdminServiceSimpleModeRejectsAdvancedGroupOperationsDirectly(t *testing.T) {
|
||||
svc := &adminServiceImpl{cfg: &config.Config{RunMode: config.RunModeSimple}}
|
||||
tests := []struct {
|
||||
name string
|
||||
call func() error
|
||||
}{
|
||||
{"duplicate", func() error { _, err := svc.DuplicateGroup(context.Background(), 1, "admin:1", "key"); return err }},
|
||||
{"recover duplicate", func() error {
|
||||
_, err := svc.RecoverDuplicateGroup(context.Background(), 1, "admin:1", "key")
|
||||
return err
|
||||
}},
|
||||
{"list composite routes", func() error { _, err := svc.ListCompositeRoutes(context.Background(), 1); return err }},
|
||||
{"create composite route", func() error {
|
||||
_, err := svc.CreateCompositeRoute(context.Background(), 1, CompositeRouteInput{})
|
||||
return err
|
||||
}},
|
||||
{"update composite route", func() error {
|
||||
_, err := svc.UpdateCompositeRoute(context.Background(), 1, 2, CompositeRouteInput{})
|
||||
return err
|
||||
}},
|
||||
{"delete composite route", func() error { return svc.DeleteCompositeRoute(context.Background(), 1, 2) }},
|
||||
{"preview composite route", func() error {
|
||||
_, err := svc.PreviewCompositeRoute(context.Background(), 1, CompositeRoutePreviewRequest{})
|
||||
return err
|
||||
}},
|
||||
{"get multipliers", func() error { _, err := svc.GetGroupRateMultipliers(context.Background(), 1); return err }},
|
||||
{"clear multipliers", func() error { return svc.ClearGroupRateMultipliers(context.Background(), 1) }},
|
||||
{"set multipliers", func() error { return svc.BatchSetGroupRateMultipliers(context.Background(), 1, nil) }},
|
||||
{"clear rpm overrides", func() error { return svc.ClearGroupRPMOverrides(context.Background(), 1) }},
|
||||
{"set rpm overrides", func() error { return svc.BatchSetGroupRPMOverrides(context.Background(), 1, nil) }},
|
||||
{"sort", func() error { return svc.UpdateGroupSortOrders(context.Background(), nil) }},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.call()
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "SIMPLE_MODE_OPERATION_UNSUPPORTED", infraerrors.Reason(err))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminServiceSimpleModeRejectsCompositeCreateAndConversionDirectly(t *testing.T) {
|
||||
svc := &adminServiceImpl{cfg: &config.Config{RunMode: config.RunModeSimple}}
|
||||
_, err := svc.CreateGroup(context.Background(), &CreateGroupInput{Platform: PlatformComposite, RateMultiplier: 1})
|
||||
require.Error(t, err)
|
||||
|
||||
repo := &groupRepoStubForAdmin{getByID: &Group{ID: 1, Platform: PlatformAnthropic}}
|
||||
svc.groupRepo = repo
|
||||
_, err = svc.UpdateGroup(context.Background(), 1, &UpdateGroupInput{Platform: PlatformComposite})
|
||||
require.Error(t, err)
|
||||
require.Nil(t, repo.updated)
|
||||
}
|
||||
|
||||
func TestAdminServiceSimpleModeNormalizesAllUnsupportedCreateFieldsDirectly(t *testing.T) {
|
||||
one := 1.0
|
||||
fallbackID := int64(44)
|
||||
input := &CreateGroupInput{
|
||||
Name: "simple", Description: "allowed", Platform: PlatformAnthropic,
|
||||
RateMultiplier: 9, IsExclusive: true, SubscriptionType: SubscriptionTypeSubscription,
|
||||
DailyLimitUSD: &one, LongContextPricingEnabled: true,
|
||||
ModelPricing: []ChannelModelPricing{{Models: []string{"claude"}}},
|
||||
PeakRateEnabled: true, PeakStart: "00:00", PeakEnd: "01:00", PeakRateMultiplier: &one,
|
||||
ImageRateIndependent: true, ImageRateMultiplier: &one, VideoRateIndependent: true, VideoRateMultiplier: &one,
|
||||
ImagePrice1K: &one, VideoPrice720P: &one, WebSearchPricePerCall: &one, SearchPricePer1k: &one,
|
||||
AudioRealtimePricePerMin: &one, ClaudeCodeOnly: true, FallbackGroupID: &fallbackID,
|
||||
ModelRouting: map[string][]int64{"claude": {1}}, ModelRoutingEnabled: true,
|
||||
AllowMessagesDispatch: true, AllowLive: true, ForceOpenAIFast: true, RequireOAuthOnly: true,
|
||||
RPMLimit: 99, MaxReasoningEffort: "high", ProfitControlEnabled: true, ProfitMinMargin: &one,
|
||||
CopyAccountsFromGroupIDs: []int64{2},
|
||||
}
|
||||
repo := &groupRepoStubForAdmin{}
|
||||
svc := &adminServiceImpl{cfg: &config.Config{RunMode: config.RunModeSimple}, groupRepo: repo}
|
||||
|
||||
created, err := svc.CreateGroup(context.Background(), input)
|
||||
require.NoError(t, err)
|
||||
require.Same(t, repo.created, created)
|
||||
require.Equal(t, CreateGroupInput{
|
||||
Name: "simple", Description: "allowed", Platform: PlatformAnthropic,
|
||||
RateMultiplier: 1, SubscriptionType: SubscriptionTypeStandard,
|
||||
}, *input)
|
||||
require.Equal(t, 1.0, created.RateMultiplier)
|
||||
require.Equal(t, SubscriptionTypeStandard, created.SubscriptionType)
|
||||
require.False(t, created.IsExclusive)
|
||||
require.Nil(t, created.FallbackGroupID)
|
||||
require.Empty(t, created.ModelPricing)
|
||||
require.Zero(t, created.RPMLimit)
|
||||
}
|
||||
|
||||
func TestAdminServiceSimpleModeNormalizesAllUnsupportedUpdateFieldsDirectly(t *testing.T) {
|
||||
one := 1.0
|
||||
truth := true
|
||||
status := "inactive"
|
||||
description := "allowed"
|
||||
fallbackID := int64(44)
|
||||
pricing := []ChannelModelPricing{{Models: []string{"claude"}}}
|
||||
input := &UpdateGroupInput{
|
||||
Name: "renamed", Description: &description, Platform: PlatformOpenAI, Status: status,
|
||||
RateMultiplier: &one, IsExclusive: &truth, SubscriptionType: SubscriptionTypeSubscription,
|
||||
DailyLimitUSD: &one, LongContextPricingEnabled: &truth, ModelPricing: &pricing,
|
||||
PeakRateEnabled: &truth, PeakRateMultiplier: &one, ImageRateIndependent: &truth,
|
||||
ImageRateMultiplier: &one, VideoRateIndependent: &truth, VideoRateMultiplier: &one,
|
||||
ImagePrice1K: &one, VideoPrice720P: &one, WebSearchPricePerCall: &one, SearchPricePer1k: &one,
|
||||
AudioRealtimePricePerMin: &one, ClaudeCodeOnly: &truth, FallbackGroupID: &fallbackID,
|
||||
ModelRouting: map[string][]int64{"claude": {1}}, ModelRoutingEnabled: &truth,
|
||||
AllowMessagesDispatch: &truth, AllowLive: &truth, ForceOpenAIFast: &truth, RequireOAuthOnly: &truth,
|
||||
RPMLimit: new(int), MaxReasoningEffort: ptrString("high"), ProfitControlEnabled: &truth,
|
||||
ProfitMinMargin: &one, CopyAccountsFromGroupIDs: []int64{2},
|
||||
}
|
||||
existing := &Group{ID: 1, Name: "old", Description: "old description", Platform: PlatformAnthropic, Status: StatusActive, RateMultiplier: 3, RPMLimit: 8, FallbackGroupID: &fallbackID}
|
||||
repo := &groupRepoStubForAdmin{getByID: existing}
|
||||
svc := &adminServiceImpl{cfg: &config.Config{RunMode: config.RunModeSimple}, groupRepo: repo}
|
||||
|
||||
updated, err := svc.UpdateGroup(context.Background(), 1, input)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, UpdateGroupInput{Name: "renamed", Description: &description}, *input)
|
||||
require.Equal(t, "renamed", updated.Name)
|
||||
require.Equal(t, description, updated.Description)
|
||||
require.Equal(t, PlatformAnthropic, updated.Platform)
|
||||
require.Equal(t, StatusActive, updated.Status)
|
||||
require.Equal(t, 3.0, updated.RateMultiplier)
|
||||
require.Equal(t, 8, updated.RPMLimit)
|
||||
require.Equal(t, &fallbackID, updated.FallbackGroupID)
|
||||
}
|
||||
|
||||
func TestAdminServiceSimpleModeListUsesRepositoryFilteredTotal(t *testing.T) {
|
||||
repo := &groupRepoStubForAdmin{
|
||||
listWithFiltersGroups: []Group{{ID: 2, Platform: PlatformAnthropic}},
|
||||
listWithFiltersResult: &pagination.PaginationResult{Total: 11, Page: 2, PageSize: 1},
|
||||
}
|
||||
svc := &adminServiceImpl{cfg: &config.Config{RunMode: config.RunModeSimple}, groupRepo: repo}
|
||||
groups, total, err := svc.ListGroups(context.Background(), 2, 1, "", "", "", nil, "id", "asc")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, groups, 1)
|
||||
require.EqualValues(t, 11, total)
|
||||
}
|
||||
|
||||
func (s *groupRepoStubForAdmin) ListActive(_ context.Context) ([]Group, error) {
|
||||
panic("unexpected ListActive call")
|
||||
}
|
||||
@@ -960,7 +1137,7 @@ func TestAdminService_UpdateGroup_ClearsReasoningPolicyForUnsupportedPlatform(t
|
||||
repo := &groupRepoStubForAdmin{getByID: existing}
|
||||
svc := &adminServiceImpl{groupRepo: repo}
|
||||
|
||||
_, err := svc.UpdateGroup(context.Background(), existing.ID, &UpdateGroupInput{Platform: PlatformAnthropic})
|
||||
_, err := svc.UpdateGroup(context.Background(), existing.ID, &UpdateGroupInput{Platform: PlatformGemini})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, repo.updated.MaxReasoningEffort)
|
||||
|
||||
@@ -115,7 +115,7 @@ type APIKeyAuthGroupSnapshot struct {
|
||||
// RPMLimit 分组级每分钟请求数上限(0 = 不限制);用于 billing_cache_service.checkRPM 级联判断。
|
||||
RPMLimit int `json:"rpm_limit"`
|
||||
|
||||
// MaxReasoningEffort OpenAI/Codex 请求的推理强度上限,空字符串表示不限制。
|
||||
// MaxReasoningEffort Anthropic/OpenAI 请求的推理强度上限,空字符串表示不限制。
|
||||
MaxReasoningEffort string `json:"max_reasoning_effort,omitempty"`
|
||||
// MaxReasoningEffortOverLimit 超过上限时的访问控制:downgrade(默认)或 deny。
|
||||
MaxReasoningEffortOverLimit string `json:"max_reasoning_effort_over_limit,omitempty"`
|
||||
|
||||
@@ -105,6 +105,7 @@ type ModelPricing struct {
|
||||
CacheReadPricePerTokenPriority float64 // priority service tier 下缓存读取每token价格 (USD)
|
||||
FastMultiplier *float64 // 渠道显式 Fast/priority 倍率;nil 时沿用模型目录行为
|
||||
FlexMultiplier *float64 // 渠道显式 Flex 倍率;nil 时沿用默认行为
|
||||
MaxReasoningEffortMultiplier *float64 // max 推理等级的额度/计费倍率;nil 时沿用模型默认行为
|
||||
CacheCreation5mPrice float64 // 5分钟缓存创建每token价格 (USD)
|
||||
CacheCreation1hPrice float64 // 1小时缓存创建每token价格 (USD)
|
||||
SupportsCacheBreakdown bool // 是否支持详细的缓存分类
|
||||
@@ -137,7 +138,7 @@ func usePriorityServiceTierPricing(serviceTier string, pricing *ModelPricing) bo
|
||||
|
||||
func serviceTierCostMultiplier(serviceTier string) float64 {
|
||||
switch normalizeBillingServiceTier(serviceTier) {
|
||||
case "priority", "fast":
|
||||
case "priority", "fast", OpenAIFastTierUltrafast:
|
||||
return 2.0
|
||||
case "flex":
|
||||
return 0.5
|
||||
@@ -214,6 +215,42 @@ func applyCostBreakdownMultiplier(cost *CostBreakdown, multiplier float64) {
|
||||
cost.ActualCost *= multiplier
|
||||
}
|
||||
|
||||
const claudeFable51MaxReasoningEffortMultiplier = 3.0
|
||||
|
||||
func isClaudeFable51Model(model string) bool {
|
||||
model = strings.ToLower(strings.TrimSpace(model))
|
||||
for _, marker := range []string{"fable-5-1", "fable-5.1", "fable5.1", "fable51"} {
|
||||
if at := strings.Index(model, marker); at >= 0 {
|
||||
after := at + len(marker)
|
||||
if after == len(model) || model[after] < '0' || model[after] > '9' {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func defaultMaxReasoningEffortMultiplier(model string) *float64 {
|
||||
if !isClaudeFable51Model(model) {
|
||||
return nil
|
||||
}
|
||||
multiplier := claudeFable51MaxReasoningEffortMultiplier
|
||||
return &multiplier
|
||||
}
|
||||
|
||||
func maxReasoningEffortBillingMultiplier(model, effort string, pricing *ModelPricing) float64 {
|
||||
if NormalizeMaxReasoningEffort(effort) != "max" {
|
||||
return 1
|
||||
}
|
||||
if pricing != nil && pricing.MaxReasoningEffortMultiplier != nil && *pricing.MaxReasoningEffortMultiplier > 0 {
|
||||
return *pricing.MaxReasoningEffortMultiplier
|
||||
}
|
||||
if multiplier := defaultMaxReasoningEffortMultiplier(model); multiplier != nil {
|
||||
return *multiplier
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func resolvedChannelTimeMultiplier(resolved *ResolvedPricing, at time.Time) float64 {
|
||||
if resolved == nil || resolved.Source != PricingSourceChannel || resolved.channelPricing == nil {
|
||||
return 1
|
||||
@@ -431,6 +468,20 @@ func (s *BillingService) initFallbackPricing() {
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
|
||||
s.fallbackPrices["gpt-6-astra"] = &ModelPricing{
|
||||
InputPricePerToken: 10e-6,
|
||||
InputPricePerTokenPriority: 20e-6,
|
||||
OutputPricePerToken: 50e-6,
|
||||
OutputPricePerTokenPriority: 100e-6,
|
||||
CacheCreationPricePerToken: 12.5e-6,
|
||||
CacheCreationPricePerTokenPriority: 25e-6,
|
||||
CacheReadPricePerToken: 1e-6,
|
||||
CacheReadPricePerTokenPriority: 2e-6,
|
||||
LongContextInputThreshold: 272_000,
|
||||
LongContextInputMultiplier: 2,
|
||||
LongContextOutputMultiplier: 1.5,
|
||||
}
|
||||
|
||||
// OpenAI GPT-5.6 官方价格(USD/token)。缓存写入为输入价的 1.25 倍。
|
||||
s.fallbackPrices["gpt-5.6-sol"] = &ModelPricing{
|
||||
InputPricePerToken: 5e-6,
|
||||
@@ -803,8 +854,7 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
|
||||
modelLower := strings.ToLower(model)
|
||||
|
||||
// 按模型系列匹配
|
||||
if strings.Contains(modelLower, "fable-5-1") || strings.Contains(modelLower, "fable-5.1") ||
|
||||
strings.Contains(modelLower, "fable5.1") || strings.Contains(modelLower, "fable51") {
|
||||
if isClaudeFable51Model(modelLower) {
|
||||
return s.fallbackPrices["claude-fable-5-1"]
|
||||
}
|
||||
if strings.Contains(modelLower, "fable-5") || strings.Contains(modelLower, "fable5") {
|
||||
@@ -976,6 +1026,8 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
|
||||
// OpenAI(GPT-5 / Codex 族):仅匹配已知型号,避免未知 OpenAI 型号误计价。
|
||||
if normalized := normalizeKnownOpenAICodexModel(modelLower); normalized != "" {
|
||||
switch normalized {
|
||||
case "gpt-6-astra":
|
||||
return s.fallbackPrices["gpt-6-astra"]
|
||||
case "gpt-5.6-sol":
|
||||
return s.fallbackPrices["gpt-5.6-sol"]
|
||||
case "gpt-5.6-terra":
|
||||
@@ -1169,6 +1221,9 @@ func (s *BillingService) GetModelPricingWithChannel(model string, channelPricing
|
||||
applyChannelTokenPriceOverrides(pricing, channelPricing)
|
||||
pricing.FastMultiplier = channelPricing.FastMultiplier
|
||||
pricing.FlexMultiplier = channelPricing.FlexMultiplier
|
||||
if channelPricing.MaxReasoningEffortMultiplier != nil {
|
||||
pricing.MaxReasoningEffortMultiplier = channelPricing.MaxReasoningEffortMultiplier
|
||||
}
|
||||
if channelPricing.ImageOutputPrice != nil {
|
||||
pricing.ImageOutputPricePerToken = *channelPricing.ImageOutputPrice
|
||||
} else {
|
||||
@@ -1241,6 +1296,7 @@ type CostInput struct {
|
||||
RateMultiplier float64
|
||||
PricingAt time.Time // 渠道分时定价使用的计费时刻
|
||||
ServiceTier string // "priority","flex","" 等
|
||||
ReasoningEffort string // 最终转发的推理等级;max 可触发模型/渠道倍率
|
||||
Resolver *ModelPricingResolver // 定价解析器
|
||||
Resolved *ResolvedPricing // 可选:预解析的定价结果(避免重复 Resolve 调用)
|
||||
LongContextBillingEnabled *bool
|
||||
@@ -1255,7 +1311,7 @@ func (s *BillingService) CalculateCostUnified(input CostInput) (*CostBreakdown,
|
||||
if input.LongContextBillingEnabled != nil {
|
||||
applyLongContextBilling = *input.LongContextBillingEnabled
|
||||
}
|
||||
return s.calculateCostInternalWithPolicy(
|
||||
breakdown, err := s.calculateCostInternalWithPolicy(
|
||||
input.Model,
|
||||
input.Tokens,
|
||||
input.RateMultiplier,
|
||||
@@ -1263,6 +1319,10 @@ func (s *BillingService) CalculateCostUnified(input CostInput) (*CostBreakdown,
|
||||
nil,
|
||||
applyLongContextBilling,
|
||||
)
|
||||
if err == nil {
|
||||
applyCostBreakdownMultiplier(breakdown, maxReasoningEffortBillingMultiplier(input.Model, input.ReasoningEffort, nil))
|
||||
}
|
||||
return breakdown, err
|
||||
}
|
||||
|
||||
// 优先使用预解析结果,避免重复 Resolve 调用
|
||||
@@ -1346,6 +1406,7 @@ func (s *BillingService) calculateTokenCost(resolved *ResolvedPricing, input Cos
|
||||
|
||||
breakdown := s.computeTokenBreakdown(pricing, input.Tokens, input.RateMultiplier, input.ServiceTier, applyLongCtx)
|
||||
applyCostBreakdownMultiplier(breakdown, resolvedChannelTimeMultiplier(resolved, input.PricingAt))
|
||||
applyCostBreakdownMultiplier(breakdown, maxReasoningEffortBillingMultiplier(input.Model, input.ReasoningEffort, pricing))
|
||||
return breakdown, nil
|
||||
}
|
||||
|
||||
@@ -1627,13 +1688,17 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing
|
||||
}
|
||||
normalized := normalizeKnownOpenAICodexModel(model)
|
||||
isGPT56 := isOpenAIGPT56Model(normalized)
|
||||
needsMaxReasoningEffortMultiplier := isClaudeFable51Model(model) && pricing.MaxReasoningEffortMultiplier == nil
|
||||
needsCacheCreationPolicy := isGPT56 && !pricing.CacheCreationPriceExplicit && (pricing.CacheCreationPricePerToken <= 0 ||
|
||||
(pricing.InputPricePerTokenPriority > 0 && pricing.CacheCreationPricePerTokenPriority <= 0))
|
||||
fastRatio := openAIModelFastPricingRatio(normalized)
|
||||
if !needsCacheCreationPolicy && fastRatio <= 0 {
|
||||
if !needsCacheCreationPolicy && fastRatio <= 0 && !needsMaxReasoningEffortMultiplier {
|
||||
return pricing
|
||||
}
|
||||
cloned := *pricing
|
||||
if needsMaxReasoningEffortMultiplier {
|
||||
cloned.MaxReasoningEffortMultiplier = defaultMaxReasoningEffortMultiplier(model)
|
||||
}
|
||||
if isGPT56 && !cloned.CacheCreationPriceExplicit {
|
||||
if cloned.CacheCreationPricePerToken <= 0 {
|
||||
cloned.CacheCreationPricePerToken = cloned.InputPricePerToken * 1.25
|
||||
@@ -1648,16 +1713,19 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing
|
||||
return &cloned
|
||||
}
|
||||
|
||||
// openAIModelFastPricingRatio 返回业务口径下 OpenAI GPT-5.x 模型 Fast/priority
|
||||
// 的标准价倍率:gpt-5.6 系列与 gpt-5.4 为 2x,gpt-5.5 为 2.5x。未定义 Fast
|
||||
// openAIModelFastPricingRatio 返回业务口径下 OpenAI GPT 模型 Fast/priority
|
||||
// 的标准价倍率:gpt-5.6 / gpt-6-astra / gpt-5.4 为 2x,gpt-5.5 为 2.5x。未定义 Fast
|
||||
// 档的模型(如 gpt-5.5-pro、gpt-5.4-mini/nano)返回 0。
|
||||
func openAIModelFastPricingRatio(normalized string) float64 {
|
||||
switch normalized {
|
||||
case "gpt-5.4", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna":
|
||||
case "gpt-5.4", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-6-astra":
|
||||
return 2.0
|
||||
case "gpt-5.5":
|
||||
return 2.5
|
||||
default:
|
||||
if isOpenAIGPT6AstraModel(normalized) {
|
||||
return 2.0
|
||||
}
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1431,6 +1431,7 @@ func TestCalculateCost_LargeTokenCount(t *testing.T) {
|
||||
func TestServiceTierCostMultiplier(t *testing.T) {
|
||||
require.InDelta(t, 2.0, serviceTierCostMultiplier("priority"), 1e-12)
|
||||
require.InDelta(t, 2.0, serviceTierCostMultiplier(" Priority "), 1e-12)
|
||||
require.InDelta(t, 2.0, serviceTierCostMultiplier("ultrafast"), 1e-12)
|
||||
require.InDelta(t, 0.5, serviceTierCostMultiplier("flex"), 1e-12)
|
||||
require.InDelta(t, 1.0, serviceTierCostMultiplier(""), 1e-12)
|
||||
require.InDelta(t, 1.0, serviceTierCostMultiplier("default"), 1e-12)
|
||||
@@ -1770,6 +1771,8 @@ func TestGetModelPricing_Fable51FallbackPricing(t *testing.T) {
|
||||
require.InDelta(t, 12.5e-6, pricing.CacheCreation5mPrice, 1e-12)
|
||||
require.InDelta(t, 20e-6, pricing.CacheCreation1hPrice, 1e-12)
|
||||
require.InDelta(t, 0.25e-6, pricing.CacheReadPricePerToken, 1e-12)
|
||||
require.NotNil(t, pricing.MaxReasoningEffortMultiplier)
|
||||
require.Equal(t, 3.0, *pricing.MaxReasoningEffortMultiplier)
|
||||
}
|
||||
|
||||
func TestGetModelPricingWithChannel_CacheReadPriceAffectsPriority(t *testing.T) {
|
||||
|
||||
@@ -7,14 +7,15 @@ import (
|
||||
|
||||
// TokenCostRequest 通用网关 token 计费请求。
|
||||
type TokenCostRequest struct {
|
||||
Ctx context.Context
|
||||
Model string
|
||||
Group *Group
|
||||
Tokens UsageTokens
|
||||
RateMultiplier float64
|
||||
PricingAt time.Time
|
||||
ServiceTier string
|
||||
Resolver *ModelPricingResolver
|
||||
Ctx context.Context
|
||||
Model string
|
||||
Group *Group
|
||||
Tokens UsageTokens
|
||||
RateMultiplier float64
|
||||
PricingAt time.Time
|
||||
ServiceTier string
|
||||
ReasoningEffort string
|
||||
Resolver *ModelPricingResolver
|
||||
// Resolved 为调用方预先解析的定价(Resolver.Resolve 的结果),nil 表示未解析。
|
||||
Resolved *ResolvedPricing
|
||||
}
|
||||
@@ -33,21 +34,25 @@ func (s *BillingService) CalculateTokenCostForRequest(req TokenCostRequest) (*Co
|
||||
if req.Resolver != nil && req.Group != nil {
|
||||
return s.CalculateCostUnified(s.tokenCostInput(req, resolved))
|
||||
}
|
||||
if req.ReasoningEffort != "" {
|
||||
return s.CalculateCostUnified(s.tokenCostInput(req, resolved))
|
||||
}
|
||||
return s.CalculateCost(req.Model, req.Tokens, req.RateMultiplier)
|
||||
}
|
||||
|
||||
func (s *BillingService) tokenCostInput(req TokenCostRequest, resolved *ResolvedPricing) CostInput {
|
||||
input := CostInput{
|
||||
Ctx: req.Ctx,
|
||||
Model: req.Model,
|
||||
Group: req.Group,
|
||||
Tokens: req.Tokens,
|
||||
RequestCount: 1,
|
||||
RateMultiplier: req.RateMultiplier,
|
||||
PricingAt: req.PricingAt,
|
||||
ServiceTier: req.ServiceTier,
|
||||
Resolver: req.Resolver,
|
||||
Resolved: resolved,
|
||||
Ctx: req.Ctx,
|
||||
Model: req.Model,
|
||||
Group: req.Group,
|
||||
Tokens: req.Tokens,
|
||||
RequestCount: 1,
|
||||
RateMultiplier: req.RateMultiplier,
|
||||
PricingAt: req.PricingAt,
|
||||
ServiceTier: req.ServiceTier,
|
||||
ReasoningEffort: req.ReasoningEffort,
|
||||
Resolver: req.Resolver,
|
||||
Resolved: resolved,
|
||||
}
|
||||
if req.Group != nil {
|
||||
gid := req.Group.ID
|
||||
|
||||
@@ -216,3 +216,41 @@ func TestCalculateTokenCostForRequest_NoResolverFallsBackToCatalog(t *testing.T)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, want, got)
|
||||
}
|
||||
|
||||
func TestCalculateTokenCostForRequest_Fable51MaxEffortUsesDefaultMultiplier(t *testing.T) {
|
||||
bs := NewBillingService(&config.Config{}, nil)
|
||||
tokens := UsageTokens{InputTokens: 1000, OutputTokens: 10}
|
||||
standard, err := bs.CalculateTokenCostForRequest(TokenCostRequest{
|
||||
Model: "claude-fable-5-1", Tokens: tokens, RateMultiplier: 1, ReasoningEffort: "xhigh",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
max, err := bs.CalculateTokenCostForRequest(TokenCostRequest{
|
||||
Model: "claude-fable-5-1", Tokens: tokens, RateMultiplier: 1, ReasoningEffort: "max",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, standard.TotalCost*3, max.TotalCost, 1e-12)
|
||||
require.InDelta(t, standard.ActualCost*3, max.ActualCost, 1e-12)
|
||||
require.InDelta(t, standard.InputCost*3, max.InputCost, 1e-12)
|
||||
require.InDelta(t, standard.OutputCost*3, max.OutputCost, 1e-12)
|
||||
}
|
||||
|
||||
func TestCalculateTokenCostForRequest_ChannelOverridesFable51MaxEffortMultiplier(t *testing.T) {
|
||||
configured := 1.5
|
||||
bs, resolver := newTokenCostTestEnv(t, PlatformAnthropic, []ChannelModelPricing{{
|
||||
Platform: PlatformAnthropic, Models: []string{"claude-fable-5-1"}, BillingMode: BillingModeToken,
|
||||
InputPrice: testPtrFloat64(10e-6), OutputPrice: testPtrFloat64(50e-6),
|
||||
MaxReasoningEffortMultiplier: &configured,
|
||||
}}, nil)
|
||||
group := &Group{ID: 100, Platform: PlatformAnthropic}
|
||||
gid := group.ID
|
||||
resolved := resolver.Resolve(context.Background(), PricingInput{Model: "claude-fable-5-1", GroupID: &gid, Group: group})
|
||||
|
||||
got, err := bs.CalculateTokenCostForRequest(TokenCostRequest{
|
||||
Ctx: context.Background(), Model: "claude-fable-5-1", Group: group,
|
||||
Tokens: UsageTokens{InputTokens: 1000}, RateMultiplier: 1, ReasoningEffort: "max",
|
||||
Resolver: resolver, Resolved: resolved,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, 1000*10e-6*configured, got.TotalCost, 1e-12)
|
||||
require.InDelta(t, got.TotalCost, got.ActualCost, 1e-12)
|
||||
}
|
||||
@@ -87,25 +87,26 @@ type AccountStatsPricingRule struct {
|
||||
|
||||
// ChannelModelPricing 渠道模型定价条目
|
||||
type ChannelModelPricing struct {
|
||||
ID int64 `json:"id,omitempty"`
|
||||
ChannelID int64 `json:"channel_id,omitempty"`
|
||||
Platform string `json:"platform"` // 所属平台(anthropic/openai/gemini/...)
|
||||
Models []string `json:"models"`
|
||||
BillingMode BillingMode `json:"billing_mode"`
|
||||
InputPrice *float64 `json:"input_price"`
|
||||
OutputPrice *float64 `json:"output_price"`
|
||||
CacheWritePrice *float64 `json:"cache_write_price"`
|
||||
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
|
||||
CacheReadPrice *float64 `json:"cache_read_price"`
|
||||
FastMultiplier *float64 `json:"fast_multiplier"`
|
||||
FlexMultiplier *float64 `json:"flex_multiplier"`
|
||||
ImageInputPrice *float64 `json:"image_input_price"`
|
||||
ImageOutputPrice *float64 `json:"image_output_price"`
|
||||
PerRequestPrice *float64 `json:"per_request_price"`
|
||||
Intervals []PricingInterval `json:"intervals"`
|
||||
TimePricing *ChannelTimePricing `json:"time_pricing,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at,omitempty"`
|
||||
ID int64 `json:"id,omitempty"`
|
||||
ChannelID int64 `json:"channel_id,omitempty"`
|
||||
Platform string `json:"platform"` // 所属平台(anthropic/openai/gemini/...)
|
||||
Models []string `json:"models"`
|
||||
BillingMode BillingMode `json:"billing_mode"`
|
||||
InputPrice *float64 `json:"input_price"`
|
||||
OutputPrice *float64 `json:"output_price"`
|
||||
CacheWritePrice *float64 `json:"cache_write_price"`
|
||||
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
|
||||
CacheReadPrice *float64 `json:"cache_read_price"`
|
||||
FastMultiplier *float64 `json:"fast_multiplier"`
|
||||
FlexMultiplier *float64 `json:"flex_multiplier"`
|
||||
MaxReasoningEffortMultiplier *float64 `json:"max_reasoning_effort_multiplier"`
|
||||
ImageInputPrice *float64 `json:"image_input_price"`
|
||||
ImageOutputPrice *float64 `json:"image_output_price"`
|
||||
PerRequestPrice *float64 `json:"per_request_price"`
|
||||
Intervals []PricingInterval `json:"intervals"`
|
||||
TimePricing *ChannelTimePricing `json:"time_pricing,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
// ChannelTimePricing 渠道模型定价的分时倍率配置。
|
||||
|
||||
@@ -117,20 +117,16 @@ func (s *ChannelService) ListAvailable(ctx context.Context) ([]AvailableChannel,
|
||||
// 1. Pricing == nil(渠道完全没声明该模型的定价条目)
|
||||
// 2. Pricing 非 nil 但所有价格字段为空(admin UI 建了条目但没填价格)
|
||||
//
|
||||
// 当 pricingService 为 nil(测试场景),跳过回落。可用渠道与模型广场共用。
|
||||
// 当 pricingService 为 nil(测试场景),跳过价格回落,但仍补充内置模型倍率。
|
||||
// 可用渠道与模型广场共用。
|
||||
func fillGlobalPricingFallback(pricingService *PricingService, models []SupportedModel) {
|
||||
if pricingService == nil {
|
||||
return
|
||||
}
|
||||
for i := range models {
|
||||
if !pricingNeedsFallback(models[i].Pricing) {
|
||||
continue
|
||||
if pricingService != nil && pricingNeedsFallback(models[i].Pricing) {
|
||||
if lp := pricingService.GetModelPricing(models[i].Name); lp != nil {
|
||||
models[i].Pricing = synthesizePricingFromLiteLLM(lp, models[i].Pricing)
|
||||
}
|
||||
}
|
||||
lp := pricingService.GetModelPricing(models[i].Name)
|
||||
if lp == nil {
|
||||
continue
|
||||
}
|
||||
models[i].Pricing = synthesizePricingFromLiteLLM(lp, models[i].Pricing)
|
||||
models[i].Pricing = withDefaultMaxReasoningEffortMultiplier(models[i].Pricing, models[i].Name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,24 +176,33 @@ func synthesizePricingFromLiteLLM(lp *LiteLLMModelPricing, existing *ChannelMode
|
||||
|
||||
if mode == BillingModeImage || mode == BillingModePerRequest {
|
||||
return &ChannelModelPricing{
|
||||
BillingMode: mode,
|
||||
PerRequestPrice: nonZeroPtr(lp.OutputCostPerImage),
|
||||
ImageOutputPrice: nonZeroPtr(lp.OutputCostPerImageToken),
|
||||
InputPrice: nonZeroPtr(lp.InputCostPerToken),
|
||||
OutputPrice: nonZeroPtr(lp.OutputCostPerToken),
|
||||
BillingMode: mode,
|
||||
PerRequestPrice: nonZeroPtr(lp.OutputCostPerImage),
|
||||
ImageOutputPrice: nonZeroPtr(lp.OutputCostPerImageToken),
|
||||
InputPrice: nonZeroPtr(lp.InputCostPerToken),
|
||||
OutputPrice: nonZeroPtr(lp.OutputCostPerToken),
|
||||
MaxReasoningEffortMultiplier: maxReasoningEffortMultiplierFromPricing(existing),
|
||||
}
|
||||
}
|
||||
return &ChannelModelPricing{
|
||||
BillingMode: mode,
|
||||
InputPrice: nonZeroPtr(lp.InputCostPerToken),
|
||||
OutputPrice: nonZeroPtr(lp.OutputCostPerToken),
|
||||
CacheWritePrice: nonZeroPtr(lp.CacheCreationInputTokenCost),
|
||||
CacheWrite1hPrice: nonZeroPtr(lp.CacheCreationInputTokenCostAbove1hr),
|
||||
CacheReadPrice: nonZeroPtr(lp.CacheReadInputTokenCost),
|
||||
ImageOutputPrice: nonZeroPtr(lp.OutputCostPerImageToken),
|
||||
BillingMode: mode,
|
||||
InputPrice: nonZeroPtr(lp.InputCostPerToken),
|
||||
OutputPrice: nonZeroPtr(lp.OutputCostPerToken),
|
||||
CacheWritePrice: nonZeroPtr(lp.CacheCreationInputTokenCost),
|
||||
CacheWrite1hPrice: nonZeroPtr(lp.CacheCreationInputTokenCostAbove1hr),
|
||||
CacheReadPrice: nonZeroPtr(lp.CacheReadInputTokenCost),
|
||||
ImageOutputPrice: nonZeroPtr(lp.OutputCostPerImageToken),
|
||||
MaxReasoningEffortMultiplier: maxReasoningEffortMultiplierFromPricing(existing),
|
||||
}
|
||||
}
|
||||
|
||||
func maxReasoningEffortMultiplierFromPricing(pricing *ChannelModelPricing) *float64 {
|
||||
if pricing == nil {
|
||||
return nil
|
||||
}
|
||||
return pricing.MaxReasoningEffortMultiplier
|
||||
}
|
||||
|
||||
func nonZeroPtr(v float64) *float64 {
|
||||
if v == 0 {
|
||||
return nil
|
||||
|
||||
@@ -198,7 +198,7 @@ var providerAdapters = map[string]providerAdapter{
|
||||
buildBody: func(_, prompt string) ([]byte, error) {
|
||||
return json.Marshal(map[string]any{
|
||||
"contents": []map[string]any{
|
||||
{"parts": []map[string]any{{"text": prompt}}},
|
||||
{"role": "user", "parts": []map[string]any{{"text": prompt}}},
|
||||
},
|
||||
"generationConfig": map[string]any{"maxOutputTokens": monitorChallengeMaxTokens},
|
||||
})
|
||||
|
||||
@@ -498,3 +498,26 @@ func TestValidateChallenge_AnthropicTextAfterThinking(t *testing.T) {
|
||||
t.Fatalf("validateChallenge(%q, %q) = false, want true", respText, "2")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiMonitorBodyIncludesExplicitUserRole(t *testing.T) {
|
||||
adapter := providerAdapters[MonitorProviderGemini]
|
||||
body, err := adapter.buildBody("gemini-3.6-flash", "Reply with only 7.")
|
||||
if err != nil {
|
||||
t.Fatalf("buildBody() error = %v", err)
|
||||
}
|
||||
|
||||
var payload struct {
|
||||
Contents []struct {
|
||||
Role string `json:"role"`
|
||||
} `json:"contents"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatalf("Unmarshal() error = %v", err)
|
||||
}
|
||||
if len(payload.Contents) != 1 {
|
||||
t.Fatalf("contents length = %d, want 1", len(payload.Contents))
|
||||
}
|
||||
if payload.Contents[0].Role != "user" {
|
||||
t.Fatalf("contents[0].role = %q, want user", payload.Contents[0].Role)
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,8 @@ func TestConfiguredServiceTierMultiplier(t *testing.T) {
|
||||
{name: "priority alias", serviceTier: "priority", pricing: &ModelPricing{FastMultiplier: pricingMultiplier(2)}, want: 2},
|
||||
{name: "flex configured", serviceTier: "flex", pricing: &ModelPricing{FlexMultiplier: pricingMultiplier(0.4)}, want: 0.4},
|
||||
{name: "legacy fast default", serviceTier: "fast", pricing: &ModelPricing{}, want: 2},
|
||||
{name: "ultrafast default", serviceTier: "ultrafast", pricing: &ModelPricing{}, want: 2},
|
||||
{name: "ultrafast ignores fast multiplier", serviceTier: "ultrafast", pricing: &ModelPricing{FastMultiplier: pricingMultiplier(2.5)}, want: 2},
|
||||
{name: "legacy flex default", serviceTier: "flex", pricing: &ModelPricing{}, want: 0.5},
|
||||
}
|
||||
|
||||
|
||||
@@ -5,16 +5,30 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// ccVersionInBillingRe matches the semver part of cc_version (X.Y.Z), preserving
|
||||
// the trailing message-derived suffix (e.g. ".c02") if present.
|
||||
// ccVersionInBillingRe matches the semver part of cc_version (X.Y.Z).
|
||||
var ccVersionInBillingRe = regexp.MustCompile(`cc_version=\d+\.\d+\.\d+`)
|
||||
|
||||
var ccVersionWithFingerprintInBillingRe = regexp.MustCompile(`cc_version=\d+\.\d+\.\d+\.[0-9a-fA-F]{3}\b`)
|
||||
|
||||
// OAuth mimicry forces the built-in User-Agent after applying account fingerprints.
|
||||
func effectiveBillingUserAgent(tokenType string, mimicClaudeCode bool, fingerprint *Fingerprint) string {
|
||||
if tokenType == "oauth" && mimicClaudeCode {
|
||||
return claude.DefaultHeaders["User-Agent"]
|
||||
}
|
||||
if fingerprint == nil {
|
||||
return ""
|
||||
}
|
||||
return fingerprint.UserAgent
|
||||
}
|
||||
|
||||
// syncBillingHeaderVersion rewrites cc_version in x-anthropic-billing-header
|
||||
// system text blocks to match the version extracted from userAgent.
|
||||
// Recompute any recognized fingerprint suffix because its input includes the version.
|
||||
// Only touches system array blocks whose text starts with "x-anthropic-billing-header".
|
||||
func syncBillingHeaderVersion(body []byte, userAgent string) []byte {
|
||||
version := ExtractCLIVersion(userAgent)
|
||||
@@ -33,7 +47,9 @@ func syncBillingHeaderVersion(body []byte, userAgent string) []byte {
|
||||
text := item.Get("text")
|
||||
if text.Exists() && text.Type == gjson.String &&
|
||||
strings.HasPrefix(text.String(), "x-anthropic-billing-header") {
|
||||
newText := ccVersionInBillingRe.ReplaceAllString(text.String(), replacement)
|
||||
fingerprintedReplacement := replacement + "." + computeClaudeCodeFingerprint(body, version)
|
||||
newText := ccVersionWithFingerprintInBillingRe.ReplaceAllString(text.String(), fingerprintedReplacement)
|
||||
newText = ccVersionInBillingRe.ReplaceAllString(newText, replacement)
|
||||
if newText != text.String() {
|
||||
if updated, err := sjson.SetBytes(body, fmt.Sprintf("system.%d.text", idx), newText); err == nil {
|
||||
body = updated
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
func TestSyncBillingHeaderVersion(t *testing.T) {
|
||||
@@ -15,10 +26,10 @@ func TestSyncBillingHeaderVersion(t *testing.T) {
|
||||
unchanged bool // expect body to remain the same
|
||||
}{
|
||||
{
|
||||
name: "replaces cc_version preserving message-derived suffix",
|
||||
name: "replaces cc_version and recomputes message-derived suffix",
|
||||
body: `{"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.81.df2; cc_entrypoint=cli; cch=00000;"},{"type":"text","text":"You are Claude Code.","cache_control":{"type":"ephemeral"}}],"messages":[]}`,
|
||||
userAgent: "claude-cli/2.1.22 (external, cli)",
|
||||
wantSub: "cc_version=2.1.22.df2",
|
||||
wantSub: "cc_version=2.1.22." + computeClaudeCodeFingerprint([]byte(`{"messages":[]}`), "2.1.22"),
|
||||
},
|
||||
{
|
||||
name: "no billing header in system",
|
||||
@@ -65,3 +76,78 @@ func TestSyncBillingHeaderVersion(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncBillingHeaderVersion_RecomputesSuffixAndIsIdempotent(t *testing.T) {
|
||||
body := []byte(`{"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.81.df2; cc_entrypoint=cli;"}],"messages":[{"role":"user","content":"hello world"}]}`)
|
||||
version := "2.1.22"
|
||||
result := syncBillingHeaderVersion(body, "claude-cli/"+version)
|
||||
require.Contains(t, gjson.GetBytes(result, "system.0.text").String(),
|
||||
"cc_version="+version+"."+computeClaudeCodeFingerprint(body, version)+";")
|
||||
require.Equal(t, string(result), string(syncBillingHeaderVersion(result, "claude-cli/"+version)))
|
||||
require.JSONEq(t, gjson.GetBytes(body, "messages").Raw, gjson.GetBytes(result, "messages").Raw)
|
||||
}
|
||||
|
||||
func TestBuildOAuthRequest_BillingMatchesWireUserAgent(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, endpoint := range []string{"messages", "count_tokens"} {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
mimic bool
|
||||
identity bool
|
||||
disableFP bool
|
||||
}{
|
||||
{name: "mimic_overrides_cached_version", mimic: true, identity: true},
|
||||
{name: "mimic_without_identity", mimic: true},
|
||||
{name: "mimic_with_fingerprint_disabled", mimic: true, identity: true, disableFP: true},
|
||||
{name: "passthrough_uses_cached_version", identity: true},
|
||||
} {
|
||||
t.Run(endpoint+"/"+tc.name, func(t *testing.T) {
|
||||
resetGatewayForwardingSettingsCacheForTest(t)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
body := []byte(`{"model":"claude-haiku-4-5","system":[{"type":"text","text":""}],"messages":[{"role":"user","content":"hello world"}]}`)
|
||||
billing, err := buildBillingAttributionText(body, "2.1.81")
|
||||
require.NoError(t, err)
|
||||
body, err = sjson.SetBytes(body, "system.0.text", billing)
|
||||
require.NoError(t, err)
|
||||
|
||||
cfg := &config.Config{}
|
||||
svc := &GatewayService{cfg: cfg}
|
||||
cachedUA := "claude-cli/2.9.0 (external, cli)"
|
||||
if tc.identity {
|
||||
svc.identityService = NewIdentityService(&stubIdentityCache{fingerprint: &Fingerprint{
|
||||
UserAgent: cachedUA, ClientID: "test-client", UpdatedAt: time.Now().Unix(),
|
||||
}})
|
||||
}
|
||||
if tc.disableFP {
|
||||
svc.settingService = NewSettingService(&gatewayTTLSettingRepo{data: map[string]string{
|
||||
SettingKeyEnableFingerprintUnification: "false",
|
||||
}}, cfg)
|
||||
}
|
||||
account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeOAuth}
|
||||
var req *http.Request
|
||||
var wireBody []byte
|
||||
if endpoint == "messages" {
|
||||
req, wireBody, err = svc.buildUpstreamRequest(context.Background(), c, account,
|
||||
body, "test-token", "oauth", "claude-haiku-4-5", false, tc.mimic)
|
||||
} else {
|
||||
req, wireBody, err = svc.buildCountTokensRequest(context.Background(), c, account,
|
||||
body, "test-token", "oauth", "claude-haiku-4-5", tc.mimic)
|
||||
}
|
||||
require.NoError(t, err)
|
||||
defer func() { require.NoError(t, req.Body.Close()) }()
|
||||
wantUA := cachedUA
|
||||
if tc.mimic {
|
||||
wantUA = claude.DefaultHeaders["User-Agent"]
|
||||
}
|
||||
require.Equal(t, wantUA, getHeaderRaw(req.Header, "User-Agent"))
|
||||
version := ExtractCLIVersion(wantUA)
|
||||
require.Contains(t, gjson.GetBytes(wireBody, "system.0.text").String(),
|
||||
"cc_version="+version+"."+computeClaudeCodeFingerprint(wireBody, version)+";")
|
||||
actualBody, err := io.ReadAll(req.Body)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, wireBody, actualBody)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -770,14 +770,14 @@ func expandClaudeOAuthSystemPromptTextTemplate(body []byte, text string, expansi
|
||||
return "", nil
|
||||
}
|
||||
expansionPrompt = defaultClaudeOAuthExpansionPrompt(expansionPrompt)
|
||||
billingText, err := buildBillingAttributionText(body, claude.CLICurrentVersion)
|
||||
billingText, err := buildBillingAttributionText(body, claude.CLIVersion())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
fp := computeClaudeCodeFingerprint(body, claude.CLICurrentVersion)
|
||||
fp := computeClaudeCodeFingerprint(body, claude.CLIVersion())
|
||||
replacer := strings.NewReplacer(
|
||||
"{billing_header}", billingText,
|
||||
"{cc_version}", claude.CLICurrentVersion,
|
||||
"{cc_version}", claude.CLIVersion(),
|
||||
"{fp}", fp,
|
||||
"{claude_code_system_prompt}", claudeCodeSystemPrompt,
|
||||
"{claude_code_expansion_prompt}", expansionPrompt,
|
||||
|
||||
@@ -485,9 +485,13 @@ func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Con
|
||||
}
|
||||
}
|
||||
|
||||
// 同步 billing header cc_version 与实际发送的 User-Agent 版本
|
||||
if ctFingerprint != nil && ctEnableFP {
|
||||
body = syncBillingHeaderVersion(body, ctFingerprint.UserAgent)
|
||||
// Disabled fingerprint unification does not disable forced mimicry headers.
|
||||
var billingFingerprint *Fingerprint
|
||||
if ctEnableFP {
|
||||
billingFingerprint = ctFingerprint
|
||||
}
|
||||
if billingUA := effectiveBillingUserAgent(tokenType, mimicClaudeCode, billingFingerprint); billingUA != "" {
|
||||
body = syncBillingHeaderVersion(body, billingUA)
|
||||
}
|
||||
|
||||
// === 计算最终 anthropic-beta header(先于 body sanitize 与 CCH 签名)===
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
|
||||
@@ -157,5 +158,8 @@ func injectCacheControlOnLastContentBlock(body []byte, idx int, msg *gjson.Resul
|
||||
// mustJSONString 把一个 Go string 序列化为合法 JSON string(含引号),
|
||||
// 用于 sjson.SetRawBytes 场景下手工拼 JSON。
|
||||
func mustJSONString(s string) string {
|
||||
return fmt.Sprintf("%q", s)
|
||||
// Go string quoting can emit non-JSON escapes such as \x7f or \a.
|
||||
// Marshaling a string cannot fail.
|
||||
encoded, _ := json.Marshal(s)
|
||||
return string(encoded)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestAddMessageCacheBreakpoints_JSONStringEscaping(t *testing.T) {
|
||||
var controls strings.Builder
|
||||
for r := rune(0); r <= 0x9f; r++ {
|
||||
controls.WriteRune(r)
|
||||
}
|
||||
tests := []struct{ name, text string }{
|
||||
{"delete_character", "before\x7fafter"},
|
||||
{"bell_and_vertical_tab", "before\a\vafter"},
|
||||
{"nul_and_escape", "before\x00\x1bafter"},
|
||||
{"all_ascii_and_c1_controls", controls.String()},
|
||||
{"supplementary_nonprinting_rune", "before\U000e0067after"},
|
||||
{"unicode_and_json_metacharacters", "中文 😀 <>& \"quote\" \\slash\n\r\t\b\f"},
|
||||
{"literal_backslash_sequences", `literal \x7f \a \v \U000e0067`},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Both the final message and the second-to-last user turn are promoted
|
||||
// from strings to text blocks by the cache rewrite.
|
||||
body, err := json.Marshal(map[string]any{
|
||||
"messages": []map[string]any{
|
||||
{"role": "user", "content": tt.text},
|
||||
{"role": "assistant", "content": "ack"},
|
||||
{"role": "user", "content": "next"},
|
||||
{"role": "assistant", "content": tt.text},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
out := addMessageCacheBreakpoints(body)
|
||||
// gjson accepts some malformed input, so validate with encoding/json
|
||||
// before inspecting the rewritten content and cache metadata.
|
||||
var decoded any
|
||||
require.NoError(t, json.Unmarshal(out, &decoded))
|
||||
for _, path := range []string{"messages.0.content", "messages.3.content"} {
|
||||
content := gjson.GetBytes(out, path)
|
||||
require.True(t, content.IsArray())
|
||||
require.Len(t, content.Array(), 1)
|
||||
block := content.Array()[0]
|
||||
require.Equal(t, "text", block.Get("type").String())
|
||||
require.Equal(t, tt.text, block.Get("text").String())
|
||||
require.Equal(t, "ephemeral", block.Get("cache_control.type").String())
|
||||
require.Equal(t, "5m", block.Get("cache_control.ttl").String())
|
||||
}
|
||||
require.JSONEq(t, string(out), string(addMessageCacheBreakpoints(out)))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3515,3 +3515,74 @@ func TestGatewayService_ResolveGatewayGroup_DetectsFallbackCycle(t *testing.T) {
|
||||
require.Nil(t, gotID)
|
||||
require.Contains(t, err.Error(), "fallback group cycle")
|
||||
}
|
||||
|
||||
func TestModelRoutingAppliesToPlatform(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
targetPlatform string
|
||||
groupPlatform string
|
||||
want bool
|
||||
}{
|
||||
{"anthropic group", PlatformAnthropic, PlatformAnthropic, true},
|
||||
{"openai group", PlatformOpenAI, PlatformOpenAI, true},
|
||||
{"composite group resolved to anthropic", PlatformAnthropic, PlatformComposite, true},
|
||||
{"composite group resolved to openai", PlatformOpenAI, PlatformComposite, true},
|
||||
{"target platform outside the allowed set", PlatformGemini, PlatformGemini, false},
|
||||
{"composite group resolved outside the allowed set", PlatformGemini, PlatformComposite, false},
|
||||
{"group platform does not match target", PlatformOpenAI, PlatformAnthropic, false},
|
||||
{"empty target platform", "", PlatformOpenAI, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.Equal(t, tc.want, modelRoutingAppliesToPlatform(tc.targetPlatform, tc.groupPlatform))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Model routing used to be read only for requests resolved to Anthropic, so an
|
||||
// OpenAI group's rules were stored and displayed but never honored. Routing an
|
||||
// OpenAI request must pick the routed account instead of the group-wide winner.
|
||||
func TestGatewayService_SelectAccountForModelWithPlatform_RoutedOpenAIGroup(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
groupID := int64(13)
|
||||
requestedModel := "gpt-6-astra"
|
||||
|
||||
repo := &mockAccountRepoForPlatform{
|
||||
accounts: []Account{
|
||||
// Priority 1 would win any group-wide selection, but it is not routed.
|
||||
{ID: 1, Platform: PlatformOpenAI, Priority: 1, Status: StatusActive, Schedulable: true},
|
||||
{ID: 2, Platform: PlatformOpenAI, Priority: 5, Status: StatusActive, Schedulable: true},
|
||||
},
|
||||
accountsByID: map[int64]*Account{},
|
||||
}
|
||||
for i := range repo.accounts {
|
||||
repo.accountsByID[repo.accounts[i].ID] = &repo.accounts[i]
|
||||
}
|
||||
|
||||
groupRepo := &mockGroupRepoForGateway{
|
||||
groups: map[int64]*Group{
|
||||
groupID: {
|
||||
ID: groupID,
|
||||
Name: "openai-route-group",
|
||||
Platform: PlatformOpenAI,
|
||||
Status: StatusActive,
|
||||
Hydrated: true,
|
||||
ModelRoutingEnabled: true,
|
||||
ModelRouting: map[string][]int64{
|
||||
requestedModel: {2},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
svc := &GatewayService{
|
||||
accountRepo: repo,
|
||||
cache: &mockGatewayCacheForPlatform{},
|
||||
cfg: testConfig(),
|
||||
groupRepo: groupRepo,
|
||||
}
|
||||
|
||||
acc, err := svc.selectAccountForModelWithPlatform(ctx, &groupID, "", requestedModel, nil, PlatformOpenAI)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, acc)
|
||||
require.Equal(t, int64(2), acc.ID, "routed account must win over the higher-priority unrouted one")
|
||||
}
|
||||
@@ -1388,6 +1388,9 @@ func NormalizeGLMOpenAIReasoningEffort(body []byte, mappedModel string) ([]byte,
|
||||
}
|
||||
|
||||
mapped := normalizeGLMOpenAIReasoningEffort(raw)
|
||||
if isGLM53Model(mappedModel) && mapped == "high" && normalizeEffortToken(raw) == "low" {
|
||||
mapped = "low"
|
||||
}
|
||||
if mapped == "" || mapped == raw {
|
||||
return body, false
|
||||
}
|
||||
@@ -1399,12 +1402,20 @@ func NormalizeGLMOpenAIReasoningEffort(body []byte, mappedModel string) ([]byte,
|
||||
return modified, true
|
||||
}
|
||||
|
||||
func normalizeGLMOpenAIReasoningEffort(raw string) string {
|
||||
func normalizeEffortToken(raw string) string {
|
||||
value := strings.ToLower(strings.TrimSpace(raw))
|
||||
return strings.NewReplacer("-", "", "_", "", " ", "").Replace(value)
|
||||
}
|
||||
|
||||
func isGLM53Model(model string) bool {
|
||||
return strings.EqualFold(strings.TrimSpace(model), "glm-5.3")
|
||||
}
|
||||
|
||||
func normalizeGLMOpenAIReasoningEffort(raw string) string {
|
||||
value := normalizeEffortToken(raw)
|
||||
if value == "" {
|
||||
return ""
|
||||
}
|
||||
value = strings.NewReplacer("-", "", "_", "", " ", "").Replace(value)
|
||||
|
||||
switch value {
|
||||
case "low", "medium", "high":
|
||||
@@ -1416,6 +1427,42 @@ func normalizeGLMOpenAIReasoningEffort(raw string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// NormalizeGLM53AnthropicThinking maps explicit client thinking effort onto the
|
||||
// GLM-5.3 Anthropic-compatible scale. Requests without an effort or thinking
|
||||
// preference are left unchanged so the upstream default remains in effect.
|
||||
func NormalizeGLM53AnthropicThinking(body []byte, mappedModel string) ([]byte, bool) {
|
||||
if !isGLM53Model(mappedModel) {
|
||||
return body, false
|
||||
}
|
||||
|
||||
raw := gjson.GetBytes(body, "output_config.effort").String()
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
raw = gjson.GetBytes(body, "thinking.type").String()
|
||||
}
|
||||
|
||||
var effort string
|
||||
switch normalizeEffortToken(raw) {
|
||||
case "disabled", "off", "none", "minimal", "low":
|
||||
effort = "low"
|
||||
case "enabled", "adaptive", "medium", "high":
|
||||
effort = "high"
|
||||
case "xhigh", "max", "ultra":
|
||||
effort = "max"
|
||||
default:
|
||||
return body, false
|
||||
}
|
||||
|
||||
modified, err := sjson.SetBytes(body, "thinking.type", "enabled")
|
||||
if err != nil {
|
||||
return body, false
|
||||
}
|
||||
modified, err = sjson.SetBytes(modified, "output_config.effort", effort)
|
||||
if err != nil {
|
||||
return body, false
|
||||
}
|
||||
return modified, true
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Thinking Budget Rectifier
|
||||
// =========================
|
||||
|
||||
@@ -1605,6 +1605,14 @@ func TestNormalizeGLMOpenAIReasoningEffort(t *testing.T) {
|
||||
wantPath: "reasoning_effort",
|
||||
wantValue: "high",
|
||||
},
|
||||
{
|
||||
name: "glm 5.2 low maps to high",
|
||||
model: "glm-5.2",
|
||||
input: `{"model":"glm-5.2","reasoning_effort":"low","messages":[]}`,
|
||||
wantApplied: true,
|
||||
wantPath: "reasoning_effort",
|
||||
wantValue: "high",
|
||||
},
|
||||
{
|
||||
name: "nested high case-normalizes",
|
||||
model: "glm-5.2",
|
||||
@@ -1613,6 +1621,13 @@ func TestNormalizeGLMOpenAIReasoningEffort(t *testing.T) {
|
||||
wantPath: "reasoning.effort",
|
||||
wantValue: "high",
|
||||
},
|
||||
{
|
||||
name: "glm 5.3 native low unchanged",
|
||||
model: "glm-5.3",
|
||||
input: `{"model":"glm-5.3","reasoning_effort":"low","messages":[]}`,
|
||||
wantApplied: false,
|
||||
wantUnchanged: true,
|
||||
},
|
||||
{
|
||||
name: "native max unchanged",
|
||||
model: "glm-5.2",
|
||||
|
||||
@@ -216,7 +216,7 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro
|
||||
return nil, err
|
||||
}
|
||||
preferOAuth := platform == PlatformGemini
|
||||
if s.debugModelRoutingEnabled() && platform == PlatformAnthropic && requestedModel != "" {
|
||||
if s.debugModelRoutingEnabled() && requestedModel != "" && modelRoutingAppliesToTargetPlatform(platform) {
|
||||
logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] load-aware enabled: group_id=%v model=%s session=%s platform=%s", derefGroupID(groupID), requestedModel, shortSessionHash(sessionHash), platform)
|
||||
}
|
||||
|
||||
@@ -250,10 +250,10 @@ func (s *GatewayService) SelectAccountWithLoadAwareness(ctx context.Context, gro
|
||||
return needsUpstreamCheck && s.isUpstreamModelRestrictedByChannel(ctx, *groupID, account, requestedModel)
|
||||
}
|
||||
|
||||
// 获取模型路由配置(anthropic 目标平台;composite 分组按目标平台判断)
|
||||
// 获取模型路由配置(anthropic / openai 目标平台;composite 分组按目标平台判断)
|
||||
var routingAccountIDs []int64
|
||||
if group != nil && requestedModel != "" && platform == PlatformAnthropic &&
|
||||
(group.Platform == PlatformAnthropic || group.Platform == PlatformComposite) {
|
||||
if group != nil && requestedModel != "" &&
|
||||
modelRoutingAppliesToPlatform(platform, group.Platform) {
|
||||
routingAccountIDs = group.GetRoutingAccountIDs(requestedModel)
|
||||
if s.debugModelRoutingEnabled() {
|
||||
logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] context group routing: group_id=%d model=%s enabled=%v rules=%d matched_ids=%v session=%s sticky_account=%d",
|
||||
@@ -865,8 +865,35 @@ func (s *GatewayService) ResolveGroupByID(ctx context.Context, groupID int64) (*
|
||||
return s.resolveGroupByID(ctx, groupID)
|
||||
}
|
||||
|
||||
// modelRoutingAppliesToPlatform 判定模型路由规则是否适用于本次请求。
|
||||
//
|
||||
// 路由规则的存储与查表(Group.ModelRouting / GetRoutingAccountIDs)本身与平台无关,
|
||||
// 早期只有 Anthropic 目标平台会读取它。OpenAI 分组同样存在“同一个公开别名由不同账号
|
||||
// 映射到不同上游模型”的故障转移写法,需要显式路由来指定谁是主、谁是备,因此这里把
|
||||
// Anthropic 与 OpenAI 一并放行。
|
||||
//
|
||||
// targetPlatform 是请求解析后的目标平台;groupPlatform 是分组自身的平台。composite
|
||||
// 分组不限定自身平台,只要目标平台落在放行集合内即可复用其规则。
|
||||
func modelRoutingAppliesToPlatform(targetPlatform, groupPlatform string) bool {
|
||||
if !modelRoutingAppliesToTargetPlatform(targetPlatform) {
|
||||
return false
|
||||
}
|
||||
return groupPlatform == targetPlatform || groupPlatform == PlatformComposite
|
||||
}
|
||||
|
||||
// modelRoutingAppliesToTargetPlatform 是放行平台集合的唯一定义处:新增平台只改这里。
|
||||
// 在只知道目标平台、还没取到分组的位置(调试日志、取分组前的短路)单独判定用。
|
||||
func modelRoutingAppliesToTargetPlatform(targetPlatform string) bool {
|
||||
switch targetPlatform {
|
||||
case PlatformAnthropic, PlatformOpenAI:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *GatewayService) routingAccountIDsForRequest(ctx context.Context, groupID *int64, requestedModel string, platform string) []int64 {
|
||||
if groupID == nil || requestedModel == "" || platform != PlatformAnthropic {
|
||||
if groupID == nil || requestedModel == "" || !modelRoutingAppliesToTargetPlatform(platform) {
|
||||
return nil
|
||||
}
|
||||
group, err := s.resolveGroupByID(ctx, *groupID)
|
||||
@@ -876,11 +903,11 @@ func (s *GatewayService) routingAccountIDsForRequest(ctx context.Context, groupI
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Model routing applies only to requests resolved to Anthropic. Composite
|
||||
// groups may still use those rules once their model resolved to Anthropic.
|
||||
if group.Platform != PlatformAnthropic && group.Platform != PlatformComposite {
|
||||
// 路由规则适用于解析到 Anthropic 或 OpenAI 的请求;composite 分组在其模型解析到
|
||||
// 上述平台后同样可以复用这些规则。
|
||||
if !modelRoutingAppliesToPlatform(platform, group.Platform) {
|
||||
if s.debugModelRoutingEnabled() {
|
||||
logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] skip: non-anthropic group platform: group_id=%d group_platform=%s model=%s", group.ID, group.Platform, requestedModel)
|
||||
logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] skip: group platform not eligible: group_id=%d group_platform=%s target_platform=%s model=%s", group.ID, group.Platform, platform, requestedModel)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1462,6 +1489,28 @@ func (s *GatewayService) checkAndRegisterSession(ctx context.Context, account *A
|
||||
return allowed
|
||||
}
|
||||
|
||||
// ReleaseAccountSession 立即释放会话槽(不等待空闲超时)
|
||||
// 供 handler 在请求最终失败(选号成功但转发失败/客户端中断)时调用:
|
||||
// 上游从未真正服务该会话,若继续占槽,max_sessions 受限的账号会被失败请求的
|
||||
// session hash 卡满整个空闲窗口,后续新会话全部被拒。
|
||||
// 适用条件与 checkAndRegisterSession 对齐;不适用账号为 no-op,幂等可安全重复调用。
|
||||
func (s *GatewayService) ReleaseAccountSession(ctx context.Context, account *Account, sessionID string) {
|
||||
if s == nil || s.sessionLimitCache == nil || account == nil || sessionID == "" {
|
||||
return
|
||||
}
|
||||
if !account.IsAnthropicOAuthOrSetupToken() {
|
||||
return
|
||||
}
|
||||
if account.GetMaxSessions() <= 0 {
|
||||
return
|
||||
}
|
||||
if err := s.sessionLimitCache.UnregisterSession(ctx, account.ID, sessionID); err != nil {
|
||||
slog.Debug("session_limit.release_failed",
|
||||
"account_id", account.ID,
|
||||
"error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *GatewayService) getSchedulableAccount(ctx context.Context, accountID int64) (*Account, error) {
|
||||
var (
|
||||
account *Account
|
||||
|
||||
@@ -84,9 +84,9 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex
|
||||
}
|
||||
}
|
||||
|
||||
// 同步 billing header cc_version 与实际发送的 User-Agent 版本
|
||||
if fingerprint != nil {
|
||||
body = syncBillingHeaderVersion(body, fingerprint.UserAgent)
|
||||
// Mimicry may override the cached User-Agent later, even without a fingerprint.
|
||||
if billingUA := effectiveBillingUserAgent(tokenType, mimicClaudeCode, fingerprint); billingUA != "" {
|
||||
body = syncBillingHeaderVersion(body, billingUA)
|
||||
}
|
||||
|
||||
// === 计算最终 anthropic-beta header(先于 body sanitize 与 CCH 签名)===
|
||||
|
||||
@@ -285,6 +285,12 @@ func ExtractUpstreamErrorMessage(body []byte) string {
|
||||
return extractUpstreamErrorMessage(body)
|
||||
}
|
||||
|
||||
// SanitizeUpstreamErrorMessage redacts sensitive query parameter values before
|
||||
// an upstream error message is recorded or returned to a client.
|
||||
func SanitizeUpstreamErrorMessage(message string) string {
|
||||
return sanitizeUpstreamErrorMessage(message)
|
||||
}
|
||||
|
||||
func extractUpstreamErrorMessage(body []byte) string {
|
||||
// Claude 风格:{"type":"error","error":{"type":"...","message":"..."}}
|
||||
if m := gjson.GetBytes(body, "error.message").String(); strings.TrimSpace(m) != "" {
|
||||
|
||||
@@ -1092,15 +1092,16 @@ func (s *GatewayService) calculateTokenCost(
|
||||
}
|
||||
|
||||
cost, err := s.billingService.CalculateTokenCostForRequest(TokenCostRequest{
|
||||
Ctx: ctx,
|
||||
Model: billingModel,
|
||||
Group: apiKey.Group,
|
||||
Tokens: tokens,
|
||||
RateMultiplier: multiplier,
|
||||
PricingAt: pricingAt,
|
||||
ServiceTier: optionalStringValue(result.ServiceTier),
|
||||
Resolver: s.resolver,
|
||||
Resolved: resolved,
|
||||
Ctx: ctx,
|
||||
Model: billingModel,
|
||||
Group: apiKey.Group,
|
||||
Tokens: tokens,
|
||||
RateMultiplier: multiplier,
|
||||
PricingAt: pricingAt,
|
||||
ServiceTier: optionalStringValue(result.ServiceTier),
|
||||
ReasoningEffort: optionalStringValue(result.ReasoningEffort),
|
||||
Resolver: s.resolver,
|
||||
Resolved: resolved,
|
||||
})
|
||||
if err != nil {
|
||||
logger.LegacyPrintf("service.gateway", "Calculate cost failed: %v", err)
|
||||
|
||||
@@ -107,7 +107,7 @@ type Group struct {
|
||||
DefaultMappedModel string
|
||||
MessagesDispatchModelConfig OpenAIMessagesDispatchModelConfig
|
||||
ModelAllowlist GroupModelAllowlist
|
||||
// CodexModelsManifestConfig 开启后,该分组的 Codex /models manifest 请求只用
|
||||
// CodexModelsManifestConfig 开启后,普通模型列表与 Codex manifest 优先使用
|
||||
// 固定账号列表拉取并合并,不经过调度器(仅 openai 平台)。
|
||||
CodexModelsManifestConfig GroupCodexModelsManifestConfig
|
||||
|
||||
@@ -115,7 +115,7 @@ type Group struct {
|
||||
// 一旦设置即接管该分组用户的限流(覆盖用户级 rpm_limit),可被 user-group rpm_override 进一步覆盖。
|
||||
RPMLimit int
|
||||
|
||||
// MaxReasoningEffort limits the effective OpenAI/Codex reasoning effort.
|
||||
// MaxReasoningEffort limits the effective Anthropic/OpenAI reasoning effort.
|
||||
// Empty means unlimited; supported values are minimal/low/medium/high/xhigh/max.
|
||||
MaxReasoningEffort string
|
||||
// MaxReasoningEffortOverLimit is the access control when an explicit effort
|
||||
@@ -141,6 +141,12 @@ type Group struct {
|
||||
RateLimitedAccountCount int64
|
||||
}
|
||||
|
||||
// IsGroupBindableInSimpleMode is the shared policy for groups that may be
|
||||
// surfaced and bound to accounts while running in simple mode.
|
||||
func IsGroupBindableInSimpleMode(group *Group) bool {
|
||||
return group != nil && group.Platform != PlatformComposite
|
||||
}
|
||||
|
||||
func (g *Group) IsActive() bool {
|
||||
return g.Status == StatusActive
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
var (
|
||||
ErrGroupNotFound = infraerrors.NotFound("GROUP_NOT_FOUND", "group not found")
|
||||
ErrGroupExists = infraerrors.Conflict("GROUP_EXISTS", "group name already exists")
|
||||
ErrGroupNotEmpty = infraerrors.Conflict("GROUP_NOT_EMPTY", "group contains accounts")
|
||||
)
|
||||
|
||||
type GroupRepository interface {
|
||||
@@ -51,6 +52,12 @@ type GroupDuplicateRepository interface {
|
||||
type AdminGroupRepository interface {
|
||||
GroupRepository
|
||||
GroupDuplicateRepository
|
||||
EmptyGroupDeleteRepository
|
||||
}
|
||||
|
||||
// EmptyGroupDeleteRepository provides the guarded cascade used by simple mode.
|
||||
type EmptyGroupDeleteRepository interface {
|
||||
DeleteCascadeIfEmpty(ctx context.Context, id int64) ([]int64, error)
|
||||
}
|
||||
|
||||
// GroupSortOrderUpdate 分组排序更新
|
||||
|
||||
@@ -14,6 +14,7 @@ const (
|
||||
|
||||
type httpUpstreamProfileContextKey struct{}
|
||||
type httpUpstreamDisableRedirectsContextKey struct{}
|
||||
type httpUpstreamPublicHostsOnlyContextKey struct{}
|
||||
|
||||
// WithHTTPUpstreamProfile injects an upstream transport profile into ctx.
|
||||
func WithHTTPUpstreamProfile(ctx context.Context, profile HTTPUpstreamProfile) context.Context {
|
||||
@@ -55,3 +56,18 @@ func WithHTTPUpstreamRedirectsDisabled(ctx context.Context) context.Context {
|
||||
func HTTPUpstreamRedirectsDisabled(ctx context.Context) bool {
|
||||
return ctx != nil && ctx.Value(httpUpstreamDisableRedirectsContextKey{}) == true
|
||||
}
|
||||
|
||||
// WithHTTPUpstreamPublicHostsOnly marks a request whose destination, and every
|
||||
// redirect hop after it, must resolve to a public address. The shared upstream
|
||||
// client enforces it regardless of the security.url_allowlist configuration;
|
||||
// use it for fetches whose URL comes from an untrusted upstream response.
|
||||
func WithHTTPUpstreamPublicHostsOnly(ctx context.Context) context.Context {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
return context.WithValue(ctx, httpUpstreamPublicHostsOnlyContextKey{}, true)
|
||||
}
|
||||
|
||||
func HTTPUpstreamPublicHostsOnly(ctx context.Context) bool {
|
||||
return ctx != nil && ctx.Value(httpUpstreamPublicHostsOnlyContextKey{}) == true
|
||||
}
|
||||
@@ -30,3 +30,17 @@ func TestWithHTTPUpstreamRedirectsDisabled(t *testing.T) {
|
||||
t.Fatal("redirects should remain enabled by default")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithHTTPUpstreamPublicHostsOnly(t *testing.T) {
|
||||
//nolint:staticcheck // Exercises the defensive nil-context fallback.
|
||||
ctx := WithHTTPUpstreamPublicHostsOnly(nil)
|
||||
if !HTTPUpstreamPublicHostsOnly(ctx) {
|
||||
t.Fatal("expected public-hosts-only marker to be set")
|
||||
}
|
||||
if HTTPUpstreamPublicHostsOnly(context.Background()) {
|
||||
t.Fatal("marker must be absent by default")
|
||||
}
|
||||
if HTTPUpstreamRedirectsDisabled(ctx) {
|
||||
t.Fatal("public-hosts-only must not disable redirects")
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,10 @@ var (
|
||||
// <product>/<major>.<minor>.<patch> 之后必须紧跟空白或字符串结束。
|
||||
// 版本号带 -local / -dev / +build 等后缀的本地构建一律不接受。
|
||||
fingerprintUserAgentPattern = regexp.MustCompile(`^[A-Za-z0-9._-]+/\d+\.\d+\.\d+(\s|$)`)
|
||||
|
||||
// claudeCLIUAVersionPrefixRegex 匹配 claude-cli UA 开头的 "claude-cli/x.y.z" 版本号段,
|
||||
// 供版本下限抬升时就地替换版本号使用;UA 其余部分(括号内的真实客户端形态等)原样保留。
|
||||
claudeCLIUAVersionPrefixRegex = regexp.MustCompile(`(?i)^(claude-cli)/\d+\.\d+\.\d+`)
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -36,7 +40,7 @@ const (
|
||||
// maxFingerprintUserAgentLength 限制写入缓存的 User-Agent 长度。
|
||||
maxFingerprintUserAgentLength = 256
|
||||
// maxClaudeCLIMajorVersionSkew 是 claude-cli 主版本号相对 sub2api 自身伪装
|
||||
// 版本(claude.CLICurrentVersion)允许的最大超前量。给足两个大版本的升级
|
||||
// 版本(claude.CLIVersion())允许的最大超前量。给足两个大版本的升级
|
||||
// 窗口,同时挡掉 999 这类哨兵版本号。
|
||||
maxClaudeCLIMajorVersionSkew = 2
|
||||
)
|
||||
@@ -68,16 +72,48 @@ func isAcceptableFingerprintUserAgent(ua string) bool {
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
currentMajor, _, _, currentOK := parseUserAgentVersion(claudeCLIUserAgentProduct + "/" + claude.CLICurrentVersion)
|
||||
currentMajor, _, _, currentOK := parseUserAgentVersion(claudeCLIUserAgentProduct + "/" + claude.CLIVersion())
|
||||
if !currentOK {
|
||||
return true
|
||||
}
|
||||
return major <= currentMajor+maxClaudeCLIMajorVersionSkew
|
||||
}
|
||||
|
||||
// floorClaudeCLIUserAgentVersion 把 claude-cli UA 中的版本号抬升到 claude.CLICurrentVersion
|
||||
// 下限:低于下限时就地升到下限并返回 changed=true,否则原样返回。
|
||||
//
|
||||
// 为什么需要这条:账号级指纹"只升不降"、活跃账号懒续期后近乎永不过期,且系统内没有重置
|
||||
// 入口,defaultFingerprint 只在首次创建指纹时使用。存量账号缓存里的 claude-cli 版本停留在
|
||||
// 历史值(如 claude-cli/2.1.220),客户端送来更旧的版本时 isNewerVersion 不会触发升级——
|
||||
// 仅升 CLICurrentVersion 常量对所有已有账号完全无效,上游按指纹 UA 做客户端版本闸门
|
||||
// (如 Fable 5.1 要求 >= 2.1.251)时旧指纹永远过不去。
|
||||
//
|
||||
// 约束:
|
||||
// - 只对 claude-cli 产品生效,其它产品一律不动,避免误伤别的合法客户端;
|
||||
// - 只升不降:版本等于或高于 CLICurrentVersion(含客户端上报的更新版本)时不做任何改动;
|
||||
// - 只替换 claude-cli/ 后的版本号段,UA 其余部分(如 "(external, claude-desktop-3p,
|
||||
// agent-sdk/0.3.100)")原样保留,不重建整个字符串、不退化为 defaultFingerprint.UserAgent;
|
||||
// - X-Stainless-* 字段不在此处理,维持调用方的既有 merge 语义。
|
||||
func floorClaudeCLIUserAgentVersion(ua string) (string, bool) {
|
||||
if extractProduct(ua) != claudeCLIUserAgentProduct {
|
||||
return ua, false
|
||||
}
|
||||
floorUA := claudeCLIUserAgentProduct + "/" + claude.CLICurrentVersion
|
||||
// isNewerVersion(floor, ua) 为 true 当且仅当下限版本严格高于 ua:
|
||||
// ua 等于或高于下限、产品名不一致、或版本无法解析时都不做改动。
|
||||
if !isNewerVersion(floorUA, ua) {
|
||||
return ua, false
|
||||
}
|
||||
floored := claudeCLIUAVersionPrefixRegex.ReplaceAllString(ua, "${1}/"+claude.CLICurrentVersion)
|
||||
if floored == ua {
|
||||
return ua, false
|
||||
}
|
||||
return floored, true
|
||||
}
|
||||
|
||||
// 默认指纹值(当客户端未提供时使用)
|
||||
var defaultFingerprint = Fingerprint{
|
||||
UserAgent: "claude-cli/" + claude.CLICurrentVersion + " (external, cli)",
|
||||
UserAgent: "claude-cli/" + claude.CLIVersion() + " (external, cli)",
|
||||
StainlessLang: "js",
|
||||
StainlessPackageVersion: "0.94.0",
|
||||
StainlessOS: "Linux",
|
||||
@@ -157,12 +193,29 @@ func (s *IdentityService) GetOrCreateFingerprint(ctx context.Context, accountID
|
||||
logger.LegacyPrintf("service.identity",
|
||||
"Replaced malformed cached fingerprint for account %d: %q -> %q",
|
||||
accountID, poisoned, cached.UserAgent)
|
||||
} else if uaAcceptable && isNewerVersion(clientUA, cached.UserAgent) {
|
||||
// 版本升级:merge 语义 — 仅更新请求中实际携带的字段,保留缓存值
|
||||
// 避免缺失的头被硬编码默认值覆盖(如新 CLI 版本 + 旧 SDK 默认值的不一致)
|
||||
mergeHeadersIntoFingerprint(cached, headers)
|
||||
} else {
|
||||
// 客户端送来更新版本时的常规升级:merge 语义 — 仅更新请求中实际携带的字段,
|
||||
// 保留缓存值,避免缺失的头被硬编码默认值覆盖(如新 CLI 版本 + 旧 SDK 默认值的不一致)
|
||||
if uaAcceptable && isNewerVersion(clientUA, cached.UserAgent) {
|
||||
mergeHeadersIntoFingerprint(cached, headers)
|
||||
needWrite = true
|
||||
logger.LegacyPrintf("service.identity", "Updated fingerprint for account %d: %s (merge update)", accountID, clientUA)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 版本下限抬升(floor):heal 与 healthy 两条缓存命中路径共同的后置条件,与
|
||||
// 上面的客户端常规升级相互独立、二者取更新者。客户端送来更旧版本时
|
||||
// isNewerVersion 不触发,此处仍能把低于 CLICurrentVersion 的存量指纹就地抬到
|
||||
// 下限并持久化,否则升 CLICurrentVersion 对所有已有账号无效,新模型的客户端
|
||||
// 版本闸门(如 Fable 5.1 要求 >= 2.1.251)永远过不去。自愈路径同样必须经过:
|
||||
// 畸形缓存 + 合法但过旧的客户端 UA 首次读取就要落到下限,不能先落库一个
|
||||
// 过旧版本、等下一次读取才纠正。
|
||||
if flooredUA, changed := floorClaudeCLIUserAgentVersion(cached.UserAgent); changed {
|
||||
cached.UserAgent = flooredUA
|
||||
needWrite = true
|
||||
logger.LegacyPrintf("service.identity", "Updated fingerprint for account %d: %s (merge update)", accountID, clientUA)
|
||||
logger.LegacyPrintf("service.identity",
|
||||
"Floored cached fingerprint claude-cli version for account %d: %s", accountID, flooredUA)
|
||||
}
|
||||
|
||||
if !needWrite && time.Since(time.Unix(cached.UpdatedAt, 0)) > 24*time.Hour {
|
||||
@@ -208,7 +261,9 @@ func (s *IdentityService) createFingerprintFromHeaders(headers http.Header) *Fin
|
||||
// 获取User-Agent:只接受形态合法且版本合理的值,否则回退默认指纹。
|
||||
// 首次创建同样是持久化写入,必须与升级路径共用同一套校验。
|
||||
if ua := strings.TrimSpace(headers.Get("User-Agent")); isAcceptableFingerprintUserAgent(ua) {
|
||||
fp.UserAgent = ua
|
||||
// 首次创建与缓存命中路径共用同一个版本下限:合法但过旧的 claude-cli UA
|
||||
// 落库时同样不能低于 CLICurrentVersion,否则新账号一开始就带着过旧的持久身份。
|
||||
fp.UserAgent, _ = floorClaudeCLIUserAgentVersion(ua)
|
||||
} else {
|
||||
fp.UserAgent = defaultFingerprint.UserAgent
|
||||
}
|
||||
|
||||
@@ -105,8 +105,9 @@ func TestGetOrCreateFingerprintRejectsMalformedUserAgentOnCreate(t *testing.T) {
|
||||
// 升级路径:哨兵版本号不得覆盖已缓存的真实指纹。
|
||||
// isNewerVersion 是纯数值比较,999.0.0 恒大于任何真实版本,一旦写入永远无法夺回。
|
||||
func TestGetOrCreateFingerprintRejectsSentinelVersionOnUpgrade(t *testing.T) {
|
||||
// 缓存版本取 CLICurrentVersion(>= 下限),使本用例只验证哨兵拒绝,不与版本下限抬升耦合。
|
||||
cached := &Fingerprint{
|
||||
UserAgent: "claude-cli/2.1.22 (external, cli)",
|
||||
UserAgent: "claude-cli/" + claude.CLICurrentVersion + " (external, cli)",
|
||||
ClientID: "cid-1",
|
||||
UpdatedAt: time.Now().Unix(),
|
||||
}
|
||||
@@ -119,7 +120,7 @@ func TestGetOrCreateFingerprintRejectsSentinelVersionOnUpgrade(t *testing.T) {
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "claude-cli/2.1.22 (external, cli)", fp.UserAgent,
|
||||
require.Equal(t, "claude-cli/"+claude.CLICurrentVersion+" (external, cli)", fp.UserAgent,
|
||||
"真实指纹不得被哨兵版本覆盖")
|
||||
require.Zero(t, cache.setCalls, "被拒的 UA 不应触发任何写入")
|
||||
}
|
||||
@@ -133,7 +134,9 @@ func TestGetOrCreateFingerprintStillUpgradesOnValidNewerVersion(t *testing.T) {
|
||||
}}
|
||||
svc := NewIdentityService(cache)
|
||||
|
||||
newUA := "claude-cli/2.1.223 (external, cli)"
|
||||
// 客户端版本取高于 CLICurrentVersion 的合法值,使本用例只验证常规升级,
|
||||
// 不与版本下限抬升耦合(低于下限的客户端升级由 version_floor 测试覆盖)。
|
||||
newUA := "claude-cli/2.9.0 (external, cli)"
|
||||
fp, err := svc.GetOrCreateFingerprint(context.Background(), 1, headersWithUA(newUA))
|
||||
|
||||
require.NoError(t, err)
|
||||
@@ -176,8 +179,10 @@ func TestGetOrCreateFingerprintHealsPoisonedCacheUsingValidClientUA(t *testing.T
|
||||
fp, err := svc.GetOrCreateFingerprint(context.Background(), 1, headersWithUA(realUA))
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, realUA, fp.UserAgent,
|
||||
"真实客户端必须能从被毒化的指纹手中夺回账号身份")
|
||||
// 真实客户端从被毒化的指纹手中夺回账号身份,但版本下限在自愈的同一读取内生效:
|
||||
// 合法而过旧的 UA 不能先以过旧版本落库、等下次读取才被抬升。
|
||||
require.Equal(t, "claude-cli/"+claude.CLICurrentVersion+" (external, cli)", fp.UserAgent)
|
||||
require.Equal(t, fp.UserAgent, cache.lastSet.UserAgent, "自愈与下限抬升应合并为同一次落库")
|
||||
require.Equal(t, 1, cache.setCalls)
|
||||
require.NotContains(t, cache.lastSet.UserAgent, "999.0.0")
|
||||
require.Equal(t, "cid-1", fp.ClientID, "自愈不应重置 ClientID")
|
||||
@@ -203,9 +208,10 @@ func TestGetOrCreateFingerprintHealsPoisonedCacheWithoutValidClientUA(t *testing
|
||||
}
|
||||
|
||||
// 自愈只针对畸形缓存:合法缓存 + 非更新版本的合法 UA 不得触发额外写入。
|
||||
// 缓存版本取 CLICurrentVersion(>= 下限),低于下限的缓存抬升由 version_floor 测试覆盖。
|
||||
func TestGetOrCreateFingerprintDoesNotRewriteHealthyCache(t *testing.T) {
|
||||
cache := &stubIdentityCache{fingerprint: &Fingerprint{
|
||||
UserAgent: "claude-cli/2.1.220 (external, cli)",
|
||||
UserAgent: "claude-cli/" + claude.CLICurrentVersion + " (external, cli)",
|
||||
ClientID: "cid-1",
|
||||
UpdatedAt: time.Now().Unix(),
|
||||
}}
|
||||
@@ -217,7 +223,7 @@ func TestGetOrCreateFingerprintDoesNotRewriteHealthyCache(t *testing.T) {
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "claude-cli/2.1.220 (external, cli)", fp.UserAgent)
|
||||
require.Equal(t, "claude-cli/"+claude.CLICurrentVersion+" (external, cli)", fp.UserAgent)
|
||||
require.Zero(t, cache.setCalls)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
|
||||
)
|
||||
|
||||
// floorClaudeCLIUserAgentVersion 单元测试:版本下限抬升的各种形态。
|
||||
func TestFloorClaudeCLIUserAgentVersion(t *testing.T) {
|
||||
floorUA := "claude-cli/" + claude.CLICurrentVersion
|
||||
cases := []struct {
|
||||
name string
|
||||
ua string
|
||||
want string
|
||||
wantChanged bool
|
||||
}{
|
||||
// 线上故障形态:历史版本低于 CLICurrentVersion,就地抬到下限。
|
||||
{"old_version_upgraded", "claude-cli/2.1.220 (external, cli)", floorUA + " (external, cli)", true},
|
||||
// 只替换版本号段,括号内的真实客户端形态原样保留。
|
||||
{"old_version_with_desktop_3p_suffix",
|
||||
"claude-cli/2.1.100 (external, claude-desktop-3p, agent-sdk/0.3.100)",
|
||||
floorUA + " (external, claude-desktop-3p, agent-sdk/0.3.100)", true},
|
||||
// 等于下限:不得改动。
|
||||
{"equal_to_floor", floorUA + " (external, cli)", floorUA + " (external, cli)", false},
|
||||
// 高于下限:只升不降,不得把客户端上报的更新版本压回去。
|
||||
{"newer_than_floor_not_downgraded", "claude-cli/2.9.0 (external, cli)", "claude-cli/2.9.0 (external, cli)", false},
|
||||
// 非 claude-cli 产品:一律不动。
|
||||
{"other_product_untouched", "opencode/1.2.3 (external, cli)", "opencode/1.2.3 (external, cli)", false},
|
||||
// 空串 / 畸形:一律不动。
|
||||
{"empty", "", "", false},
|
||||
{"no_version", "claude-cli (external, cli)", "claude-cli (external, cli)", false},
|
||||
{"unparseable_version", "claude-cli/abc (external, cli)", "claude-cli/abc (external, cli)", false},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, changed := floorClaudeCLIUserAgentVersion(tc.ua)
|
||||
require.Equal(t, tc.want, got)
|
||||
require.Equal(t, tc.wantChanged, changed)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// GetOrCreateFingerprint 集成行为,直接对应线上故障:缓存指纹停留在历史版本
|
||||
// 2.1.220(生产 Redis 中账号 147 的实际值),客户端送来更旧的 2.1.75。
|
||||
// 修复前:isNewerVersion 不触发、UA 形态合法不触发自愈,旧指纹被原样返回并
|
||||
// 近乎永不过期——上游按指纹 UA 做客户端版本闸门(Fable 5.1 要求 >= 2.1.251),
|
||||
// 仅升 CLICurrentVersion 对存量账号完全无效。
|
||||
func TestGetOrCreateFingerprintFloorsStaleCachedUserAgent(t *testing.T) {
|
||||
cache := &stubIdentityCache{fingerprint: &Fingerprint{
|
||||
UserAgent: "claude-cli/2.1.220 (external, cli)",
|
||||
ClientID: "cid-1",
|
||||
StainlessPackageVersion: "0.91.1",
|
||||
UpdatedAt: time.Now().Unix(),
|
||||
}}
|
||||
svc := NewIdentityService(cache)
|
||||
|
||||
fp, err := svc.GetOrCreateFingerprint(
|
||||
context.Background(), 147,
|
||||
headersWithUA("claude-cli/2.1.75 (external, cli)"),
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "claude-cli/"+claude.CLICurrentVersion+" (external, cli)", fp.UserAgent)
|
||||
require.Equal(t, 1, cache.setCalls, "下限抬升必须持久化写回缓存")
|
||||
require.Equal(t, "claude-cli/"+claude.CLICurrentVersion+" (external, cli)", cache.lastSet.UserAgent)
|
||||
// X-Stainless-* 维持既有 merge 语义:客户端未携带时保留缓存中的真实值,不被下限逻辑覆盖。
|
||||
require.Equal(t, "0.91.1", fp.StainlessPackageVersion)
|
||||
}
|
||||
|
||||
// 缓存版本高于下限:不得被降级,也不得触发多余写入。
|
||||
func TestGetOrCreateFingerprintDoesNotTouchCacheAboveFloor(t *testing.T) {
|
||||
ua := "claude-cli/2.9.0 (external, cli)"
|
||||
cache := &stubIdentityCache{fingerprint: &Fingerprint{
|
||||
UserAgent: ua,
|
||||
ClientID: "cid-1",
|
||||
StainlessPackageVersion: "0.91.1",
|
||||
UpdatedAt: time.Now().Unix(),
|
||||
}}
|
||||
svc := NewIdentityService(cache)
|
||||
|
||||
fp, err := svc.GetOrCreateFingerprint(
|
||||
context.Background(), 1,
|
||||
headersWithUA("claude-cli/2.1.75 (external, cli)"),
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, ua, fp.UserAgent, "高于下限的缓存版本不得被降级")
|
||||
require.Zero(t, cache.setCalls)
|
||||
}
|
||||
|
||||
// 客户端送来高于下限的更新版本:常规升级照常生效,且不被下限压回。
|
||||
func TestGetOrCreateFingerprintClientNewerThanFloorStillWins(t *testing.T) {
|
||||
newUA := "claude-cli/2.9.0 (external, cli)"
|
||||
cache := &stubIdentityCache{fingerprint: &Fingerprint{
|
||||
UserAgent: "claude-cli/2.1.220 (external, cli)",
|
||||
ClientID: "cid-1",
|
||||
UpdatedAt: time.Now().Unix(),
|
||||
}}
|
||||
svc := NewIdentityService(cache)
|
||||
|
||||
fp, err := svc.GetOrCreateFingerprint(context.Background(), 1, headersWithUA(newUA))
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, newUA, fp.UserAgent, "客户端更新版本优先于下限,不得被压回")
|
||||
require.Equal(t, 1, cache.setCalls)
|
||||
}
|
||||
|
||||
// 客户端版本高于缓存但低于下限:merge 升级后仍被抬到下限(二者取更新者)。
|
||||
func TestGetOrCreateFingerprintFloorWinsOverStaleClientUpgrade(t *testing.T) {
|
||||
cache := &stubIdentityCache{fingerprint: &Fingerprint{
|
||||
UserAgent: "claude-cli/2.1.22 (external, cli)",
|
||||
ClientID: "cid-1",
|
||||
UpdatedAt: time.Now().Unix(),
|
||||
}}
|
||||
svc := NewIdentityService(cache)
|
||||
|
||||
fp, err := svc.GetOrCreateFingerprint(
|
||||
context.Background(), 1,
|
||||
headersWithUA("claude-cli/2.1.223 (external, cli)"),
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "claude-cli/"+claude.CLICurrentVersion+" (external, cli)", fp.UserAgent)
|
||||
require.Equal(t, 1, cache.setCalls)
|
||||
}
|
||||
|
||||
// 首次创建路径同样受下限约束:合法但过旧的 claude-cli UA 落库时必须抬到 CLICurrentVersion。
|
||||
func TestCreateFingerprintFromHeadersFloorsOldClientUserAgent(t *testing.T) {
|
||||
cache := &stubIdentityCache{}
|
||||
svc := NewIdentityService(cache)
|
||||
|
||||
fp, err := svc.GetOrCreateFingerprint(
|
||||
context.Background(), 1,
|
||||
headersWithUA("claude-cli/2.1.75 (external, claude-desktop-3p)"),
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "claude-cli/"+claude.CLICurrentVersion+" (external, claude-desktop-3p)", fp.UserAgent)
|
||||
require.Equal(t, 1, cache.setCalls)
|
||||
}
|
||||
@@ -112,3 +112,29 @@ func TestIsOpenAICodexPlanGatedModelError(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsOpenAICompatibleModelNotFound400(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
want bool
|
||||
}{
|
||||
{name: "structured code", body: `{"error":{"code":"model_not_found","message":"No such deployment"}}`, want: true},
|
||||
{name: "unknown provider", body: `{"error":{"message":"Unknown provider for model claude-x"}}`, want: true},
|
||||
{name: "model not found", body: `{"error":{"message":"Model not found: claude-x"}}`, want: true},
|
||||
{name: "model unsupported", body: `{"error":{"message":"The requested model is not supported"}}`, want: true},
|
||||
{name: "plain text compatible gateway", body: `unknown provider for model claude-x`, want: true},
|
||||
{name: "invalid parameter remains terminal", body: `{"error":{"code":"invalid_request_error","message":"Invalid value for temperature"}}`, want: false},
|
||||
{name: "structured non-matching code overrides model not found message", body: `{"error":{"code":"invalid_request_error","message":"Model not found: claude-x"}}`, want: false},
|
||||
{name: "structured non-matching error code overrides unsupported message", body: `{"error":{"code":"upstream_error","message":"The requested model is not supported"}}`, want: false},
|
||||
{name: "echoed phrase is ignored", body: `{"error":{"message":"Invalid request"},"echo":"model not found"}`, want: false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := isOpenAICompatibleModelNotFound400([]byte(tt.body)); got != tt.want {
|
||||
t.Fatalf("isOpenAICompatibleModelNotFound400() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -231,7 +231,7 @@ func (s *ModelPlazaService) fillDisplayPricing(ctx context.Context, m *PlazaMode
|
||||
Platform: m.Platform,
|
||||
})
|
||||
if err == nil && sched != nil && len(sched.Tiers) > 0 {
|
||||
m.Pricing = plazaPricingFromSchedule(m.Pricing, sched)
|
||||
m.Pricing = withDefaultMaxReasoningEffortMultiplier(plazaPricingFromSchedule(m.Pricing, sched), m.Name)
|
||||
if len(sched.Tiers) > 1 {
|
||||
m.LongContextBasis = sched.Basis
|
||||
}
|
||||
@@ -239,7 +239,20 @@ func (s *ModelPlazaService) fillDisplayPricing(ctx context.Context, m *PlazaMode
|
||||
return
|
||||
}
|
||||
}
|
||||
m.Pricing = plazaImageDisplayPricing(m.Pricing, g)
|
||||
m.Pricing = withDefaultMaxReasoningEffortMultiplier(plazaImageDisplayPricing(m.Pricing, g), m.Name)
|
||||
}
|
||||
|
||||
func withDefaultMaxReasoningEffortMultiplier(pricing *ChannelModelPricing, model string) *ChannelModelPricing {
|
||||
if pricing == nil || pricing.MaxReasoningEffortMultiplier != nil {
|
||||
return pricing
|
||||
}
|
||||
multiplier := defaultMaxReasoningEffortMultiplier(model)
|
||||
if multiplier == nil {
|
||||
return pricing
|
||||
}
|
||||
cloned := pricing.Clone()
|
||||
cloned.MaxReasoningEffortMultiplier = multiplier
|
||||
return &cloned
|
||||
}
|
||||
|
||||
// plazaPricingFromSchedule 把阶梯表压成展示用的 ChannelModelPricing:
|
||||
@@ -250,6 +263,7 @@ func plazaPricingFromSchedule(raw *ChannelModelPricing, sched *ContextPricingSch
|
||||
out.ImageInputPrice = raw.ImageInputPrice
|
||||
out.ImageOutputPrice = raw.ImageOutputPrice
|
||||
out.PerRequestPrice = raw.PerRequestPrice
|
||||
out.MaxReasoningEffortMultiplier = raw.MaxReasoningEffortMultiplier
|
||||
}
|
||||
first := sched.Tiers[0]
|
||||
out.InputPrice = first.Input
|
||||
|
||||
@@ -57,6 +57,19 @@ func TestListPlazaGroups_GroupCentricAggregation(t *testing.T) {
|
||||
require.Equal(t, "claude-sonnet", out[0].Models[1].Name)
|
||||
}
|
||||
|
||||
func TestWithDefaultMaxReasoningEffortMultiplier_Fable51(t *testing.T) {
|
||||
base := &ChannelModelPricing{BillingMode: BillingModeToken}
|
||||
got := withDefaultMaxReasoningEffortMultiplier(base, "claude-fable-5-1")
|
||||
require.NotSame(t, base, got)
|
||||
require.NotNil(t, got.MaxReasoningEffortMultiplier)
|
||||
require.Equal(t, 3.0, *got.MaxReasoningEffortMultiplier)
|
||||
require.Nil(t, base.MaxReasoningEffortMultiplier)
|
||||
|
||||
configured := 1.25
|
||||
custom := &ChannelModelPricing{MaxReasoningEffortMultiplier: &configured}
|
||||
require.Same(t, custom, withDefaultMaxReasoningEffortMultiplier(custom, "claude-fable-5-1"))
|
||||
}
|
||||
|
||||
func TestListPlazaGroups_DedupFirstWinsWithPricingUpgrade(t *testing.T) {
|
||||
// 同名模型:先见者胜;仅当已存条目无定价而新条目有定价时升级替换。
|
||||
unpriced := Channel{
|
||||
|
||||
@@ -247,6 +247,9 @@ func (r *ModelPricingResolver) applyTokenOverrides(chPricing *ChannelModelPricin
|
||||
}
|
||||
resolved.BasePricing.FastMultiplier = chPricing.FastMultiplier
|
||||
resolved.BasePricing.FlexMultiplier = chPricing.FlexMultiplier
|
||||
if chPricing.MaxReasoningEffortMultiplier != nil {
|
||||
resolved.BasePricing.MaxReasoningEffortMultiplier = chPricing.MaxReasoningEffortMultiplier
|
||||
}
|
||||
// 渠道定价覆盖一切:显式配置则用配置值,未配置则归零(不回退到 LiteLLM)
|
||||
if chPricing.ImageOutputPrice != nil {
|
||||
resolved.BasePricing.ImageOutputPricePerToken = *chPricing.ImageOutputPrice
|
||||
|
||||
@@ -77,7 +77,7 @@ func TestOpenAIUpstreamAccessStateClassification(t *testing.T) {
|
||||
if !tt.want {
|
||||
return
|
||||
}
|
||||
require.True(t, (&OpenAIGatewayService{}).shouldFailoverOpenAIUpstreamResponse(http.StatusForbidden, "", body))
|
||||
require.True(t, (&OpenAIGatewayService{}).shouldFailoverOpenAIUpstreamResponse(newOpenAIUpstreamErrorTestAccount(), http.StatusForbidden, "", body))
|
||||
require.True(t, shouldFailoverOpenAIPassthroughResponse(&Account{Type: AccountTypeOAuth}, http.StatusForbidden, body))
|
||||
|
||||
err := newOpenAIUpstreamFailoverError(http.StatusForbidden, nil, body, "", true)
|
||||
@@ -105,7 +105,7 @@ func TestOpenAIHTTPAccessStateDoesNotTrustBadRequestMessage(t *testing.T) {
|
||||
|
||||
require.False(t, isOpenAIUpstreamAccessStateError("", body), "free-form stream messages are not durable account evidence")
|
||||
require.False(t, isOpenAIHTTPUpstreamAccessStateError(http.StatusBadRequest, "", body))
|
||||
require.False(t, svc.shouldFailoverOpenAIUpstreamResponse(http.StatusBadRequest, "", body))
|
||||
require.False(t, svc.shouldFailoverOpenAIUpstreamResponse(newOpenAIUpstreamErrorTestAccount(), http.StatusBadRequest, "", body))
|
||||
require.False(t, shouldFailoverOpenAIPassthroughResponse(&Account{Type: AccountTypeOAuth}, http.StatusBadRequest, body))
|
||||
|
||||
err := newOpenAIUpstreamFailoverError(http.StatusBadRequest, nil, body, "", false)
|
||||
@@ -148,7 +148,7 @@ func TestOpenAIHTTPAccessStateTrustsStructuredCode(t *testing.T) {
|
||||
body := []byte(`{"error":{"code":"organization_deactivated","message":"request rejected"}}`)
|
||||
|
||||
require.True(t, isOpenAIHTTPUpstreamAccessStateError(http.StatusBadRequest, "", body))
|
||||
require.True(t, svc.shouldFailoverOpenAIUpstreamResponse(http.StatusBadRequest, "", body))
|
||||
require.True(t, svc.shouldFailoverOpenAIUpstreamResponse(newOpenAIUpstreamErrorTestAccount(), http.StatusBadRequest, "", body))
|
||||
require.True(t, svc.handleOpenAIAccountUpstreamError(context.Background(), account, http.StatusBadRequest, nil, body))
|
||||
require.Equal(t, 1, repo.setErrorCalls)
|
||||
require.True(t, svc.isOpenAIAccountRuntimeBlocked(account))
|
||||
@@ -189,7 +189,7 @@ func TestOpenAIHTTPAuthMessagesUseExistingStatusPolicies(t *testing.T) {
|
||||
func TestOpenAICyberPolicyWrapped5xxNeverFailsOver(t *testing.T) {
|
||||
body := []byte(`{"error":{"code":"cyber_policy","message":"blocked"}}`)
|
||||
svc := &OpenAIGatewayService{}
|
||||
require.False(t, svc.shouldFailoverOpenAIUpstreamResponse(http.StatusBadGateway, "wrapped upstream failure", body))
|
||||
require.False(t, svc.shouldFailoverOpenAIUpstreamResponse(newOpenAIUpstreamErrorTestAccount(), http.StatusBadGateway, "wrapped upstream failure", body))
|
||||
require.False(t, shouldFailoverOpenAIPassthroughResponse(&Account{Type: AccountTypeOAuth}, http.StatusBadGateway, body))
|
||||
}
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ func (s *OpenAIGatewayService) ForwardAlphaSearch(ctx context.Context, c *gin.Co
|
||||
|
||||
if resp.StatusCode >= http.StatusBadRequest {
|
||||
upstreamMessage := sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody)))
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(resp.StatusCode, upstreamMessage, respBody) ||
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMessage, respBody) ||
|
||||
isOpenAIAlphaSearchEndpointUnsupported(account, resp.StatusCode) {
|
||||
resp.Body = io.NopCloser(bytes.NewReader(respBody))
|
||||
// alpha/search 是独立的工具端点,单次 401 不能证明账号的模型调用
|
||||
@@ -175,7 +175,7 @@ func (s *OpenAIGatewayService) forwardAlphaSearchViaResponsesWebSearch(
|
||||
|
||||
if resp.StatusCode >= http.StatusBadRequest {
|
||||
upstreamMessage := sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody)))
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(resp.StatusCode, upstreamMessage, respBody) {
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMessage, respBody) {
|
||||
resp.Body = io.NopCloser(bytes.NewReader(respBody))
|
||||
// 仍按 alpha/search 工具请求处理:PAT 的工具链路失败不能直接永久置错。
|
||||
shouldDisable := false
|
||||
|
||||
@@ -1,11 +1,111 @@
|
||||
package service
|
||||
|
||||
import "strings"
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var codexToolCapabilityFields = []string{
|
||||
"supports_search_tool", "apply_patch_tool_type", "comp_hash", "tool_mode", "use_responses_lite",
|
||||
}
|
||||
|
||||
func applyCodexToolCapabilities(dst, src map[string]json.RawMessage, overwrite bool) bool {
|
||||
changed := false
|
||||
for _, field := range codexToolCapabilityFields {
|
||||
value := bytes.TrimSpace(src[field])
|
||||
if len(value) == 0 {
|
||||
continue
|
||||
}
|
||||
// These five Codex fields are nullable booleans or strings, never arbitrary objects.
|
||||
if !bytes.Equal(value, []byte("null")) {
|
||||
if field == "supports_search_tool" || field == "use_responses_lite" {
|
||||
if !bytes.Equal(value, []byte("true")) && !bytes.Equal(value, []byte("false")) {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
var text string
|
||||
if json.Unmarshal(value, &text) != nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
current, exists := dst[field]
|
||||
if (exists && !overwrite) || bytes.Equal(current, value) {
|
||||
continue
|
||||
}
|
||||
dst[field] = append(json.RawMessage(nil), value...)
|
||||
changed = true
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
func accountCodexToolCapabilities(account *Account, modelID string) map[string]json.RawMessage {
|
||||
capabilities := make(map[string]json.RawMessage)
|
||||
if account == nil {
|
||||
return capabilities
|
||||
}
|
||||
if metadata, ok := account.GetUpstreamModelMetadata(modelID); ok {
|
||||
applyCodexToolCapabilities(capabilities, metadata.CodexToolCapabilities, true)
|
||||
}
|
||||
if account.IsOpenAI() && shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
|
||||
// This bridge implements client-side tool discovery, even without a native manifest.
|
||||
applyCodexToolCapabilities(capabilities, map[string]json.RawMessage{"supports_search_tool": json.RawMessage("true")}, false)
|
||||
}
|
||||
// Codex 0.153's bundled Astra catalog verifies these values. API-key routes
|
||||
// use standard Responses, not the ChatGPT-only Responses Lite wire.
|
||||
baseURL := strings.TrimSpace(account.GetCredential("base_url"))
|
||||
if baseURL == "" {
|
||||
baseURL = account.GetOpenAIBaseURL()
|
||||
}
|
||||
parsed, err := url.Parse(baseURL)
|
||||
official := err == nil && (strings.EqualFold(parsed.Hostname(), "api.openai.com") ||
|
||||
(account.IsOpenAIOAuth() && strings.EqualFold(parsed.Hostname(), "chatgpt.com")))
|
||||
if account.IsOpenAI() && isOpenAIGPT6AstraModel(modelID) && official {
|
||||
defaults := map[string]json.RawMessage{
|
||||
"supports_search_tool": json.RawMessage("true"),
|
||||
"apply_patch_tool_type": json.RawMessage(`"freeform"`),
|
||||
"comp_hash": json.RawMessage(`"3000"`),
|
||||
"tool_mode": json.RawMessage("null"),
|
||||
"use_responses_lite": json.RawMessage("false"),
|
||||
}
|
||||
if account.IsOpenAIOAuth() {
|
||||
defaults["tool_mode"] = json.RawMessage(`"code_mode_only"`)
|
||||
defaults["use_responses_lite"] = json.RawMessage("true")
|
||||
}
|
||||
applyCodexToolCapabilities(capabilities, defaults, false)
|
||||
}
|
||||
if account.IsOpenAIApiKey() {
|
||||
target := modelID
|
||||
if isOpenAIGPT6AstraModel(target) {
|
||||
target = "gpt-6-astra"
|
||||
}
|
||||
_, disabled := apiKeyCodexModelsWithoutResponsesLite[target]
|
||||
if disabled && bytes.Equal(capabilities["use_responses_lite"], []byte("true")) {
|
||||
capabilities["use_responses_lite"] = json.RawMessage("false")
|
||||
}
|
||||
}
|
||||
return capabilities
|
||||
}
|
||||
|
||||
// codexModelRoutingAccountIDs 返回分组显式为该公开别名声明的账号集合。
|
||||
//
|
||||
// 返回非空表示运营者已经用 model_routing 指明“这个别名由这些账号服务”,此时别名的
|
||||
// 归属不再是需要推断的未知量:能力声明只看这些账号,且不再因为它们映射到不同上游而
|
||||
// 判定为冲突。返回空表示没有相关规则,保持原有的全量推断与失败即关闭行为。
|
||||
func codexModelRoutingAccountIDs(group *Group, modelID string) []int64 {
|
||||
if group == nil {
|
||||
return nil
|
||||
}
|
||||
return group.GetRoutingAccountIDs(strings.TrimSpace(modelID))
|
||||
}
|
||||
|
||||
func groupCodexModelMetadata(
|
||||
platform string,
|
||||
modelID string,
|
||||
accounts []Account,
|
||||
group *Group,
|
||||
compositeRoutes []CompositeModelRoute,
|
||||
compositeRoutesAvailable bool,
|
||||
) (codexModelMetadataOverride, bool) {
|
||||
@@ -13,6 +113,9 @@ func groupCodexModelMetadata(
|
||||
if modelID == "" {
|
||||
return codexModelMetadataOverride{}, false
|
||||
}
|
||||
// 显式路由规则本身与平台无关,先取出来供后续两处判定共用。
|
||||
routedAccountIDs := codexModelRoutingAccountIDs(group, modelID)
|
||||
routed := len(routedAccountIDs) > 0
|
||||
upstreamModel := modelID
|
||||
if platform == PlatformComposite {
|
||||
var resolved bool
|
||||
@@ -23,7 +126,7 @@ func groupCodexModelMetadata(
|
||||
compositeRoutesAvailable,
|
||||
)
|
||||
if !resolved {
|
||||
if codexExplicitModelTargetsConflict(accounts, modelID) {
|
||||
if !routed && codexExplicitModelTargetsConflict(accounts, modelID) {
|
||||
return codexModelMetadataOverride{
|
||||
reasoningConflict: true,
|
||||
inputModalitiesConflict: true,
|
||||
@@ -38,21 +141,32 @@ func groupCodexModelMetadata(
|
||||
|
||||
explicitClaims := false
|
||||
if upstreamModel == modelID {
|
||||
for _, account := range accounts {
|
||||
if account.Platform == platform && codexExplicitModelMappingClaims(account, modelID) {
|
||||
for i := range accounts {
|
||||
account := &accounts[i]
|
||||
if routed && !containsInt64(routedAccountIDs, account.ID) {
|
||||
continue
|
||||
}
|
||||
if account.Platform == platform && codexExplicitModelMappingClaims(*account, modelID) {
|
||||
explicitClaims = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
explicitTargetsConflict := explicitClaims && codexExplicitModelTargetsConflictForPlatform(accounts, platform, modelID)
|
||||
// 别名已被显式路由声明时,"多个账号映射到不同上游"是故障转移的正常写法,不是歧义,
|
||||
// 因此不再失败即关闭;能力回落到与单账号无快照时相同的按名推导。
|
||||
explicitTargetsConflict := explicitClaims && !routed &&
|
||||
codexExplicitModelTargetsConflictForPlatform(accounts, platform, modelID)
|
||||
publicAlias := upstreamModel != modelID
|
||||
candidates := make([]UpstreamModelMetadata, 0)
|
||||
missingMetadata := false
|
||||
for i := range accounts {
|
||||
account := &accounts[i]
|
||||
if account.Platform != platform {
|
||||
continue
|
||||
}
|
||||
if routed && !containsInt64(routedAccountIDs, account.ID) {
|
||||
continue
|
||||
}
|
||||
var lookupModel string
|
||||
if explicitClaims {
|
||||
if !codexExplicitModelMappingClaims(*account, modelID) {
|
||||
@@ -76,14 +190,20 @@ func groupCodexModelMetadata(
|
||||
inputModalitiesConflict: true,
|
||||
}, true
|
||||
}
|
||||
return codexModelMetadataOverride{}, false
|
||||
missingMetadata = true
|
||||
}
|
||||
metadata.CodexToolCapabilities = accountCodexToolCapabilities(account, lookupModel)
|
||||
candidates = append(candidates, metadata)
|
||||
}
|
||||
if len(candidates) == 0 {
|
||||
return codexModelMetadataOverride{}, false
|
||||
}
|
||||
metadata := intersectUpstreamModelMetadata(modelID, candidates)
|
||||
if missingMetadata {
|
||||
metadata = codexModelMetadataOverride{UpstreamModelMetadata: UpstreamModelMetadata{
|
||||
CodexToolCapabilities: metadata.CodexToolCapabilities,
|
||||
}}
|
||||
}
|
||||
if publicAlias {
|
||||
metadata.DisplayName = modelID
|
||||
metadata.Description = configuredCodexCustomDescription
|
||||
@@ -124,6 +244,27 @@ func codexExplicitModelTargetsConflictForPlatform(accounts []Account, platform,
|
||||
|
||||
func intersectUpstreamModelMetadata(modelID string, candidates []UpstreamModelMetadata) codexModelMetadataOverride {
|
||||
result := codexModelMetadataOverride{UpstreamModelMetadata: UpstreamModelMetadata{ID: strings.TrimSpace(modelID)}}
|
||||
result.CodexToolCapabilities = make(map[string]json.RawMessage)
|
||||
for _, field := range codexToolCapabilityFields {
|
||||
value := bytes.TrimSpace(candidates[0].CodexToolCapabilities[field])
|
||||
shared := len(value) > 0
|
||||
declared := shared
|
||||
for _, candidate := range candidates[1:] {
|
||||
declared = declared || len(candidate.CodexToolCapabilities[field]) > 0
|
||||
if !bytes.Equal(value, bytes.TrimSpace(candidate.CodexToolCapabilities[field])) {
|
||||
shared = false
|
||||
}
|
||||
}
|
||||
if shared {
|
||||
result.CodexToolCapabilities[field] = value
|
||||
} else if declared {
|
||||
fallback := json.RawMessage("null")
|
||||
if field == "supports_search_tool" || field == "use_responses_lite" {
|
||||
fallback = json.RawMessage("false")
|
||||
}
|
||||
result.CodexToolCapabilities[field] = fallback
|
||||
}
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
if result.DisplayName == "" && strings.TrimSpace(candidate.DisplayName) != "" {
|
||||
result.DisplayName = strings.TrimSpace(candidate.DisplayName)
|
||||
|
||||
@@ -2,12 +2,92 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAstraCodexToolCapabilitiesUseAccountScopeAndSharedDeclarations(t *testing.T) {
|
||||
newAccount := func(baseURL string) Account {
|
||||
return Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{
|
||||
"base_url": baseURL, "model_mapping": map[string]any{"public-astra": "gpt-6-astra"},
|
||||
}}
|
||||
}
|
||||
official := newAccount("https://api.openai.com/v1")
|
||||
custom := newAccount("https://relay.example/v1")
|
||||
bridge := newAccount("https://bridge.example/v1")
|
||||
bridge.Extra = map[string]any{"openai_responses_supported": false}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
accounts []Account
|
||||
search bool
|
||||
}{
|
||||
{"official fallback", []Account{official}, true},
|
||||
{"custom host has no guessed capability", []Account{custom}, false},
|
||||
{"missing peer capability", []Account{official, custom}, false},
|
||||
{"implemented chat bridge", []Account{bridge}, true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
body, err := buildCodexModelsManifestForAccounts(PlatformOpenAI, []string{"public-astra"}, tt.accounts, nil, nil, true)
|
||||
require.NoError(t, err)
|
||||
model := decodeCodexManifestModels(t, body)[0]
|
||||
require.Equal(t, "public-astra", model["slug"])
|
||||
require.Equal(t, tt.search, model["supports_search_tool"])
|
||||
require.Equal(t, false, model["use_responses_lite"])
|
||||
if tt.name == "official fallback" {
|
||||
require.Equal(t, "freeform", model["apply_patch_tool_type"])
|
||||
require.Equal(t, "3000", model["comp_hash"])
|
||||
}
|
||||
})
|
||||
}
|
||||
custom.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{Models: map[string]UpstreamModelMetadata{
|
||||
"gpt-6-astra": {CodexToolCapabilities: map[string]json.RawMessage{
|
||||
"supports_search_tool": json.RawMessage("true"), "apply_patch_tool_type": json.RawMessage("null"),
|
||||
"comp_hash": json.RawMessage(`"3000"`), "tool_mode": json.RawMessage("null"), "use_responses_lite": json.RawMessage("false"),
|
||||
}},
|
||||
}})
|
||||
body, err := buildCodexModelsManifestForAccounts(PlatformOpenAI, []string{"public-astra"}, []Account{official, custom}, nil, nil, true)
|
||||
require.NoError(t, err)
|
||||
model := decodeCodexManifestModels(t, body)[0]
|
||||
require.Equal(t, true, model["supports_search_tool"])
|
||||
require.Nil(t, model["apply_patch_tool_type"], "conflicting tool protocols must not be advertised")
|
||||
require.Equal(t, "3000", model["comp_hash"])
|
||||
}
|
||||
|
||||
func TestAstraCodexToolCapabilitiesPreserveLiveNullAndFalse(t *testing.T) {
|
||||
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"base_url": "https://api.openai.com/v1"}}
|
||||
account.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{Models: map[string]UpstreamModelMetadata{
|
||||
"gpt-6-astra": {CodexToolCapabilities: map[string]json.RawMessage{
|
||||
"supports_search_tool": json.RawMessage("true"), "apply_patch_tool_type": json.RawMessage(`"freeform"`),
|
||||
"comp_hash": json.RawMessage(`"3000"`), "tool_mode": json.RawMessage(`"code_mode_only"`),
|
||||
}},
|
||||
}})
|
||||
for _, source := range []string{
|
||||
`{"models":[{"slug":"gpt-6-astra","supports_search_tool":false,"apply_patch_tool_type":null,"tool_mode":null}]}`,
|
||||
`{"data":[{"id":"gpt-6-astra","supports_search_tool":false,"apply_patch_tool_type":null,"tool_mode":null}]}`,
|
||||
} {
|
||||
converted := convertOpenAIModelListToCodexManifestForAccount([]byte(source), account)
|
||||
body, err := applySyncedAPIKeyCodexModelMetadata(converted, account, source[2:6] == "data")
|
||||
require.NoError(t, err)
|
||||
body, err = completeAPIKeyCodexModelsManifestMetadata(body, true, account)
|
||||
require.NoError(t, err)
|
||||
model := decodeCodexManifestModels(t, body)[0]
|
||||
require.Equal(t, false, model["supports_search_tool"])
|
||||
require.Nil(t, model["apply_patch_tool_type"])
|
||||
require.Nil(t, model["tool_mode"])
|
||||
require.Equal(t, "3000", model["comp_hash"])
|
||||
}
|
||||
fields := make(map[string]json.RawMessage)
|
||||
applyCodexToolCapabilities(fields, map[string]json.RawMessage{
|
||||
"supports_search_tool": json.RawMessage(`"true"`), "comp_hash": json.RawMessage(`{"unexpected":true}`),
|
||||
"model_messages": json.RawMessage(`"do not persist prompts"`),
|
||||
}, true)
|
||||
require.Empty(t, fields)
|
||||
}
|
||||
|
||||
// Scenario: mixed groups prefer capability metadata synced for the routed account.
|
||||
func TestBuildCodexModelsManifestForGroupUsesSyncedAccountMetadata(t *testing.T) {
|
||||
t.Parallel()
|
||||
@@ -120,7 +200,7 @@ func TestBuildCodexModelsManifestForGroupAdvertisesSearchOnlyForChatBridgeRoutes
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
body, err := buildCodexModelsManifestForAccounts(
|
||||
PlatformOpenAI, []string{"company-coding-model"}, tc.accounts, nil, true,
|
||||
PlatformOpenAI, []string{"company-coding-model"}, tc.accounts, nil, nil, true,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
models := decodeCodexManifestModels(t, body)
|
||||
@@ -472,3 +552,140 @@ func TestBuildCodexModelsManifestForGroupDoesNotAdvertiseNoneWhenAccountReasonin
|
||||
require.False(t, hasDefault)
|
||||
require.Empty(t, models[0]["supported_reasoning_levels"])
|
||||
}
|
||||
|
||||
func TestAstraCodexToolCapabilitiesFollowAPIKeyAlias(t *testing.T) {
|
||||
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{
|
||||
"base_url": "https://relay.example/v1", "model_mapping": map[string]any{"my-astra": "gpt-6-astra"},
|
||||
}}
|
||||
account.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{Models: map[string]UpstreamModelMetadata{
|
||||
"gpt-6-astra": {CodexToolCapabilities: map[string]json.RawMessage{
|
||||
"supports_search_tool": json.RawMessage("true"), "apply_patch_tool_type": json.RawMessage(`"freeform"`),
|
||||
"use_responses_lite": json.RawMessage("false"),
|
||||
}},
|
||||
}})
|
||||
for _, source := range []string{`{"data":[{"id":"my-astra"}]}`, `{"models":[{"slug":"my-astra"}]}`} {
|
||||
converted := convertOpenAIModelListToCodexManifestForAccount([]byte(source), account)
|
||||
body, err := completeAPIKeyCodexModelsManifestMetadata(converted, true, account)
|
||||
require.NoError(t, err)
|
||||
models := decodeCodexManifestModels(t, body)
|
||||
require.Len(t, models, 1)
|
||||
model := models[0]
|
||||
require.Equal(t, "my-astra", model["slug"])
|
||||
require.Equal(t, "my-astra", model["display_name"])
|
||||
require.Equal(t, true, model["supports_search_tool"])
|
||||
require.Equal(t, "freeform", model["apply_patch_tool_type"])
|
||||
require.Equal(t, false, model["use_responses_lite"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAstraCodexToolCapabilitiesKeepAPIKeyResponsesLiteGuard(t *testing.T) {
|
||||
account := Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{
|
||||
"base_url": "https://relay.example/v1", "model_mapping": map[string]any{"my-astra": "gpt-6-astra"},
|
||||
}}
|
||||
account.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{Models: map[string]UpstreamModelMetadata{
|
||||
"gpt-6-astra": {CodexToolCapabilities: map[string]json.RawMessage{"use_responses_lite": json.RawMessage("true")}},
|
||||
}})
|
||||
body, err := buildCodexModelsManifestForAccounts(PlatformOpenAI, []string{"my-astra"}, []Account{account}, nil, nil, true)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, false, decodeCodexManifestModels(t, body)[0]["use_responses_lite"])
|
||||
body, err = adjustAPIKeyCodexModelsManifest([]byte(`{"models":[{"slug":"my-astra","use_responses_lite":true}]}`), &account)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, false, decodeCodexManifestModels(t, body)[0]["use_responses_lite"])
|
||||
}
|
||||
|
||||
// Scenario: an OpenAI group keeps a failover account whose mapping points the
|
||||
// shared public alias at a different upstream model. Without an explicit routing
|
||||
// rule the alias target is ambiguous and capabilities must fail closed; with one,
|
||||
// the operator has declared who serves the alias, so the reasoning slider and
|
||||
// image input must survive.
|
||||
func TestCodexAliasFailoverMappingHonorsModelRouting(t *testing.T) {
|
||||
newAccount := func(id int64, target string, priority int) Account {
|
||||
return Account{
|
||||
ID: id,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Priority: priority,
|
||||
Credentials: map[string]any{
|
||||
"base_url": "https://relay.example/v1",
|
||||
"model_mapping": map[string]any{"gpt-6-astra": target},
|
||||
},
|
||||
}
|
||||
}
|
||||
// Account 16-alike serves the alias natively; account 1-alike is the failover
|
||||
// and can only reach a different upstream model.
|
||||
primary := newAccount(16, "gpt-6-astra", 0)
|
||||
failover := newAccount(1, "gpt-5.6-sol", 10)
|
||||
accounts := []Account{primary, failover}
|
||||
|
||||
// supported_reasoning_levels entries are {effort, description} objects; the
|
||||
// slider only cares about the effort names.
|
||||
manifestFieldsOf := func(t *testing.T, group *Group) ([]string, any, any) {
|
||||
t.Helper()
|
||||
body, err := buildCodexModelsManifestForAccounts(
|
||||
PlatformOpenAI, []string{"gpt-6-astra"}, accounts, group, nil, true,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
models := decodeCodexManifestModels(t, body)
|
||||
require.Len(t, models, 1)
|
||||
model := models[0]
|
||||
require.Equal(t, "gpt-6-astra", model["slug"])
|
||||
var efforts []string
|
||||
levels, _ := model["supported_reasoning_levels"].([]any)
|
||||
for _, level := range levels {
|
||||
entry, ok := level.(map[string]any)
|
||||
require.True(t, ok, "reasoning level entry must be an object")
|
||||
effort, ok := entry["effort"].(string)
|
||||
require.True(t, ok, "reasoning level entry must carry an effort name")
|
||||
efforts = append(efforts, effort)
|
||||
}
|
||||
return efforts, model["default_reasoning_level"], model["input_modalities"]
|
||||
}
|
||||
|
||||
t.Run("no routing rule still fails closed", func(t *testing.T) {
|
||||
levels, def, modalities := manifestFieldsOf(t, nil)
|
||||
require.Empty(t, levels, "ambiguous alias target must not advertise reasoning levels")
|
||||
require.Nil(t, def)
|
||||
require.Equal(t, []any{"text"}, modalities)
|
||||
})
|
||||
|
||||
t.Run("routing rule resolves the alias", func(t *testing.T) {
|
||||
group := &Group{
|
||||
ID: 2,
|
||||
Platform: PlatformOpenAI,
|
||||
ModelRoutingEnabled: true,
|
||||
ModelRouting: map[string][]int64{"gpt-6-astra": {16, 1}},
|
||||
}
|
||||
levels, def, modalities := manifestFieldsOf(t, group)
|
||||
require.Equal(t,
|
||||
[]string{"low", "medium", "high", "xhigh", "max"},
|
||||
levels,
|
||||
"routed alias must keep a movable reasoning slider",
|
||||
)
|
||||
require.Equal(t, "medium", def)
|
||||
require.Contains(t, modalities, "image")
|
||||
})
|
||||
|
||||
t.Run("routing disabled falls back to failing closed", func(t *testing.T) {
|
||||
group := &Group{
|
||||
ID: 2,
|
||||
Platform: PlatformOpenAI,
|
||||
ModelRoutingEnabled: false,
|
||||
ModelRouting: map[string][]int64{"gpt-6-astra": {16, 1}},
|
||||
}
|
||||
levels, _, _ := manifestFieldsOf(t, group)
|
||||
require.Empty(t, levels, "a disabled routing rule must not resolve the alias")
|
||||
})
|
||||
|
||||
t.Run("routing rule for another alias does not leak", func(t *testing.T) {
|
||||
group := &Group{
|
||||
ID: 2,
|
||||
Platform: PlatformOpenAI,
|
||||
ModelRoutingEnabled: true,
|
||||
ModelRouting: map[string][]int64{"gpt-5.6-sol": {1}},
|
||||
}
|
||||
levels, _, _ := manifestFieldsOf(t, group)
|
||||
require.Empty(t, levels, "unrelated routing rules must not resolve this alias")
|
||||
})
|
||||
}
|
||||
|
||||
// Scenario: mixed groups prefer capability metadata synced for the routed account.
|
||||
@@ -114,18 +114,53 @@ func mergeCodexModelsManifestBodies(bodies [][]byte) ([]byte, error) {
|
||||
// - every fetch failed → the last upstream error
|
||||
// - partial failure → successful accounts are still merged and a warning
|
||||
// naming the failed account IDs is logged.
|
||||
func (s *OpenAIGatewayService) FetchPinnedCodexModelsManifest(ctx context.Context, group *Group, clientVersion string) (*CodexModelsManifest, *Account, error) {
|
||||
func (s *OpenAIGatewayService) FetchPinnedCodexModelsManifest(ctx context.Context, group *Group, clientVersion string) (*OpenAIModelsResponse, *Account, error) {
|
||||
results, err := s.fetchPinnedOpenAIModels(ctx, group, func(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) {
|
||||
manifest, err := s.FetchCodexModelsManifest(ctx, account, clientVersion, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.CompleteAPIKeyCodexModelsManifestForClient(manifest, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ApplyPinnedCodexModelsMapping(manifest, account, group); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return manifest, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
bodies := make([][]byte, 0, len(results))
|
||||
for _, result := range results {
|
||||
bodies = append(bodies, result.response.Body)
|
||||
}
|
||||
merged, err := mergeCodexModelsManifestBodies(bodies)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("merge pinned codex models manifests: %w", err)
|
||||
}
|
||||
return &OpenAIModelsResponse{Body: merged, ETag: codexModelsManifestBodyETag(merged)}, results[0].account, nil
|
||||
}
|
||||
|
||||
type pinnedOpenAIModelsResult struct {
|
||||
account *Account
|
||||
response *OpenAIModelsResponse
|
||||
}
|
||||
|
||||
// fetchPinnedOpenAIModels shares membership, eligibility, fanout and partial
|
||||
// failure policy between ordinary model lists and Codex manifests.
|
||||
func (s *OpenAIGatewayService) fetchPinnedOpenAIModels(ctx context.Context, group *Group, fetch func(context.Context, *Account) (*OpenAIModelsResponse, error)) ([]pinnedOpenAIModelsResult, error) {
|
||||
if s == nil || s.accountRepo == nil || group == nil {
|
||||
return nil, nil, ErrNoPinnedCodexModelsAccounts
|
||||
return nil, ErrNoPinnedCodexModelsAccounts
|
||||
}
|
||||
cfg := group.CodexModelsManifestConfig
|
||||
if group.Platform != PlatformOpenAI || !cfg.Enabled || len(cfg.AccountIDs) == 0 {
|
||||
return nil, nil, ErrNoPinnedCodexModelsAccounts
|
||||
return nil, ErrNoPinnedCodexModelsAccounts
|
||||
}
|
||||
|
||||
members, err := s.accountRepo.ListByGroup(ctx, group.ID)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("load pinned codex models manifest accounts: %w", err)
|
||||
return nil, fmt.Errorf("load pinned codex models manifest accounts: %w", err)
|
||||
}
|
||||
memberByID := make(map[int64]Account, len(members))
|
||||
for _, member := range members {
|
||||
@@ -145,70 +180,46 @@ func (s *OpenAIGatewayService) FetchPinnedCodexModelsManifest(ctx context.Contex
|
||||
usable = append(usable, member)
|
||||
}
|
||||
if len(usable) == 0 {
|
||||
return nil, nil, ErrNoPinnedCodexModelsAccounts
|
||||
return nil, ErrNoPinnedCodexModelsAccounts
|
||||
}
|
||||
|
||||
bodies := make([][]byte, len(usable))
|
||||
results := make([]pinnedOpenAIModelsResult, len(usable))
|
||||
fetchErrs := make([]error, len(usable))
|
||||
// 各自独立完成、不取消兄弟请求,错误按下标收集,普通 WaitGroup 足够。
|
||||
var fetchGroup sync.WaitGroup
|
||||
for i := range usable {
|
||||
account := usable[i]
|
||||
index := i
|
||||
fetchGroup.Add(1)
|
||||
go func() {
|
||||
defer fetchGroup.Done()
|
||||
manifest, fetchErr := s.FetchCodexModelsManifest(ctx, &account, clientVersion, "")
|
||||
if fetchErr != nil {
|
||||
fetchErrs[index] = fetchErr
|
||||
return
|
||||
}
|
||||
if completeErr := s.CompleteAPIKeyCodexModelsManifestForClient(manifest, &account); completeErr != nil {
|
||||
fetchErrs[index] = completeErr
|
||||
return
|
||||
}
|
||||
bodies[index] = manifest.Body
|
||||
response, err := fetch(ctx, &usable[i])
|
||||
results[i] = pinnedOpenAIModelsResult{account: &usable[i], response: response}
|
||||
fetchErrs[i] = err
|
||||
}()
|
||||
}
|
||||
fetchGroup.Wait()
|
||||
|
||||
successBodies := make([][]byte, 0, len(usable))
|
||||
successAccounts := make([]*Account, 0, len(usable))
|
||||
failedIDs := make([]int64, 0)
|
||||
for i := range usable {
|
||||
if fetchErrs[i] != nil || bodies[i] == nil {
|
||||
failedIDs = append(failedIDs, usable[i].ID)
|
||||
continue
|
||||
}
|
||||
successBodies = append(successBodies, bodies[i])
|
||||
successAccounts = append(successAccounts, &usable[i])
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(successBodies) == 0 {
|
||||
var lastErr error
|
||||
for i := range fetchErrs {
|
||||
successes := make([]pinnedOpenAIModelsResult, 0, len(results))
|
||||
failedIDs := make([]int64, 0)
|
||||
var lastErr error
|
||||
for i, result := range results {
|
||||
if fetchErrs[i] != nil || result.response == nil {
|
||||
failedIDs = append(failedIDs, usable[i].ID)
|
||||
if fetchErrs[i] != nil {
|
||||
lastErr = fetchErrs[i]
|
||||
}
|
||||
continue
|
||||
}
|
||||
successes = append(successes, result)
|
||||
}
|
||||
if len(successes) == 0 {
|
||||
if lastErr == nil {
|
||||
lastErr = infraerrors.New(http.StatusBadGateway, "OPENAI_CODEX_MODELS_UPSTREAM_FAILED", "pinned codex models manifest accounts all failed")
|
||||
lastErr = infraerrors.New(http.StatusBadGateway, "OPENAI_MODELS_UPSTREAM_FAILED", "pinned model discovery accounts all failed")
|
||||
}
|
||||
return nil, nil, lastErr
|
||||
return nil, lastErr
|
||||
}
|
||||
if len(failedIDs) > 0 {
|
||||
slog.Warn("codex_models_manifest_pinned_partial_failure",
|
||||
"group_id", group.ID,
|
||||
"failed_account_ids", failedIDs,
|
||||
)
|
||||
slog.Warn("openai_models_pinned_partial_failure", "group_id", group.ID, "failed_account_ids", failedIDs)
|
||||
}
|
||||
|
||||
merged, err := mergeCodexModelsManifestBodies(successBodies)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("merge pinned codex models manifests: %w", err)
|
||||
}
|
||||
firstAccount := *successAccounts[0]
|
||||
return &CodexModelsManifest{
|
||||
Body: merged,
|
||||
ETag: codexModelsManifestBodyETag(merged),
|
||||
}, &firstAccount, nil
|
||||
return successes, nil
|
||||
}
|
||||
@@ -30,18 +30,18 @@ import (
|
||||
var chatgptCodexModelsURL = "https://chatgpt.com/backend-api/codex/models"
|
||||
|
||||
const (
|
||||
codexModelsManifestCacheBodyLimit = 1 << 20
|
||||
// codexModelsManifestCacheMaxEntries 上限按「账号数 × 客户端版本数 × 代理形态」
|
||||
openAIModelsCacheBodyLimit = 1 << 20
|
||||
// openAIModelsCacheMaxEntries 上限按「账号数 × 客户端版本数 × 代理形态」
|
||||
// 估算:缓存同时覆盖 OAuth 与 API Key 账号,且缓存键含 Authorization 与
|
||||
// Version 头,不同客户端版本各自占一条;64 条在大规模部署下会被淘汰导致
|
||||
// 额外上游请求。单条清单通常几十 KB,512 条最坏内存占用在几十 MB 量级。
|
||||
codexModelsManifestCacheMaxEntries = 512
|
||||
openAIModelsCacheMaxEntries = 512
|
||||
// 三段时效:≤TTL 为新鲜(直接返回缓存,零上游请求);TTL 到 StaleTTL 之间
|
||||
// 乐观返回旧值并后台单飞刷新(携带上游 ETag,304 续期);超过 StaleTTL 丢弃
|
||||
// 缓存同步等待刷新。TTL 取 1 分钟:manifest 变化低频,1 分钟内同账号重复
|
||||
// 请求完全吸收;StaleTTL 取 5 分钟,控制旧内容最长可见时间在分钟级。
|
||||
codexModelsManifestCacheTTL = 60 * time.Second
|
||||
codexModelsManifestCacheStaleTTL = 5 * time.Minute
|
||||
openAIModelsCacheTTL = 60 * time.Second
|
||||
openAIModelsCacheStaleTTL = 5 * time.Minute
|
||||
codexModelsManifestRequestTimeout = 15 * time.Second
|
||||
codexAutoModelPrefix = "codex-auto-"
|
||||
)
|
||||
@@ -105,8 +105,9 @@ func codexProviderQualifiedModelID(modelID string) string {
|
||||
return strings.TrimPrefix(modelID, "models/")
|
||||
}
|
||||
|
||||
// CodexModelsManifest carries the client representation plus caching metadata.
|
||||
type CodexModelsManifest struct {
|
||||
// OpenAIModelsResponse carries either an OpenAI model list or a Codex manifest
|
||||
// together with upstream and client caching metadata.
|
||||
type OpenAIModelsResponse struct {
|
||||
Body []byte
|
||||
ETag string
|
||||
upstreamETag string
|
||||
@@ -123,7 +124,7 @@ func (s *OpenAIGatewayService) BuildGroupConfiguredCodexModelsManifest(
|
||||
ctx context.Context,
|
||||
group *Group,
|
||||
ifNoneMatch string,
|
||||
) (*CodexModelsManifest, bool, error) {
|
||||
) (*OpenAIModelsResponse, bool, error) {
|
||||
if s == nil || s.accountRepo == nil || group == nil || group.Platform != PlatformOpenAI {
|
||||
return nil, false, nil
|
||||
}
|
||||
@@ -141,6 +142,7 @@ func (s *OpenAIGatewayService) BuildGroupConfiguredCodexModelsManifest(
|
||||
PlatformOpenAI,
|
||||
configuredModels,
|
||||
catalog,
|
||||
group,
|
||||
nil,
|
||||
true,
|
||||
)
|
||||
@@ -156,7 +158,7 @@ func (s *OpenAIGatewayService) BuildGroupConfiguredCodexModelsManifest(
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("build group configured Codex models: %w", err)
|
||||
}
|
||||
manifest := &CodexModelsManifest{
|
||||
manifest := &OpenAIModelsResponse{
|
||||
Body: body,
|
||||
ETag: codexModelsManifestBodyETag(body),
|
||||
}
|
||||
@@ -174,7 +176,7 @@ func (s *OpenAIGatewayService) BuildGroupConfiguredCodexModelsManifest(
|
||||
func (s *OpenAIGatewayService) MergeGroupConfiguredCodexModels(
|
||||
ctx context.Context,
|
||||
group *Group,
|
||||
manifest *CodexModelsManifest,
|
||||
manifest *OpenAIModelsResponse,
|
||||
ifNoneMatch string,
|
||||
) error {
|
||||
if s == nil || s.accountRepo == nil || group == nil || manifest == nil || manifest.NotModified {
|
||||
@@ -184,9 +186,13 @@ func (s *OpenAIGatewayService) MergeGroupConfiguredCodexModels(
|
||||
return nil
|
||||
}
|
||||
|
||||
configuredModels, err := s.groupConfiguredCodexModelIDs(ctx, group)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load group configured Codex models: %w", err)
|
||||
var configuredModels []string
|
||||
if !group.CodexModelsManifestConfig.Enabled {
|
||||
var err error
|
||||
configuredModels, err = s.groupConfiguredCodexModelIDs(ctx, group)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load group configured Codex models: %w", err)
|
||||
}
|
||||
}
|
||||
body, changed, err := mergeConfiguredCodexModelsManifest(
|
||||
manifest.Body,
|
||||
@@ -197,6 +203,13 @@ func (s *OpenAIGatewayService) MergeGroupConfiguredCodexModels(
|
||||
if err != nil {
|
||||
return fmt.Errorf("merge group configured Codex models: %w", err)
|
||||
}
|
||||
if group.CodexModelsManifestConfig.Enabled && group.ModelAllowlistEnabled() {
|
||||
body, err = orderPinnedCodexModelsBySelection(body, group.ModelAllowlist)
|
||||
if err != nil {
|
||||
return fmt.Errorf("order pinned Codex models: %w", err)
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if changed {
|
||||
manifest.Body = body
|
||||
manifest.ETag = codexModelsManifestBodyETag(body)
|
||||
@@ -324,6 +337,7 @@ const (
|
||||
configuredCodexGrokContext = 500_000
|
||||
configuredCodexGrokBuildContext = 256_000
|
||||
configuredCodexGPT56MaxContext = 872_000
|
||||
configuredCodexGPT6AstraContext = 1_050_000
|
||||
configuredCodexToolOutputMaxTokens = 10_000
|
||||
)
|
||||
|
||||
@@ -482,15 +496,7 @@ func newConfiguredCodexModelDescriptor(modelID string) configuredCodexModelDescr
|
||||
descriptor.DisplayName = openaiCodexDisplayName(modelID)
|
||||
descriptor.Description = "OpenAI GPT coding model routed through Sub2API."
|
||||
descriptor.SupportsParallelToolCalls = true
|
||||
if configuredCodexSupportsPriorityServiceTier(modelID) {
|
||||
descriptor.ServiceTiers = []configuredCodexServiceTier{
|
||||
{
|
||||
ID: "priority",
|
||||
Name: "Fast",
|
||||
Description: "Priority processing for lower latency.",
|
||||
},
|
||||
}
|
||||
}
|
||||
descriptor.ServiceTiers = configuredCodexServiceTiersForModel(modelID)
|
||||
if isOpenAICodexReasoningGPTModel(modelID) {
|
||||
defaultReasoningLevel := "medium"
|
||||
if getNormalizedCodexModel(modelID) == "gpt-5.6-sol" {
|
||||
@@ -503,6 +509,10 @@ func newConfiguredCodexModelDescriptor(modelID string) configuredCodexModelDescr
|
||||
if isOpenAIGPT56Model(modelID) {
|
||||
descriptor.MaxContextWindow = configuredCodexGPT56MaxContext
|
||||
}
|
||||
if isOpenAIGPT6AstraModel(modelID) {
|
||||
descriptor.ContextWindow = configuredCodexGPT6AstraContext
|
||||
descriptor.MaxContextWindow = configuredCodexGPT6AstraContext
|
||||
}
|
||||
}
|
||||
if SupportsVerbosity(modelID) {
|
||||
defaultVerbosity := "low"
|
||||
@@ -514,6 +524,25 @@ func newConfiguredCodexModelDescriptor(modelID string) configuredCodexModelDescr
|
||||
return descriptor
|
||||
}
|
||||
|
||||
func configuredCodexServiceTiersForModel(modelID string) []configuredCodexServiceTier {
|
||||
tiers := make([]configuredCodexServiceTier, 0, 2)
|
||||
if configuredCodexSupportsPriorityServiceTier(modelID) {
|
||||
tiers = append(tiers, configuredCodexServiceTier{
|
||||
ID: OpenAIFastTierPriority,
|
||||
Name: "Fast",
|
||||
Description: "Priority processing for lower latency.",
|
||||
})
|
||||
}
|
||||
if configuredCodexSupportsUltrafastServiceTier(modelID) {
|
||||
tiers = append(tiers, configuredCodexServiceTier{
|
||||
ID: OpenAIFastTierUltrafast,
|
||||
Name: "Ultrafast",
|
||||
Description: "Ultra-low latency processing.",
|
||||
})
|
||||
}
|
||||
return tiers
|
||||
}
|
||||
|
||||
func configuredCodexSupportsPriorityServiceTier(modelID string) bool {
|
||||
normalized := canonicalizeOpenAIModelAliasSpelling(modelID)
|
||||
for _, family := range []string{"gpt-5.4", "gpt-5.5", "gpt-5.6"} {
|
||||
@@ -521,7 +550,12 @@ func configuredCodexSupportsPriorityServiceTier(modelID string) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
// GPT-6 Astra advertises Fast via service_tier=priority in public model metadata.
|
||||
return isOpenAIGPT6AstraModel(modelID)
|
||||
}
|
||||
|
||||
func configuredCodexSupportsUltrafastServiceTier(modelID string) bool {
|
||||
return normalizeKnownOpenAICodexModel(modelID) == "gpt-5.6-sol"
|
||||
}
|
||||
|
||||
func configuredCodexGrokReasoningLevels(modelID string) []configuredCodexReasoningLevel {
|
||||
@@ -580,7 +614,7 @@ func configuredCodexGPTReasoningLevels(modelID string) []configuredCodexReasonin
|
||||
{Effort: "xhigh", Description: "Extra-high reasoning depth for difficult tasks"},
|
||||
}
|
||||
normalized := getNormalizedCodexModel(modelID)
|
||||
if isOpenAIGPT56Model(modelID) {
|
||||
if isOpenAIGPT56Model(modelID) || isOpenAIGPT6AstraModel(modelID) {
|
||||
levels = append(levels, configuredCodexReasoningLevel{
|
||||
Effort: "max",
|
||||
Description: "Maximum reasoning depth for complex tasks",
|
||||
@@ -605,12 +639,13 @@ func isOpenAICodexGPTModel(modelID string) bool {
|
||||
|
||||
func isOpenAICodexReasoningGPTModel(modelID string) bool {
|
||||
normalized := canonicalizeOpenAIModelAliasSpelling(modelID)
|
||||
return strings.HasPrefix(normalized, "gpt-5")
|
||||
return isOpenAIGPT6AstraModel(normalized) || strings.HasPrefix(normalized, "gpt-5")
|
||||
}
|
||||
|
||||
func isOpenAICodexImageInputModel(modelID string) bool {
|
||||
normalized := canonicalizeOpenAIModelAliasSpelling(modelID)
|
||||
return strings.HasPrefix(normalized, "gpt-5") ||
|
||||
return isOpenAIGPT6AstraModel(normalized) ||
|
||||
strings.HasPrefix(normalized, "gpt-5") ||
|
||||
strings.HasPrefix(normalized, "gpt-4o") ||
|
||||
strings.HasPrefix(normalized, "gpt-4.1") ||
|
||||
strings.HasPrefix(normalized, "gpt-4.5") ||
|
||||
@@ -789,6 +824,7 @@ func (s *GatewayService) BuildCodexModelsManifestForGroup(
|
||||
effectivePlatform,
|
||||
modelIDs,
|
||||
catalog,
|
||||
group,
|
||||
compositeRoutes,
|
||||
compositeRoutesAvailable,
|
||||
)
|
||||
@@ -798,6 +834,7 @@ func buildCodexModelsManifestForAccounts(
|
||||
effectivePlatform string,
|
||||
modelIDs []string,
|
||||
accounts []Account,
|
||||
group *Group,
|
||||
compositeRoutes []CompositeModelRoute,
|
||||
compositeRoutesAvailable bool,
|
||||
) ([]byte, error) {
|
||||
@@ -835,6 +872,7 @@ func buildCodexModelsManifestForAccounts(
|
||||
effectivePlatform,
|
||||
modelID,
|
||||
accounts,
|
||||
group,
|
||||
compositeRoutes,
|
||||
compositeRoutesAvailable,
|
||||
); ok {
|
||||
@@ -852,7 +890,7 @@ func buildCodexModelsManifest(
|
||||
modelMetadata map[string]codexModelMetadataOverride,
|
||||
) ([]byte, error) {
|
||||
seen := make(map[string]struct{}, len(modelIDs))
|
||||
models := make([]configuredCodexModelDescriptor, 0, len(modelIDs))
|
||||
models := make([]json.RawMessage, 0, len(modelIDs))
|
||||
for _, modelID := range modelIDs {
|
||||
modelID = strings.TrimSpace(modelID)
|
||||
if modelID == "" {
|
||||
@@ -882,10 +920,25 @@ func buildCodexModelsManifest(
|
||||
descriptor.DisplayName = modelID
|
||||
descriptor.Description = configuredCodexCustomDescription
|
||||
}
|
||||
models = append(models, descriptor)
|
||||
encoded, err := json.Marshal(descriptor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if capabilities := modelMetadata[modelID].CodexToolCapabilities; len(capabilities) > 0 {
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(encoded, &fields); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
applyCodexToolCapabilities(fields, capabilities, true)
|
||||
encoded, err = json.Marshal(fields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
models = append(models, encoded)
|
||||
}
|
||||
return json.Marshal(struct {
|
||||
Models []configuredCodexModelDescriptor `json:"models"`
|
||||
Models []json.RawMessage `json:"models"`
|
||||
}{Models: models})
|
||||
}
|
||||
|
||||
@@ -1443,7 +1496,7 @@ func isRetryableCodexModelsManifestTransportError(err error) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
type codexModelsManifestRequest struct {
|
||||
type openAIModelsRequest struct {
|
||||
url string
|
||||
headers http.Header
|
||||
proxyURL string
|
||||
@@ -1452,61 +1505,63 @@ type codexModelsManifestRequest struct {
|
||||
credentialAccount *Account
|
||||
accountConcurrency int
|
||||
useAPIKeyUpstream bool
|
||||
// Cached bodies have already been converted to their requested format.
|
||||
standardModelsList bool
|
||||
}
|
||||
|
||||
type codexModelsManifestCacheEntry struct {
|
||||
manifest *CodexModelsManifest
|
||||
type openAIModelsCacheEntry struct {
|
||||
manifest *OpenAIModelsResponse
|
||||
order uint64
|
||||
expiresAt time.Time
|
||||
staleUntil time.Time
|
||||
}
|
||||
|
||||
type codexModelsManifestCacheState uint8
|
||||
type openAIModelsCacheState uint8
|
||||
|
||||
const (
|
||||
codexModelsManifestCacheMiss codexModelsManifestCacheState = iota
|
||||
codexModelsManifestCacheFresh
|
||||
codexModelsManifestCacheStale
|
||||
openAIModelsCacheMiss openAIModelsCacheState = iota
|
||||
openAIModelsCacheFresh
|
||||
openAIModelsCacheStale
|
||||
)
|
||||
|
||||
type codexModelsManifestCache struct {
|
||||
type openAIModelsCache struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]codexModelsManifestCacheEntry
|
||||
entries map[string]openAIModelsCacheEntry
|
||||
nextOrder uint64
|
||||
refresh singleflight.Group
|
||||
}
|
||||
|
||||
func (c *codexModelsManifestCache) get(key string, now time.Time) (*CodexModelsManifest, codexModelsManifestCacheState) {
|
||||
func (c *openAIModelsCache) get(key string, now time.Time) (*OpenAIModelsResponse, openAIModelsCacheState) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
entry, ok := c.entries[key]
|
||||
if !ok {
|
||||
return nil, codexModelsManifestCacheMiss
|
||||
return nil, openAIModelsCacheMiss
|
||||
}
|
||||
if !now.Before(entry.staleUntil) {
|
||||
delete(c.entries, key)
|
||||
return nil, codexModelsManifestCacheMiss
|
||||
return nil, openAIModelsCacheMiss
|
||||
}
|
||||
if now.Before(entry.expiresAt) {
|
||||
return entry.manifest, codexModelsManifestCacheFresh
|
||||
return entry.manifest, openAIModelsCacheFresh
|
||||
}
|
||||
return entry.manifest, codexModelsManifestCacheStale
|
||||
return entry.manifest, openAIModelsCacheStale
|
||||
}
|
||||
|
||||
func (c *codexModelsManifestCache) set(key string, manifest *CodexModelsManifest, now time.Time) {
|
||||
if manifest == nil || len(manifest.Body) > codexModelsManifestCacheBodyLimit {
|
||||
func (c *openAIModelsCache) set(key string, manifest *OpenAIModelsResponse, now time.Time) {
|
||||
if manifest == nil || len(manifest.Body) > openAIModelsCacheBodyLimit {
|
||||
return
|
||||
}
|
||||
remainingBodyBudget := codexModelsManifestCacheBodyLimit - len(manifest.Body)
|
||||
remainingBodyBudget := openAIModelsCacheBodyLimit - len(manifest.Body)
|
||||
if len(manifest.upstreamSourceBody) > remainingBodyBudget {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.entries == nil {
|
||||
c.entries = make(map[string]codexModelsManifestCacheEntry)
|
||||
c.entries = make(map[string]openAIModelsCacheEntry)
|
||||
}
|
||||
if _, exists := c.entries[key]; !exists && len(c.entries) >= codexModelsManifestCacheMaxEntries {
|
||||
if _, exists := c.entries[key]; !exists && len(c.entries) >= openAIModelsCacheMaxEntries {
|
||||
oldestKey := ""
|
||||
var oldestOrder uint64
|
||||
for candidateKey, entry := range c.entries {
|
||||
@@ -1519,16 +1574,16 @@ func (c *codexModelsManifestCache) set(key string, manifest *CodexModelsManifest
|
||||
oldestOrder = entry.order
|
||||
}
|
||||
}
|
||||
if len(c.entries) >= codexModelsManifestCacheMaxEntries && oldestKey != "" {
|
||||
if len(c.entries) >= openAIModelsCacheMaxEntries && oldestKey != "" {
|
||||
delete(c.entries, oldestKey)
|
||||
}
|
||||
}
|
||||
c.nextOrder++
|
||||
c.entries[key] = codexModelsManifestCacheEntry{
|
||||
c.entries[key] = openAIModelsCacheEntry{
|
||||
manifest: manifest,
|
||||
order: c.nextOrder,
|
||||
expiresAt: now.Add(codexModelsManifestCacheTTL),
|
||||
staleUntil: now.Add(codexModelsManifestCacheStaleTTL),
|
||||
expiresAt: now.Add(openAIModelsCacheTTL),
|
||||
staleUntil: now.Add(openAIModelsCacheStaleTTL),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1538,7 +1593,7 @@ func (c *codexModelsManifestCache) set(key string, manifest *CodexModelsManifest
|
||||
// After validating the stable top-level envelope, OAuth response bodies are
|
||||
// passed through verbatim. Custom API key manifests receive only the narrowly
|
||||
// scoped compatibility adjustments required by custom-provider Codex clients.
|
||||
func (s *OpenAIGatewayService) FetchCodexModelsManifest(ctx context.Context, account *Account, clientVersion, ifNoneMatch string) (*CodexModelsManifest, error) {
|
||||
func (s *OpenAIGatewayService) FetchCodexModelsManifest(ctx context.Context, account *Account, clientVersion, ifNoneMatch string) (*OpenAIModelsResponse, error) {
|
||||
if account == nil {
|
||||
return nil, infraerrors.New(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_ACCOUNT_REQUIRED", "account is required")
|
||||
}
|
||||
@@ -1626,7 +1681,7 @@ func (s *OpenAIGatewayService) FetchCodexModelsManifest(ctx context.Context, acc
|
||||
proxyURL = account.Proxy.URL()
|
||||
}
|
||||
|
||||
request := codexModelsManifestRequest{
|
||||
request := openAIModelsRequest{
|
||||
url: requestURL.String(),
|
||||
headers: headers,
|
||||
proxyURL: proxyURL,
|
||||
@@ -1637,11 +1692,11 @@ func (s *OpenAIGatewayService) FetchCodexModelsManifest(ctx context.Context, acc
|
||||
useAPIKeyUpstream: useAPIKeyUpstream,
|
||||
}
|
||||
if useAPIKeyUpstream {
|
||||
return s.fetchCachedCodexModelsManifest(ctx, request, s.fetchCodexModelsManifestUpstreamForRequest(request), ifNoneMatch)
|
||||
return s.fetchCachedOpenAIModels(ctx, request, s.fetchCodexModelsManifestUpstreamForRequest(request), ifNoneMatch)
|
||||
}
|
||||
// OAuth 账号同样经过账号级缓存;闭包保留 agent identity 任务恢复逻辑,
|
||||
// 错误时仍交给 handleCodexModelsManifestAccountAuthError 处理账号状态。
|
||||
oauthFetch := func(fetchCtx context.Context, ifNoneMatch string) (*CodexModelsManifest, error) {
|
||||
oauthFetch := func(fetchCtx context.Context, ifNoneMatch string) (*OpenAIModelsResponse, error) {
|
||||
manifest, fetchErr := s.fetchCodexModelsManifestUpstream(fetchCtx, request, ifNoneMatch)
|
||||
if !credAccount.IsOpenAIAgentIdentity() || !isAgentIdentityTaskInvalidCodexModelsError(fetchErr) {
|
||||
s.handleCodexModelsManifestAccountAuthError(fetchCtx, account, credAccount, fetchErr)
|
||||
@@ -1665,7 +1720,7 @@ func (s *OpenAIGatewayService) FetchCodexModelsManifest(ctx context.Context, acc
|
||||
setOpenAIChatGPTAccountHeaders(request.headers, credAccount)
|
||||
return s.fetchCodexModelsManifestUpstream(fetchCtx, request, ifNoneMatch)
|
||||
}
|
||||
return s.fetchCachedCodexModelsManifest(ctx, request, oauthFetch, ifNoneMatch)
|
||||
return s.fetchCachedOpenAIModels(ctx, request, oauthFetch, ifNoneMatch)
|
||||
}
|
||||
|
||||
func isAgentIdentityTaskInvalidCodexModelsError(err error) bool {
|
||||
@@ -1705,18 +1760,18 @@ func (s *OpenAIGatewayService) handleCodexModelsManifestAccountAuthError(ctx con
|
||||
s.handleOpenAIAccountUpstreamError(ctx, account, upstreamErr.statusCode, headers, upstreamErr.body)
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) fetchCachedCodexModelsManifest(ctx context.Context, request codexModelsManifestRequest, fetch func(ctx context.Context, ifNoneMatch string) (*CodexModelsManifest, error), ifNoneMatch string) (*CodexModelsManifest, error) {
|
||||
func (s *OpenAIGatewayService) fetchCachedOpenAIModels(ctx context.Context, request openAIModelsRequest, fetch func(ctx context.Context, ifNoneMatch string) (*OpenAIModelsResponse, error), ifNoneMatch string) (*OpenAIModelsResponse, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cacheKey := buildCodexModelsManifestCacheKey(request)
|
||||
manifest, state := s.codexModelsManifestCache.get(cacheKey, time.Now())
|
||||
if state == codexModelsManifestCacheFresh {
|
||||
return codexModelsManifestForClient(manifest, ifNoneMatch), nil
|
||||
cacheKey := buildOpenAIModelsCacheKey(request)
|
||||
manifest, state := s.openAIModelsCache.get(cacheKey, time.Now())
|
||||
if state == openAIModelsCacheFresh {
|
||||
return openAIModelsResponseForClient(manifest, ifNoneMatch), nil
|
||||
}
|
||||
resultCh := s.refreshCachedCodexModelsManifest(cacheKey, request, fetch)
|
||||
if state == codexModelsManifestCacheStale {
|
||||
return codexModelsManifestForClient(manifest, ifNoneMatch), nil
|
||||
resultCh := s.refreshCachedOpenAIModels(cacheKey, request, fetch)
|
||||
if state == openAIModelsCacheStale {
|
||||
return openAIModelsResponseForClient(manifest, ifNoneMatch), nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -1725,19 +1780,19 @@ func (s *OpenAIGatewayService) fetchCachedCodexModelsManifest(ctx context.Contex
|
||||
if result.Err != nil {
|
||||
return nil, result.Err
|
||||
}
|
||||
manifest, ok := result.Val.(*CodexModelsManifest)
|
||||
manifest, ok := result.Val.(*OpenAIModelsResponse)
|
||||
if !ok || manifest == nil {
|
||||
return nil, infraerrors.New(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_REQUEST_FAILED", "invalid shared Codex models manifest result")
|
||||
}
|
||||
return codexModelsManifestForClient(manifest, ifNoneMatch), nil
|
||||
return openAIModelsResponseForClient(manifest, ifNoneMatch), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) refreshCachedCodexModelsManifest(cacheKey string, request codexModelsManifestRequest, fetch func(ctx context.Context, ifNoneMatch string) (*CodexModelsManifest, error)) <-chan singleflight.Result {
|
||||
return s.codexModelsManifestCache.refresh.DoChan(cacheKey, func() (any, error) {
|
||||
func (s *OpenAIGatewayService) refreshCachedOpenAIModels(cacheKey string, request openAIModelsRequest, fetch func(ctx context.Context, ifNoneMatch string) (*OpenAIModelsResponse, error)) <-chan singleflight.Result {
|
||||
return s.openAIModelsCache.refresh.DoChan(cacheKey, func() (any, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), codexModelsManifestRequestTimeout)
|
||||
defer cancel()
|
||||
cached, _ := s.codexModelsManifestCache.get(cacheKey, time.Now())
|
||||
cached, _ := s.openAIModelsCache.get(cacheKey, time.Now())
|
||||
ifNoneMatch := ""
|
||||
if cached != nil {
|
||||
ifNoneMatch = cached.upstreamETag
|
||||
@@ -1747,23 +1802,23 @@ func (s *OpenAIGatewayService) refreshCachedCodexModelsManifest(cacheKey string,
|
||||
return nil, err
|
||||
}
|
||||
if manifest.NotModified && cached != nil {
|
||||
s.codexModelsManifestCache.set(cacheKey, cached, time.Now())
|
||||
s.openAIModelsCache.set(cacheKey, cached, time.Now())
|
||||
return cached, nil
|
||||
}
|
||||
if !manifest.NotModified {
|
||||
s.codexModelsManifestCache.set(cacheKey, manifest, time.Now())
|
||||
s.openAIModelsCache.set(cacheKey, manifest, time.Now())
|
||||
}
|
||||
return manifest, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstreamForRequest(request codexModelsManifestRequest) func(ctx context.Context, ifNoneMatch string) (*CodexModelsManifest, error) {
|
||||
return func(ctx context.Context, ifNoneMatch string) (*CodexModelsManifest, error) {
|
||||
func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstreamForRequest(request openAIModelsRequest) func(ctx context.Context, ifNoneMatch string) (*OpenAIModelsResponse, error) {
|
||||
return func(ctx context.Context, ifNoneMatch string) (*OpenAIModelsResponse, error) {
|
||||
return s.fetchCodexModelsManifestUpstream(ctx, request, ifNoneMatch)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstream(ctx context.Context, request codexModelsManifestRequest, ifNoneMatch string) (*CodexModelsManifest, error) {
|
||||
func (s *OpenAIGatewayService) fetchOpenAIModelsUpstream(ctx context.Context, request openAIModelsRequest, ifNoneMatch string) (*OpenAIModelsResponse, error) {
|
||||
reqCtx, cancel := context.WithTimeout(ctx, codexModelsManifestRequestTimeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, request.url, nil)
|
||||
@@ -1808,7 +1863,7 @@ func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstream(ctx context.Cont
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode == http.StatusNotModified {
|
||||
return &CodexModelsManifest{ETag: resp.Header.Get("ETag"), NotModified: true}, nil
|
||||
return &OpenAIModelsResponse{ETag: resp.Header.Get("ETag"), NotModified: true}, nil
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
|
||||
@@ -1840,6 +1895,17 @@ func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstream(ctx context.Cont
|
||||
retryable: true,
|
||||
}
|
||||
}
|
||||
etag := resp.Header.Get("ETag")
|
||||
return &OpenAIModelsResponse{Body: body, ETag: etag, upstreamETag: etag}, nil
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstream(ctx context.Context, request openAIModelsRequest, ifNoneMatch string) (*OpenAIModelsResponse, error) {
|
||||
response, err := s.fetchOpenAIModelsUpstream(ctx, request, ifNoneMatch)
|
||||
if err != nil || response.NotModified {
|
||||
return response, err
|
||||
}
|
||||
body := response.Body
|
||||
|
||||
upstreamBody := body
|
||||
convertedFromOpenAIModelList := false
|
||||
if request.useAPIKeyUpstream {
|
||||
@@ -1875,7 +1941,7 @@ func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstream(ctx context.Cont
|
||||
retryable: true,
|
||||
}
|
||||
}
|
||||
body, err = adjustAPIKeyCodexModelsManifest(body)
|
||||
body, err = adjustAPIKeyCodexModelsManifest(body, request.credentialAccount)
|
||||
if err != nil {
|
||||
return nil, &codexModelsManifestUpstreamError{
|
||||
err: infraerrors.Newf(
|
||||
@@ -1888,8 +1954,8 @@ func (s *OpenAIGatewayService) fetchCodexModelsManifestUpstream(ctx context.Cont
|
||||
}
|
||||
}
|
||||
}
|
||||
etag := resp.Header.Get("ETag")
|
||||
manifest := &CodexModelsManifest{
|
||||
etag := response.upstreamETag
|
||||
manifest := &OpenAIModelsResponse{
|
||||
Body: body,
|
||||
ETag: etag,
|
||||
upstreamETag: etag,
|
||||
@@ -1914,6 +1980,7 @@ func CodexModelsManifestETag(body []byte) string {
|
||||
}
|
||||
|
||||
var apiKeyCodexModelsWithoutResponsesLite = map[string]struct{}{
|
||||
"gpt-6-astra": {},
|
||||
"gpt-5.6-sol": {},
|
||||
"gpt-5.6-terra": {},
|
||||
"gpt-5.6-luna": {},
|
||||
@@ -1923,7 +1990,7 @@ var apiKeyCodexModelsWithoutResponsesLite = map[string]struct{}{
|
||||
// Lite for custom API key providers. Those clients do not install web.run in
|
||||
// Lite mode, so the affected model manifests must advertise the full Responses
|
||||
// path. Return the original body when no targeted true value is present.
|
||||
func adjustAPIKeyCodexModelsManifest(body []byte) ([]byte, error) {
|
||||
func adjustAPIKeyCodexModelsManifest(body []byte, account *Account) ([]byte, error) {
|
||||
var envelope map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &envelope); err != nil {
|
||||
return nil, fmt.Errorf("decode JSON object: %w", err)
|
||||
@@ -1943,7 +2010,14 @@ func adjustAPIKeyCodexModelsManifest(body []byte) ([]byte, error) {
|
||||
if err := json.Unmarshal(model["slug"], &slug); err != nil {
|
||||
continue
|
||||
}
|
||||
if _, targeted := apiKeyCodexModelsWithoutResponsesLite[slug]; !targeted {
|
||||
target := slug
|
||||
if account != nil {
|
||||
target = account.GetMappedModel(slug)
|
||||
}
|
||||
if isOpenAIGPT6AstraModel(target) {
|
||||
target = "gpt-6-astra"
|
||||
}
|
||||
if _, targeted := apiKeyCodexModelsWithoutResponsesLite[target]; !targeted {
|
||||
continue
|
||||
}
|
||||
var useResponsesLite bool
|
||||
@@ -1996,19 +2070,33 @@ func convertOpenAIModelListToCodexManifestForAccount(body []byte, account *Accou
|
||||
if !ok {
|
||||
return body
|
||||
}
|
||||
var entries []struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
var entries []map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &entries); err != nil {
|
||||
return body
|
||||
}
|
||||
modelIDs := make([]string, 0, len(entries))
|
||||
modelMetadata := make(map[string]codexModelMetadataOverride, len(entries))
|
||||
metadataModels := make(map[string]string, len(entries))
|
||||
for _, entry := range entries {
|
||||
id := strings.TrimSpace(entry.ID)
|
||||
var id string
|
||||
if err := json.Unmarshal(entry["id"], &id); err != nil {
|
||||
continue
|
||||
}
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
modelIDs = append(modelIDs, id)
|
||||
capabilityModel := id
|
||||
if account != nil {
|
||||
capabilityModel = account.GetMappedModel(id)
|
||||
}
|
||||
metadataModels[id] = capabilityModel
|
||||
capabilities := accountCodexToolCapabilities(account, capabilityModel)
|
||||
applyCodexToolCapabilities(capabilities, entry, true)
|
||||
modelMetadata[id] = codexModelMetadataOverride{UpstreamModelMetadata: UpstreamModelMetadata{
|
||||
CodexToolCapabilities: capabilities,
|
||||
}}
|
||||
}
|
||||
if len(modelIDs) == 0 {
|
||||
return body
|
||||
@@ -2025,7 +2113,7 @@ func convertOpenAIModelListToCodexManifestForAccount(body []byte, account *Accou
|
||||
searchToolModels[modelID] = true
|
||||
}
|
||||
}
|
||||
converted, err := buildCodexModelsManifest(modelIDs, imageInputModels, searchToolModels, nil, nil)
|
||||
converted, err := buildCodexModelsManifest(modelIDs, imageInputModels, searchToolModels, metadataModels, modelMetadata)
|
||||
if err != nil {
|
||||
return body
|
||||
}
|
||||
@@ -2038,7 +2126,7 @@ func convertOpenAIModelListToCodexManifestForAccount(body []byte, account *Accou
|
||||
// CompleteAPIKeyCodexModelsManifestForClient fills the complete ModelInfo
|
||||
// contract immediately before a group-specific API key manifest is returned.
|
||||
// The shared upstream cache remains independent from local group policy.
|
||||
func (s *OpenAIGatewayService) CompleteAPIKeyCodexModelsManifestForClient(manifest *CodexModelsManifest, account *Account) error {
|
||||
func (s *OpenAIGatewayService) CompleteAPIKeyCodexModelsManifestForClient(manifest *OpenAIModelsResponse, account *Account) error {
|
||||
if manifest == nil || account == nil || !account.IsOpenAIApiKey() || manifest.NotModified || len(manifest.Body) == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -2062,7 +2150,7 @@ func (s *OpenAIGatewayService) CompleteAPIKeyCodexModelsManifestForClient(manife
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body, err = adjustAPIKeyCodexModelsManifest(body)
|
||||
body, err = adjustAPIKeyCodexModelsManifest(body, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -2097,10 +2185,15 @@ func applySyncedAPIKeyCodexModelMetadata(body []byte, account *Account, overwrit
|
||||
continue
|
||||
}
|
||||
slug = strings.TrimSpace(slug)
|
||||
metadata, ok := snapshot.Models[slug]
|
||||
lookupModel := account.GetMappedModel(slug)
|
||||
metadata, ok := snapshot.Models[lookupModel]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if lookupModel != slug {
|
||||
metadata.DisplayName = ""
|
||||
metadata.Description = ""
|
||||
}
|
||||
|
||||
descriptor := newConfiguredCodexModelDescriptor(slug)
|
||||
applyUpstreamModelMetadataToCodexDescriptor(
|
||||
@@ -2133,7 +2226,8 @@ func applySyncedAPIKeyCodexModelMetadata(body []byte, account *Account, overwrit
|
||||
fields = append(fields, "context_window", "max_context_window")
|
||||
}
|
||||
|
||||
modelChanged := false
|
||||
// List conversion has already applied live fields over account capabilities.
|
||||
modelChanged := applyCodexToolCapabilities(model, metadata.CodexToolCapabilities, false)
|
||||
for _, field := range fields {
|
||||
value, exists := syncedFields[field]
|
||||
if !exists {
|
||||
@@ -2244,13 +2338,18 @@ func completeAPIKeyCodexModelsManifestMetadata(body []byte, completeAll bool, ac
|
||||
return nil, fmt.Errorf("decode default model %q: %w", slug, err)
|
||||
}
|
||||
|
||||
modelChanged := false
|
||||
capabilityModel := slug
|
||||
if account != nil {
|
||||
capabilityModel = account.GetMappedModel(slug)
|
||||
}
|
||||
capabilities := accountCodexToolCapabilities(account, capabilityModel)
|
||||
modelChanged := applyCodexToolCapabilities(model, capabilities, false)
|
||||
if completeDescriptor {
|
||||
merged, err := mergeMissingCodexModelFields(model, defaults)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("complete model %q: %w", slug, err)
|
||||
}
|
||||
modelChanged = merged
|
||||
modelChanged = merged || modelChanged
|
||||
}
|
||||
if forceOfficialImage {
|
||||
modalities, err := json.Marshal([]string{"text", "image"})
|
||||
@@ -2297,6 +2396,9 @@ func mergeMissingCodexModelFields(current, defaults map[string]json.RawMessage)
|
||||
changed := false
|
||||
for key, defaultValue := range defaults {
|
||||
currentValue, exists := current[key]
|
||||
if exists && stringSliceContains(codexToolCapabilityFields, key) {
|
||||
continue
|
||||
}
|
||||
if !exists || (bytes.Equal(bytes.TrimSpace(currentValue), []byte("null")) &&
|
||||
!bytes.Equal(bytes.TrimSpace(defaultValue), []byte("null"))) {
|
||||
current[key] = defaultValue
|
||||
@@ -2352,9 +2454,9 @@ func validateCodexModelsManifestEnvelope(body []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildCodexModelsManifestCacheKey(request codexModelsManifestRequest) string {
|
||||
func buildOpenAIModelsCacheKey(request openAIModelsRequest) string {
|
||||
hasher := sha256.New()
|
||||
_, _ = fmt.Fprintf(hasher, "%d\n%d\n%s\n%s\n", request.accountID, request.credentialAccountID, request.proxyURL, request.url)
|
||||
_, _ = fmt.Fprintf(hasher, "%d\n%d\n%t\n%s\n%s\n", request.accountID, request.credentialAccountID, request.standardModelsList, request.proxyURL, request.url)
|
||||
headerNames := make([]string, 0, len(request.headers))
|
||||
for name := range request.headers {
|
||||
headerNames = append(headerNames, name)
|
||||
@@ -2369,7 +2471,7 @@ func buildCodexModelsManifestCacheKey(request codexModelsManifestRequest) string
|
||||
return fmt.Sprintf("%x", hasher.Sum(nil))
|
||||
}
|
||||
|
||||
func cloneCodexModelsManifest(manifest *CodexModelsManifest) *CodexModelsManifest {
|
||||
func cloneOpenAIModelsResponse(manifest *OpenAIModelsResponse) *OpenAIModelsResponse {
|
||||
if manifest == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -2383,14 +2485,14 @@ func cloneCodexModelsManifest(manifest *CodexModelsManifest) *CodexModelsManifes
|
||||
return &cloned
|
||||
}
|
||||
|
||||
func codexModelsManifestForClient(manifest *CodexModelsManifest, ifNoneMatch string) *CodexModelsManifest {
|
||||
func openAIModelsResponseForClient(manifest *OpenAIModelsResponse, ifNoneMatch string) *OpenAIModelsResponse {
|
||||
if manifest == nil {
|
||||
return nil
|
||||
}
|
||||
if codexModelsManifestETagMatches(ifNoneMatch, manifest.ETag) {
|
||||
return &CodexModelsManifest{ETag: manifest.ETag, NotModified: true}
|
||||
return &OpenAIModelsResponse{ETag: manifest.ETag, NotModified: true}
|
||||
}
|
||||
return cloneCodexModelsManifest(manifest)
|
||||
return cloneOpenAIModelsResponse(manifest)
|
||||
}
|
||||
|
||||
func codexModelsManifestETagMatches(ifNoneMatch, etag string) bool {
|
||||
|
||||
@@ -349,6 +349,30 @@ func TestNewConfiguredCodexModelDescriptorUsesProviderMetadataAndSafeFallback(t
|
||||
require.Equal(t, []string{"low", "medium", "high", "xhigh", "max"}, effortsFromConfiguredCodexLevels(gpt56Luna.SupportedReasoningLevels))
|
||||
require.Equal(t, "medium", *gpt56Luna.DefaultReasoningLevel)
|
||||
|
||||
gpt6Astra := newConfiguredCodexModelDescriptor("gpt-6-astra")
|
||||
require.Equal(t, "GPT-6 Astra", gpt6Astra.DisplayName)
|
||||
require.NotNil(t, gpt6Astra.DefaultReasoningLevel)
|
||||
require.Equal(t, "medium", *gpt6Astra.DefaultReasoningLevel)
|
||||
require.Equal(t, []string{"low", "medium", "high", "xhigh", "max"}, effortsFromConfiguredCodexLevels(gpt6Astra.SupportedReasoningLevels))
|
||||
require.NotContains(t, gpt6Astra.SupportedReasoningLevels, configuredCodexReasoningLevel{Effort: "ultra"})
|
||||
require.NotContains(t, gpt6Astra.SupportedReasoningLevels, configuredCodexReasoningLevel{Effort: "none"})
|
||||
require.True(t, configuredCodexSupportsPriorityServiceTier("gpt-6-astra"))
|
||||
require.Equal(t, []configuredCodexServiceTier{{
|
||||
ID: "priority",
|
||||
Name: "Fast",
|
||||
Description: "Priority processing for lower latency.",
|
||||
}}, gpt6Astra.ServiceTiers)
|
||||
require.True(t, isOpenAICodexImageInputModel("gpt-6-astra"))
|
||||
require.True(t, isOpenAICodexReasoningGPTModel("openai/gpt-6-astra"))
|
||||
require.True(t, isOpenAIGPT6AstraModel("gpt-6-astra-2026-09-01"))
|
||||
require.False(t, isOpenAIGPT6AstraModel("gpt-6-other"))
|
||||
require.Equal(t, int64(1_050_000), gpt6Astra.ContextWindow)
|
||||
require.Equal(t, int64(1_050_000), gpt6Astra.MaxContextWindow)
|
||||
gpt6 := newConfiguredCodexModelDescriptor("gpt-6")
|
||||
require.Equal(t, "GPT-6 (Astra)", gpt6.DisplayName)
|
||||
require.Equal(t, []string{"low", "medium", "high", "xhigh", "max"}, effortsFromConfiguredCodexLevels(gpt6.SupportedReasoningLevels))
|
||||
require.Equal(t, int64(1_050_000), gpt6.ContextWindow)
|
||||
|
||||
gpt55 := newConfiguredCodexModelDescriptor("gpt-5.5")
|
||||
require.Equal(t, "GPT-5.5", gpt55.DisplayName)
|
||||
require.NotNil(t, gpt55.DefaultReasoningLevel)
|
||||
@@ -434,7 +458,7 @@ func TestBuildCodexModelsManifestAdvertisesPriorityServiceTierForFastGPTModels(t
|
||||
body, err := BuildCodexModelsManifest([]string{
|
||||
"gpt-5.4-mini",
|
||||
"gpt-5.5",
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-terra",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
models := decodeCodexManifestModels(t, body)
|
||||
@@ -452,6 +476,36 @@ func TestBuildCodexModelsManifestAdvertisesPriorityServiceTierForFastGPTModels(t
|
||||
}
|
||||
}
|
||||
|
||||
// Scenario: GPT-5.6 Sol 在 Fast 之外额外声明 ultrafast service tier。
|
||||
func TestBuildCodexModelsManifestAdvertisesUltrafastServiceTierForSol(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
body, err := BuildCodexModelsManifest([]string{
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
models := decodeCodexManifestModels(t, body)
|
||||
require.Len(t, models, 2)
|
||||
|
||||
wantTiers := []any{
|
||||
map[string]any{
|
||||
"id": "priority",
|
||||
"name": "Fast",
|
||||
"description": "Priority processing for lower latency.",
|
||||
},
|
||||
map[string]any{
|
||||
"id": "ultrafast",
|
||||
"name": "Ultrafast",
|
||||
"description": "Ultra-low latency processing.",
|
||||
},
|
||||
}
|
||||
for _, model := range models {
|
||||
require.Equal(t, wantTiers, model["service_tiers"])
|
||||
require.Nil(t, model["default_service_tier"])
|
||||
}
|
||||
}
|
||||
|
||||
// Scenario: 未明确支持 Fast 的型号不推测 service tier。
|
||||
func TestBuildCodexModelsManifestLeavesServiceTiersEmptyForOtherModels(t *testing.T) {
|
||||
t.Parallel()
|
||||
@@ -1027,7 +1081,7 @@ func TestMergeGroupConfiguredCodexModelsInjectsCurrentGroupAliases(t *testing.T)
|
||||
},
|
||||
},
|
||||
}}
|
||||
manifest := &CodexModelsManifest{
|
||||
manifest := &OpenAIModelsResponse{
|
||||
Body: []byte(`{"models":[{"slug":"gpt-5.6","display_name":"GPT-5.6","unknown":{"kept":true}}],"metadata":{"version":1}}`),
|
||||
}
|
||||
|
||||
@@ -1268,7 +1322,7 @@ func TestMergeGroupConfiguredCodexModelsFiltersAutoReviewByDefault(t *testing.T)
|
||||
|
||||
const groupID int64 = 74
|
||||
svc := &OpenAIGatewayService{accountRepo: codexModelsVisibilityAccountRepo{}}
|
||||
manifest := &CodexModelsManifest{
|
||||
manifest := &OpenAIModelsResponse{
|
||||
Body: []byte(`{"models":[{"slug":"codex-auto-review","visibility":"list"},{"slug":"codex-auto-future","visibility":"list"},{"slug":"gpt-image-2","visibility":"list"},{"slug":"gpt-5.6","visibility":"list"}]}`),
|
||||
}
|
||||
|
||||
@@ -1303,7 +1357,7 @@ func TestMergeGroupConfiguredCodexModelsFiltersAccountMappedAutoReviewByDefault(
|
||||
},
|
||||
},
|
||||
}}
|
||||
manifest := &CodexModelsManifest{
|
||||
manifest := &OpenAIModelsResponse{
|
||||
Body: []byte(`{"models":[{"slug":"codex-auto-review","visibility":"hide","model_messages":{"auto_review":{"enabled":true}}},{"slug":"gpt-5.6","visibility":"list"}]}`),
|
||||
}
|
||||
|
||||
@@ -1322,7 +1376,7 @@ func TestMergeGroupConfiguredCodexModelsKeepsExplicitAutoReviewSelection(t *test
|
||||
|
||||
const groupID int64 = 76
|
||||
svc := &OpenAIGatewayService{accountRepo: codexModelsVisibilityAccountRepo{}}
|
||||
manifest := &CodexModelsManifest{
|
||||
manifest := &OpenAIModelsResponse{
|
||||
Body: []byte(`{"models":[{"slug":"codex-auto-review","visibility":"list"},{"slug":"gpt-5.6","visibility":"list"}]}`),
|
||||
}
|
||||
group := &Group{
|
||||
@@ -1366,7 +1420,7 @@ func TestMergeGroupConfiguredCodexModelsHonorsCustomListAndFinalETag(t *testing.
|
||||
},
|
||||
}
|
||||
upstreamBody := []byte(`{"models":[{"slug":"gpt-5.6","display_name":"GPT-5.6"}]}`)
|
||||
manifest := &CodexModelsManifest{Body: upstreamBody}
|
||||
manifest := &OpenAIModelsResponse{Body: upstreamBody}
|
||||
|
||||
require.NoError(t, svc.MergeGroupConfiguredCodexModels(context.Background(), group, manifest, ""))
|
||||
models := decodeCodexManifestModels(t, manifest.Body)
|
||||
@@ -1374,7 +1428,7 @@ func TestMergeGroupConfiguredCodexModelsHonorsCustomListAndFinalETag(t *testing.
|
||||
requireCompleteConfiguredCodexModel(t, models[0], "deepseek-4-pro")
|
||||
|
||||
finalETag := manifest.ETag
|
||||
second := &CodexModelsManifest{Body: upstreamBody}
|
||||
second := &OpenAIModelsResponse{Body: upstreamBody}
|
||||
require.NoError(t, svc.MergeGroupConfiguredCodexModels(context.Background(), group, second, finalETag))
|
||||
require.True(t, second.NotModified)
|
||||
require.Empty(t, second.Body)
|
||||
@@ -1957,7 +2011,7 @@ func TestCompleteAPIKeyCodexModelsManifestForClientPreservesProviderMetadata(t *
|
||||
t.Parallel()
|
||||
|
||||
svc := &OpenAIGatewayService{}
|
||||
manifest := &CodexModelsManifest{
|
||||
manifest := &OpenAIModelsResponse{
|
||||
Body: []byte(`{"models":[{"slug":"grok-4.6","description":"Provider supplied","service_tiers":[{"id":"provider-priority","name":"Provider Fast","description":"Provider supplied tier."}],"model_messages":{"auto_review":{"enabled":true}},"truncation_policy":{"mode":"tokens"},"unknown":{"kept":true}}],"metadata":{"source":"upstream"}}`),
|
||||
}
|
||||
account := newCodexModelsAPIKeyTestAccount("https://upstream.example/v1")
|
||||
@@ -1993,7 +2047,7 @@ func TestCompleteAPIKeyCodexModelsManifestForClientUsesKnownGPTImageFallback(t *
|
||||
t.Parallel()
|
||||
|
||||
svc := &OpenAIGatewayService{}
|
||||
manifest := &CodexModelsManifest{Body: []byte(`{"models":[
|
||||
manifest := &OpenAIModelsResponse{Body: []byte(`{"models":[
|
||||
{"slug":"gpt-5.6-sol"},
|
||||
{"slug":"company-coding-model"},
|
||||
{"slug":"gpt-4o","input_modalities":["text"]}
|
||||
@@ -2068,7 +2122,7 @@ func TestCompleteAPIKeyCodexModelsManifestForClientFillsMissingProviderFieldsWit
|
||||
ContextWindow: 999_000,
|
||||
},
|
||||
}})
|
||||
manifest := &CodexModelsManifest{Body: []byte(`{"models":[{
|
||||
manifest := &OpenAIModelsResponse{Body: []byte(`{"models":[{
|
||||
"slug":"provider-model",
|
||||
"description":"Provider supplied",
|
||||
"context_window":64000,
|
||||
@@ -2147,12 +2201,12 @@ func TestCompleteAPIKeyCodexModelsManifestForClientMarksOnlyOfficialVisionGPTIma
|
||||
t.Parallel()
|
||||
|
||||
svc := &OpenAIGatewayService{}
|
||||
manifest := &CodexModelsManifest{Body: []byte(`{"models":[{"slug":"gpt-5.6-sol"},{"slug":"gpt-4o"},{"slug":"gpt-3.5-turbo"},{"slug":"gpt-4"}]}`)}
|
||||
manifest := &OpenAIModelsResponse{Body: []byte(`{"models":[{"slug":"gpt-6-astra"},{"slug":"gpt-5.6-sol"},{"slug":"gpt-4o"},{"slug":"gpt-3.5-turbo"},{"slug":"gpt-4"}]}`)}
|
||||
account := newCodexModelsAPIKeyTestAccount("")
|
||||
|
||||
require.NoError(t, svc.CompleteAPIKeyCodexModelsManifestForClient(manifest, account))
|
||||
models := decodeCodexManifestModels(t, manifest.Body)
|
||||
require.Len(t, models, 4)
|
||||
require.Len(t, models, 5)
|
||||
|
||||
bySlug := make(map[string]map[string]any, len(models))
|
||||
for _, model := range models {
|
||||
@@ -2160,7 +2214,7 @@ func TestCompleteAPIKeyCodexModelsManifestForClientMarksOnlyOfficialVisionGPTIma
|
||||
require.True(t, ok)
|
||||
bySlug[slug] = model
|
||||
}
|
||||
for _, slug := range []string{"gpt-5.6-sol", "gpt-4o"} {
|
||||
for _, slug := range []string{"gpt-6-astra", "gpt-5.6-sol", "gpt-4o"} {
|
||||
require.Equal(t, []any{"text", "image"}, bySlug[slug]["input_modalities"])
|
||||
require.Equal(t, true, bySlug[slug]["supports_image_detail_original"])
|
||||
}
|
||||
@@ -2175,7 +2229,7 @@ func TestCompleteAPIKeyCodexModelsManifestForClientFiltersOfficialNonAgentModels
|
||||
t.Parallel()
|
||||
|
||||
svc := &OpenAIGatewayService{}
|
||||
manifest := &CodexModelsManifest{Body: []byte(`{"models":[{"slug":"gpt-5.6-sol"},{"slug":"gpt-4o-realtime-preview"},{"slug":"gpt-4o-mini-tts"},{"slug":"text-embedding-3-large"},{"slug":"omni-moderation-latest"},{"slug":"o4-mini"},{"slug":"codex-mini-latest"}]}`)}
|
||||
manifest := &OpenAIModelsResponse{Body: []byte(`{"models":[{"slug":"gpt-5.6-sol"},{"slug":"gpt-4o-realtime-preview"},{"slug":"gpt-4o-mini-tts"},{"slug":"text-embedding-3-large"},{"slug":"omni-moderation-latest"},{"slug":"o4-mini"},{"slug":"codex-mini-latest"}]}`)}
|
||||
account := newCodexModelsAPIKeyTestAccount("")
|
||||
|
||||
require.NoError(t, svc.CompleteAPIKeyCodexModelsManifestForClient(manifest, account))
|
||||
@@ -2191,8 +2245,8 @@ func TestAdjustAPIKeyCodexModelsManifest(t *testing.T) {
|
||||
}{
|
||||
{
|
||||
name: "affected models disable responses lite and preserve unknown fields",
|
||||
body: `{"models":[{"slug":"gpt-5.6-sol","use_responses_lite":true,"unknown_model":{"enabled":true}},{"slug":"gpt-5.6-terra","use_responses_lite":true},{"slug":"gpt-5.6-luna","use_responses_lite":true}],"unknown_top":{"version":1}}`,
|
||||
want: `{"models":[{"slug":"gpt-5.6-sol","unknown_model":{"enabled":true},"use_responses_lite":false},{"slug":"gpt-5.6-terra","use_responses_lite":false},{"slug":"gpt-5.6-luna","use_responses_lite":false}],"unknown_top":{"version":1}}`,
|
||||
body: `{"models":[{"slug":"gpt-6-astra","use_responses_lite":true},{"slug":"gpt-5.6-sol","use_responses_lite":true,"unknown_model":{"enabled":true}},{"slug":"gpt-5.6-terra","use_responses_lite":true},{"slug":"gpt-5.6-luna","use_responses_lite":true}],"unknown_top":{"version":1}}`,
|
||||
want: `{"models":[{"slug":"gpt-6-astra","use_responses_lite":false},{"slug":"gpt-5.6-sol","unknown_model":{"enabled":true},"use_responses_lite":false},{"slug":"gpt-5.6-terra","use_responses_lite":false},{"slug":"gpt-5.6-luna","use_responses_lite":false}],"unknown_top":{"version":1}}`,
|
||||
},
|
||||
{
|
||||
name: "unaffected model unchanged",
|
||||
@@ -2208,7 +2262,7 @@ func TestAdjustAPIKeyCodexModelsManifest(t *testing.T) {
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := adjustAPIKeyCodexModelsManifest([]byte(tt.body))
|
||||
got, err := adjustAPIKeyCodexModelsManifest([]byte(tt.body), nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, string(got))
|
||||
})
|
||||
@@ -2493,13 +2547,13 @@ func TestFetchCodexModelsManifestAPIKeySharedRefreshSurvivesCallerCancellation(t
|
||||
}
|
||||
|
||||
secondResult := make(chan struct {
|
||||
manifest *CodexModelsManifest
|
||||
manifest *OpenAIModelsResponse
|
||||
err error
|
||||
}, 1)
|
||||
go func() {
|
||||
manifest, err := s.FetchCodexModelsManifest(context.Background(), account, "0.144.0", "")
|
||||
secondResult <- struct {
|
||||
manifest *CodexModelsManifest
|
||||
manifest *OpenAIModelsResponse
|
||||
err error
|
||||
}{manifest: manifest, err: err}
|
||||
}()
|
||||
@@ -2809,21 +2863,21 @@ func TestFetchCodexModelsManifestAPIKeyServesStaleWhileRefreshing(t *testing.T)
|
||||
t.Fatalf("initial fetch returned error: %v", err)
|
||||
}
|
||||
|
||||
s.codexModelsManifestCache.mu.Lock()
|
||||
for key, entry := range s.codexModelsManifestCache.entries {
|
||||
s.openAIModelsCache.mu.Lock()
|
||||
for key, entry := range s.openAIModelsCache.entries {
|
||||
entry.expiresAt = time.Now().Add(-time.Second)
|
||||
s.codexModelsManifestCache.entries[key] = entry
|
||||
s.openAIModelsCache.entries[key] = entry
|
||||
}
|
||||
s.codexModelsManifestCache.mu.Unlock()
|
||||
s.openAIModelsCache.mu.Unlock()
|
||||
|
||||
resultCh := make(chan struct {
|
||||
manifest *CodexModelsManifest
|
||||
manifest *OpenAIModelsResponse
|
||||
err error
|
||||
}, 1)
|
||||
go func() {
|
||||
manifest, err := s.FetchCodexModelsManifest(context.Background(), account, "0.144.0", "")
|
||||
resultCh <- struct {
|
||||
manifest *CodexModelsManifest
|
||||
manifest *OpenAIModelsResponse
|
||||
err error
|
||||
}{manifest: manifest, err: err}
|
||||
}()
|
||||
@@ -2834,7 +2888,7 @@ func TestFetchCodexModelsManifestAPIKeyServesStaleWhileRefreshing(t *testing.T)
|
||||
}
|
||||
|
||||
var staleResult struct {
|
||||
manifest *CodexModelsManifest
|
||||
manifest *OpenAIModelsResponse
|
||||
err error
|
||||
}
|
||||
select {
|
||||
@@ -2902,12 +2956,12 @@ func TestFetchCodexModelsManifestAPIKeyRevalidatesStaleETag(t *testing.T) {
|
||||
if _, err := s.FetchCodexModelsManifest(context.Background(), account, "0.144.0", ""); err != nil {
|
||||
t.Fatalf("initial fetch returned error: %v", err)
|
||||
}
|
||||
s.codexModelsManifestCache.mu.Lock()
|
||||
for key, entry := range s.codexModelsManifestCache.entries {
|
||||
s.openAIModelsCache.mu.Lock()
|
||||
for key, entry := range s.openAIModelsCache.entries {
|
||||
entry.expiresAt = time.Now().Add(-time.Second)
|
||||
s.codexModelsManifestCache.entries[key] = entry
|
||||
s.openAIModelsCache.entries[key] = entry
|
||||
}
|
||||
s.codexModelsManifestCache.mu.Unlock()
|
||||
s.openAIModelsCache.mu.Unlock()
|
||||
|
||||
manifest, err := s.FetchCodexModelsManifest(context.Background(), account, "0.144.0", "")
|
||||
if err != nil {
|
||||
@@ -2924,12 +2978,12 @@ func TestFetchCodexModelsManifestAPIKeyRevalidatesStaleETag(t *testing.T) {
|
||||
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for {
|
||||
s.codexModelsManifestCache.mu.Lock()
|
||||
s.openAIModelsCache.mu.Lock()
|
||||
fresh := false
|
||||
for _, entry := range s.codexModelsManifestCache.entries {
|
||||
for _, entry := range s.openAIModelsCache.entries {
|
||||
fresh = time.Now().Before(entry.expiresAt)
|
||||
}
|
||||
s.codexModelsManifestCache.mu.Unlock()
|
||||
s.openAIModelsCache.mu.Unlock()
|
||||
if fresh {
|
||||
break
|
||||
}
|
||||
@@ -3294,13 +3348,13 @@ func newCodexModelsOAuthCacheServer(t *testing.T, body string) (*httptest.Server
|
||||
}
|
||||
|
||||
func expireCodexModelsManifestCache(s *OpenAIGatewayService, age time.Duration) {
|
||||
s.codexModelsManifestCache.mu.Lock()
|
||||
for key, entry := range s.codexModelsManifestCache.entries {
|
||||
s.openAIModelsCache.mu.Lock()
|
||||
for key, entry := range s.openAIModelsCache.entries {
|
||||
entry.expiresAt = time.Now().Add(-age)
|
||||
entry.staleUntil = time.Now().Add(codexModelsManifestCacheStaleTTL - age)
|
||||
s.codexModelsManifestCache.entries[key] = entry
|
||||
entry.staleUntil = time.Now().Add(openAIModelsCacheStaleTTL - age)
|
||||
s.openAIModelsCache.entries[key] = entry
|
||||
}
|
||||
s.codexModelsManifestCache.mu.Unlock()
|
||||
s.openAIModelsCache.mu.Unlock()
|
||||
}
|
||||
|
||||
func TestFetchCodexModelsManifestOAuthFreshWindowZeroUpstreamRequests(t *testing.T) {
|
||||
@@ -3343,7 +3397,7 @@ func TestFetchCodexModelsManifestOAuthStaleServesOldValueAndRefreshesInBackgroun
|
||||
|
||||
expireCodexModelsManifestCache(s, 2*time.Minute)
|
||||
|
||||
resultCh := make(chan *CodexModelsManifest, 1)
|
||||
resultCh := make(chan *OpenAIModelsResponse, 1)
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
manifest, fetchErr := s.FetchCodexModelsManifest(context.Background(), account, "0.137.0", "")
|
||||
@@ -3373,9 +3427,9 @@ func TestFetchCodexModelsManifestOAuthStaleServesOldValueAndRefreshesInBackgroun
|
||||
if fetchErr == nil && manifest != nil && !manifest.NotModified {
|
||||
require.Contains(t, string(manifest.Body), `"new"`)
|
||||
}
|
||||
s.codexModelsManifestCache.mu.Lock()
|
||||
fresh := len(s.codexModelsManifestCache.entries) > 0
|
||||
s.codexModelsManifestCache.mu.Unlock()
|
||||
s.openAIModelsCache.mu.Lock()
|
||||
fresh := len(s.openAIModelsCache.entries) > 0
|
||||
s.openAIModelsCache.mu.Unlock()
|
||||
if fresh {
|
||||
break
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
)
|
||||
|
||||
var codexModelMap = map[string]string{
|
||||
"gpt-6-astra": "gpt-6-astra",
|
||||
"gpt-5.6-sol": "gpt-5.6-sol",
|
||||
"gpt-5.6-terra": "gpt-5.6-terra",
|
||||
"gpt-5.6-luna": "gpt-5.6-luna",
|
||||
|
||||
@@ -1361,6 +1361,10 @@ func TestApplyCodexOAuthTransform_EmptyInput(t *testing.T) {
|
||||
|
||||
func TestNormalizeCodexModel_Gpt53(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"gpt-6-astra": "gpt-6-astra",
|
||||
"openai/gpt-6-astra": "gpt-6-astra",
|
||||
"gpt-6": "gpt-6-astra",
|
||||
"openai/gpt-6": "gpt-6-astra",
|
||||
"gpt-5.4": "gpt-5.4",
|
||||
"gpt5.5": "gpt-5.5",
|
||||
"openai/gpt5.5": "gpt-5.5",
|
||||
|
||||
@@ -2271,3 +2271,43 @@ func TestForwardAsAnthropic_UpstreamRequestIgnoresClientCancel(t *testing.T) {
|
||||
require.NotNil(t, upstream.lastReq)
|
||||
require.NoError(t, upstream.lastReq.Context().Err())
|
||||
}
|
||||
|
||||
func TestForwardAsAnthropic_AstraContinuationRestoresHistoryAndDisablesUnsupportedSession(t *testing.T) {
|
||||
for _, message := range []string{
|
||||
"previous_response_id is not available for this user",
|
||||
"previous_response_id requires an OpenAI API-key account for HTTP requests",
|
||||
} {
|
||||
t.Run(message, func(t *testing.T) {
|
||||
encodedError, err := json.Marshal(map[string]any{"error": map[string]string{"message": message}})
|
||||
require.NoError(t, err)
|
||||
upstream := &httpUpstreamRecorder{responses: []*http.Response{
|
||||
{StatusCode: http.StatusBadRequest, Body: io.NopCloser(bytes.NewReader(encodedError))},
|
||||
openAICompatSSECompletedResponse("resp_replayed", "gpt-6-astra"),
|
||||
openAICompatSSECompletedResponse("resp_later", "gpt-6-astra"),
|
||||
}}
|
||||
svc := &OpenAIGatewayService{httpUpstream: upstream, cfg: &config.Config{}}
|
||||
account := rawGPT56ResponsesAPIKeyAccount("gpt-6-astra", "gpt-6-astra")
|
||||
svc.bindOpenAICompatSessionResponseID(context.Background(), nil, account, "astra-session", "resp_old")
|
||||
body := []byte(`{"model":"gpt-6-astra","max_tokens":16,"messages":[{"role":"user","content":"first"},{"role":"assistant","content":"ok"},{"role":"user","content":"second"}]}`)
|
||||
for i := 0; i < 2; i++ {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body))
|
||||
result, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "astra-session", "gpt-6-astra")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
}
|
||||
require.Len(t, upstream.bodies, 3)
|
||||
require.Equal(t, "resp_old", gjson.GetBytes(upstream.bodies[0], "previous_response_id").String())
|
||||
for _, sent := range upstream.bodies[1:] {
|
||||
require.False(t, gjson.GetBytes(sent, "previous_response_id").Exists())
|
||||
require.Equal(t, "astra-session", gjson.GetBytes(sent, "prompt_cache_key").String())
|
||||
require.Equal(t, int64(4), gjson.GetBytes(sent, "input.#").Int())
|
||||
require.Contains(t, gjson.GetBytes(sent, "input.0.content.0.text").String(), "<sub2api-claude-code-todo-guard>")
|
||||
require.Equal(t, "first", gjson.GetBytes(sent, "input.1.content.0.text").String())
|
||||
require.Equal(t, "second", gjson.GetBytes(sent, "input.3.content.0.text").String())
|
||||
}
|
||||
})
|
||||
}
|
||||
require.False(t, isOpenAICompatPreviousResponseUnsupported(http.StatusUnauthorized, "previous_response_id is not available for this user", nil))
|
||||
require.False(t, isOpenAICompatPreviousResponseUnsupported(http.StatusBadRequest, "The model is not available for this user", nil))
|
||||
}
|
||||
@@ -86,3 +86,22 @@ func detectOpenAICyberPolicy(payload []byte) (bool, string, string) {
|
||||
}
|
||||
return true, "cyber_policy", strings.TrimSpace(msg)
|
||||
}
|
||||
|
||||
func markOpenAICyberPolicyEvent(c *gin.Context, payload []byte, upstreamStatus int, usage *OpenAIUsage) bool {
|
||||
hit, code, message := detectOpenAICyberPolicy(payload)
|
||||
if !hit {
|
||||
return false
|
||||
}
|
||||
mark := CyberPolicyMark{
|
||||
Code: code,
|
||||
Message: message,
|
||||
Body: truncateString(string(payload), 4096),
|
||||
UpstreamStatus: upstreamStatus,
|
||||
}
|
||||
if usage != nil {
|
||||
mark.UpstreamInTok = usage.InputTokens
|
||||
mark.UpstreamOutTok = usage.OutputTokens
|
||||
}
|
||||
MarkOpsCyberPolicy(c, mark)
|
||||
return true
|
||||
}
|
||||
@@ -118,7 +118,7 @@ func (s *OpenAIGatewayService) ForwardEmbeddings(
|
||||
|
||||
upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody))
|
||||
upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg)
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(resp.StatusCode, upstreamMsg, respBody) {
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMsg, respBody) {
|
||||
upstreamDetail := ""
|
||||
if s.cfg != nil && s.cfg.Gateway.LogUpstreamErrorBody {
|
||||
maxBytes := s.cfg.Gateway.LogUpstreamErrorBodyMaxBytes
|
||||
|
||||
@@ -100,6 +100,9 @@ func TestEvaluateOpenAIFastPolicy_DefaultPassesKnownTiers(t *testing.T) {
|
||||
action, _ = svc.evaluateOpenAIFastPolicy(context.Background(), account, "gpt-5.5", OpenAIFastTierFlex)
|
||||
require.Equal(t, BetaPolicyActionPass, action)
|
||||
|
||||
action, _ = svc.evaluateOpenAIFastPolicy(context.Background(), account, "gpt-5.6-sol", OpenAIFastTierUltrafast)
|
||||
require.Equal(t, BetaPolicyActionPass, action)
|
||||
|
||||
// empty tier → pass
|
||||
action, _ = svc.evaluateOpenAIFastPolicy(context.Background(), account, "gpt-5.5", "")
|
||||
require.Equal(t, BetaPolicyActionPass, action)
|
||||
@@ -248,6 +251,16 @@ func TestApplyOpenAIFastPolicyToBody_UserScopedRuleOverridesGlobalRule(t *testin
|
||||
require.NotContains(t, string(updated), `"service_tier"`)
|
||||
}
|
||||
|
||||
func TestApplyOpenAIFastPolicyToBody_PriorityFilterLeavesUltrafast(t *testing.T) {
|
||||
svc := newOpenAIGatewayServiceWithSettings(t, openAIFastFilterPriorityPolicy())
|
||||
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}
|
||||
body := []byte(`{"model":"gpt-5.6-sol","service_tier":"ultrafast"}`)
|
||||
|
||||
updated, err := svc.applyOpenAIFastPolicyToBody(context.Background(), account, "gpt-5.6-sol", body)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, OpenAIFastTierUltrafast, gjson.GetBytes(updated, "service_tier").String())
|
||||
}
|
||||
|
||||
func TestApplyOpenAIFastPolicyToBody_ForcePriorityRewritesKnownTier(t *testing.T) {
|
||||
settings := &OpenAIFastPolicySettings{
|
||||
Rules: []OpenAIFastPolicyRule{{
|
||||
@@ -259,7 +272,7 @@ func TestApplyOpenAIFastPolicyToBody_ForcePriorityRewritesKnownTier(t *testing.T
|
||||
svc := newOpenAIGatewayServiceWithSettings(t, settings)
|
||||
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}
|
||||
|
||||
for _, tier := range []string{"flex", "auto", "default", "scale", "fast", "priority"} {
|
||||
for _, tier := range []string{"flex", "auto", "default", "scale", "fast", "priority", "ultrafast"} {
|
||||
body := []byte(`{"model":"gpt-5.5","service_tier":"` + tier + `"}`)
|
||||
updated, err := svc.applyOpenAIFastPolicyToBody(context.Background(), account, "gpt-5.5", body)
|
||||
require.NoError(t, err)
|
||||
@@ -480,19 +493,28 @@ func TestSetOpenAIFastPolicySettings_Validation(t *testing.T) {
|
||||
|
||||
// Valid settings persisted
|
||||
err = svc.SetOpenAIFastPolicySettings(context.Background(), &OpenAIFastPolicySettings{
|
||||
Rules: []OpenAIFastPolicyRule{{
|
||||
ServiceTier: OpenAIFastTierPriority,
|
||||
Action: OpenAIFastPolicyActionForcePriority,
|
||||
Scope: BetaPolicyScopeAll,
|
||||
UserIDs: []int64{42, 43},
|
||||
}},
|
||||
Rules: []OpenAIFastPolicyRule{
|
||||
{
|
||||
ServiceTier: OpenAIFastTierPriority,
|
||||
Action: OpenAIFastPolicyActionForcePriority,
|
||||
Scope: BetaPolicyScopeAll,
|
||||
UserIDs: []int64{42, 43},
|
||||
},
|
||||
{
|
||||
ServiceTier: OpenAIFastTierUltrafast,
|
||||
Action: BetaPolicyActionPass,
|
||||
Scope: BetaPolicyScopeAll,
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
got, err := svc.GetOpenAIFastPolicySettings(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got.Rules, 1)
|
||||
require.Len(t, got.Rules, 2)
|
||||
require.Equal(t, OpenAIFastTierPriority, got.Rules[0].ServiceTier)
|
||||
require.Equal(t, OpenAIFastPolicyActionForcePriority, got.Rules[0].Action)
|
||||
require.Equal(t, []int64{42, 43}, got.Rules[0].UserIDs)
|
||||
require.Equal(t, OpenAIFastTierUltrafast, got.Rules[1].ServiceTier)
|
||||
require.Equal(t, BetaPolicyActionPass, got.Rules[1].Action)
|
||||
}
|
||||
@@ -112,7 +112,7 @@ func TestWSResponseCreate_ForcePriorityRewritesKnownTier(t *testing.T) {
|
||||
svc := newOpenAIGatewayServiceWithSettings(t, settings)
|
||||
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}
|
||||
|
||||
for _, tier := range []string{"flex", "auto", "default", "scale", "fast", "priority"} {
|
||||
for _, tier := range []string{"flex", "auto", "default", "scale", "fast", "priority", "ultrafast"} {
|
||||
frame := []byte(`{"type":"response.create","model":"gpt-5.5","service_tier":"` + tier + `"}`)
|
||||
updated, blocked, err := svc.applyOpenAIFastPolicyToWSResponseCreate(context.Background(), account, "gpt-5.5", frame)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -43,7 +43,7 @@ func TestValidateOpenAIServiceTierField(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("official tiers pass through", func(t *testing.T) {
|
||||
for _, tier := range []string{"flex", "auto", "default", "scale"} {
|
||||
for _, tier := range []string{"flex", "auto", "default", "scale", "ultrafast"} {
|
||||
norm, err := ValidateOpenAIServiceTierField([]byte(`{"model":"gpt-5.5","service_tier":"` + tier + `"}`))
|
||||
require.NoError(t, err, "tier %q must be accepted", tier)
|
||||
require.Equal(t, tier, norm)
|
||||
|
||||
@@ -88,7 +88,7 @@ func (s *OpenAIGatewayService) failoverOpenAIUpstreamHTTPError(
|
||||
upstreamMsg string,
|
||||
upstreamModel string,
|
||||
) *UpstreamFailoverError {
|
||||
shouldFailover := s.shouldFailoverOpenAIUpstreamResponse(resp.StatusCode, upstreamMsg, respBody)
|
||||
shouldFailover := s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMsg, respBody)
|
||||
tempUnscheduled := false
|
||||
if c != nil && account != nil && account.Platform != PlatformGrok && !shouldFailover && !IsResponseCommitted(c) && s.rateLimitService != nil {
|
||||
tempUnscheduled = s.rateLimitService.CheckErrorPolicy(ctx, account, resp.StatusCode, respBody, upstreamModel) == ErrorPolicyTempUnscheduled
|
||||
@@ -223,6 +223,7 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest(
|
||||
// 账号级请求头覆写:放在所有内置默认头(含 Grok CLI 身份头)之后应用,
|
||||
// 使配置值获得除共享传输层强制头之外的最高优先级。
|
||||
account.ApplyHeaderOverrides(upstreamReq.Header)
|
||||
applyOpenCodeSessionHeader(c, account, targetURL, upstreamReq.Header)
|
||||
|
||||
proxyURL := ""
|
||||
if account.ProxyID != nil && account.Proxy != nil {
|
||||
|
||||
@@ -148,6 +148,11 @@ func TestNormalizeResponsesBodyServiceTier(t *testing.T) {
|
||||
require.Equal(t, "scale", tier)
|
||||
require.Equal(t, "scale", gjson.GetBytes(body, "service_tier").String())
|
||||
|
||||
body, tier, err = normalizeResponsesBodyServiceTier([]byte(`{"model":"gpt-5.6-sol","service_tier":"ultrafast"}`))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "ultrafast", tier)
|
||||
require.Equal(t, "ultrafast", gjson.GetBytes(body, "service_tier").String())
|
||||
|
||||
// 真未知值才会被删除。
|
||||
body, tier, err = normalizeResponsesBodyServiceTier([]byte(`{"model":"gpt-5.1","service_tier":"turbo"}`))
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -4,8 +4,10 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -350,9 +352,13 @@ func TestEstimateOpenAIInputTokens_CompareWithOpenAIAPI(t *testing.T) {
|
||||
|
||||
actual, err := callOpenAIInputTokensAPIForTest(client, apiKey, prepared.Request)
|
||||
if err != nil {
|
||||
// Live-API comparison only; invalid/expired local keys should skip, not fail CI.
|
||||
if strings.Contains(err.Error(), "status=401") || strings.Contains(err.Error(), "invalid_api_key") {
|
||||
t.Skipf("OPENAI_API_KEY rejected by OpenAI: %v", err)
|
||||
// This is an optional live-API comparison. Credential and transient
|
||||
// network failures must not make the deterministic unit suite fail.
|
||||
var netErr net.Error
|
||||
if strings.Contains(err.Error(), "status=401") ||
|
||||
strings.Contains(err.Error(), "invalid_api_key") ||
|
||||
errors.As(err, &netErr) {
|
||||
t.Skipf("OpenAI live comparison unavailable: %v", err)
|
||||
}
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
@@ -1136,7 +1136,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
)
|
||||
continue
|
||||
}
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(resp.StatusCode, upstreamMsg, respBody) {
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMsg, respBody) {
|
||||
upstreamDetail := ""
|
||||
if s.cfg != nil && s.cfg.Gateway.LogUpstreamErrorBody {
|
||||
maxBytes := s.cfg.Gateway.LogUpstreamErrorBodyMaxBytes
|
||||
@@ -1211,7 +1211,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
compactResp, compactBody := openAICompactFallbackErrorResponse(resp, signal)
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(compactResp.StatusCode, signal.message, compactBody) {
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(account, compactResp.StatusCode, signal.message, compactBody) {
|
||||
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
|
||||
ProxyID: opsUpstreamProxyID(account),
|
||||
ProxyName: opsUpstreamProxyName(account),
|
||||
@@ -1478,6 +1478,7 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin.
|
||||
|
||||
// 账号级请求头覆写(仅 openai api_key 账号启用时生效;OAuth 路径 no-op)
|
||||
account.ApplyHeaderOverrides(req.Header)
|
||||
applyOpenCodeSessionHeader(c, account, targetURL, req.Header)
|
||||
// x-codex-beta-features:按真实 Codex 的会话级行为补注(在账号级覆写之后,
|
||||
// 保证不被覆盖丢失)。
|
||||
applyOpenAICodexBetaFeatures(c, account, req.Header)
|
||||
|
||||
@@ -57,6 +57,9 @@ func (s *OpenAIGatewayService) forwardAnthropicViaNativeAnthropicEndpoint(
|
||||
}
|
||||
body = rewritten
|
||||
}
|
||||
if normalized, changed := NormalizeGLM53AnthropicThinking(body, upstreamModel); changed {
|
||||
body = normalized
|
||||
}
|
||||
|
||||
// 记录客户端请求的推理强度:优先 Claude 协议的 output_config.effort;
|
||||
// 缺失且 thinking 已启用时,按国产 passback-required 模型兜底为 high
|
||||
|
||||
@@ -4,6 +4,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// 国产供应商原生 Anthropic 直通路径(api_protocol=anthropic)的 reasoning_effort 记录。
|
||||
@@ -35,6 +37,13 @@ func nativeAnthropicTestAccount() *Account {
|
||||
}
|
||||
}
|
||||
|
||||
func nativeAnthropicGLMTestAccount() *Account {
|
||||
account := nativeAnthropicTestAccount()
|
||||
account.Name = "zhipu-native"
|
||||
account.Platform = PlatformZhipu
|
||||
return account
|
||||
}
|
||||
|
||||
func nativeAnthropicBufferedResponse() *http.Response {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
@@ -137,3 +146,70 @@ func TestNativeAnthropicPassthroughNoEffortStaysNil(t *testing.T) {
|
||||
require.NotNil(t, result)
|
||||
require.Nil(t, result.ReasoningEffort)
|
||||
}
|
||||
|
||||
func TestNativeAnthropicPassthroughNormalizesGLM53Thinking(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
tests := []struct {
|
||||
name string
|
||||
stream bool
|
||||
preference string
|
||||
wantEffort string
|
||||
}{
|
||||
{name: "disabled buffered", preference: `"thinking":{"type":"disabled"},`, wantEffort: "low"},
|
||||
{name: "off buffered", preference: `"thinking":{"type":"off"},`, wantEffort: "low"},
|
||||
{name: "none buffered", preference: `"thinking":{"type":"none"},`, wantEffort: "low"},
|
||||
{name: "enabled buffered", preference: `"thinking":{"type":"enabled"},`, wantEffort: "high"},
|
||||
{name: "enabled streaming", stream: true, preference: `"thinking":{"type":"enabled"},`, wantEffort: "high"},
|
||||
{name: "adaptive buffered", preference: `"thinking":{"type":"adaptive"},`, wantEffort: "high"},
|
||||
{name: "adaptive streaming", stream: true, preference: `"thinking":{"type":"adaptive"},`, wantEffort: "high"},
|
||||
{name: "minimal buffered", preference: `"output_config":{"effort":"minimal"},`, wantEffort: "low"},
|
||||
{name: "low buffered", preference: `"output_config":{"effort":"low"},`, wantEffort: "low"},
|
||||
{name: "medium streaming", stream: true, preference: `"output_config":{"effort":"medium"},`, wantEffort: "high"},
|
||||
{name: "high buffered", preference: `"output_config":{"effort":"high"},`, wantEffort: "high"},
|
||||
{name: "xhigh buffered", preference: `"output_config":{"effort":"xhigh"},`, wantEffort: "max"},
|
||||
{name: "max buffered", preference: `"output_config":{"effort":"max"},`, wantEffort: "max"},
|
||||
{name: "ultra buffered", preference: `"output_config":{"effort":"ultra"},`, wantEffort: "max"},
|
||||
{name: "output effort wins over thinking", preference: `"thinking":{"type":"adaptive"},"output_config":{"effort":"low"},`, wantEffort: "low"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
body := []byte(fmt.Sprintf(`{"model":"glm-5.3","max_tokens":32,"stream":%t,%s"messages":[{"role":"user","content":"hi"}]}`, tt.stream, tt.preference))
|
||||
response := nativeAnthropicBufferedResponse()
|
||||
if tt.stream {
|
||||
response = nativeAnthropicStreamResponse()
|
||||
}
|
||||
upstream := &httpUpstreamRecorder{resp: response}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
|
||||
_, err := svc.ForwardAsAnthropic(context.Background(),
|
||||
adaptiveProtocolTestContext("/v1/messages", body), nativeAnthropicGLMTestAccount(), body, "", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "enabled", gjson.GetBytes(upstream.lastBody, "thinking.type").String())
|
||||
require.Equal(t, tt.wantEffort, gjson.GetBytes(upstream.lastBody, "output_config.effort").String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeAnthropicPassthroughLeavesOtherThinkingUntouched(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
}{
|
||||
{name: "glm 5.3 unspecified", body: `{"model":"glm-5.3","max_tokens":32,"stream":false,"messages":[]}`},
|
||||
{name: "glm 5.2 disabled", body: `{"model":"glm-5.2","max_tokens":32,"stream":false,"thinking":{"type":"disabled"},"messages":[]}`},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
body := []byte(tt.body)
|
||||
upstream := &httpUpstreamRecorder{resp: nativeAnthropicBufferedResponse()}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
_, err := svc.ForwardAsAnthropic(context.Background(),
|
||||
adaptiveProtocolTestContext("/v1/messages", body), nativeAnthropicGLMTestAccount(), body, "", "")
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, tt.body, string(upstream.lastBody))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -721,6 +721,7 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough(
|
||||
|
||||
// 账号级请求头覆写(仅 openai api_key 账号启用时生效;OAuth 路径 no-op)
|
||||
account.ApplyHeaderOverrides(req.Header)
|
||||
applyOpenCodeSessionHeader(c, account, targetURL, req.Header)
|
||||
// x-codex-beta-features:按真实 Codex 的会话级行为补注(在账号级覆写之后,
|
||||
// 保证不被覆盖丢失)。
|
||||
applyOpenAICodexBetaFeatures(c, account, req.Header)
|
||||
|
||||
@@ -1466,9 +1466,8 @@ func TestNormalizeOpenAIServiceTier(t *testing.T) {
|
||||
|
||||
t.Run("openai official tiers preserved", func(t *testing.T) {
|
||||
// OpenAI 官方文档定义的合法 tier 值都应被透传保留,避免因白名单过窄
|
||||
// 静默剥离客户端显式发送的合法字段。Codex 客户端只发 priority/flex,
|
||||
// 所以扩大白名单对 Codex 流量零影响(见 codex-rs/core/src/client.rs)。
|
||||
for _, tier := range []string{"priority", "flex", "auto", "default", "scale"} {
|
||||
// 静默剥离客户端显式发送的合法字段。Codex 会发 priority/flex/ultrafast。
|
||||
for _, tier := range []string{"priority", "flex", "auto", "default", "scale", "ultrafast"} {
|
||||
got := normalizeOpenAIServiceTier(tier)
|
||||
require.NotNil(t, got, "tier %q should not be normalized to nil", tier)
|
||||
require.Equal(t, tier, *got)
|
||||
@@ -1487,6 +1486,7 @@ func TestExtractOpenAIServiceTier(t *testing.T) {
|
||||
require.Equal(t, "auto", *extractOpenAIServiceTier(map[string]any{"service_tier": "auto"}))
|
||||
require.Equal(t, "default", *extractOpenAIServiceTier(map[string]any{"service_tier": "default"}))
|
||||
require.Equal(t, "scale", *extractOpenAIServiceTier(map[string]any{"service_tier": "scale"}))
|
||||
require.Equal(t, "ultrafast", *extractOpenAIServiceTier(map[string]any{"service_tier": "ultrafast"}))
|
||||
require.Nil(t, extractOpenAIServiceTier(map[string]any{"service_tier": 1}))
|
||||
require.Nil(t, extractOpenAIServiceTier(nil))
|
||||
}
|
||||
@@ -1497,6 +1497,7 @@ func TestExtractOpenAIServiceTierFromBody(t *testing.T) {
|
||||
require.Equal(t, "auto", *extractOpenAIServiceTierFromBody([]byte(`{"service_tier":"auto"}`)))
|
||||
require.Equal(t, "default", *extractOpenAIServiceTierFromBody([]byte(`{"service_tier":"default"}`)))
|
||||
require.Equal(t, "scale", *extractOpenAIServiceTierFromBody([]byte(`{"service_tier":"scale"}`)))
|
||||
require.Equal(t, "ultrafast", *extractOpenAIServiceTierFromBody([]byte(`{"service_tier":"ultrafast"}`)))
|
||||
require.Nil(t, extractOpenAIServiceTierFromBody([]byte(`{"service_tier":"turbo"}`)))
|
||||
require.Nil(t, extractOpenAIServiceTierFromBody(nil))
|
||||
}
|
||||
|
||||
@@ -18,24 +18,28 @@ import (
|
||||
)
|
||||
|
||||
func (s *OpenAIGatewayService) validateUpstreamBaseURL(raw string) (string, error) {
|
||||
if s.cfg != nil && !s.cfg.Security.URLAllowlist.Enabled {
|
||||
normalized, err := urlvalidator.ValidateURLFormat(raw, s.cfg.Security.URLAllowlist.AllowInsecureHTTP)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid base_url: %w", err)
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
normalized, err := urlvalidator.ValidateHTTPSURL(raw, urlvalidator.ValidationOptions{
|
||||
AllowedHosts: s.cfg.Security.URLAllowlist.UpstreamHosts,
|
||||
RequireAllowlist: true,
|
||||
AllowPrivate: s.cfg.Security.URLAllowlist.AllowPrivateHosts,
|
||||
})
|
||||
normalized, err := s.validateOutboundURL(raw)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid base_url: %w", err)
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
// validateOutboundURL 按 security.url_allowlist 策略校验网关主动连接的出站 URL。
|
||||
func (s *OpenAIGatewayService) validateOutboundURL(raw string) (string, error) {
|
||||
if s.cfg == nil {
|
||||
return urlvalidator.ValidateURLFormat(raw, false)
|
||||
}
|
||||
if !s.cfg.Security.URLAllowlist.Enabled {
|
||||
return urlvalidator.ValidateURLFormat(raw, s.cfg.Security.URLAllowlist.AllowInsecureHTTP)
|
||||
}
|
||||
return urlvalidator.ValidateHTTPSURL(raw, urlvalidator.ValidationOptions{
|
||||
AllowedHosts: s.cfg.Security.URLAllowlist.UpstreamHosts,
|
||||
RequireAllowlist: true,
|
||||
AllowPrivate: s.cfg.Security.URLAllowlist.AllowPrivateHosts,
|
||||
})
|
||||
}
|
||||
|
||||
// buildOpenAIResponsesURL 组装 OpenAI Responses 端点。
|
||||
// - base 以 /v1 结尾:追加 /responses
|
||||
// - base 以其他版本段结尾(如 /v4):追加 /responses
|
||||
@@ -59,6 +63,9 @@ func shouldPreserveOpenAIResponsesNoneReasoningEffort(account *Account) bool {
|
||||
if account == nil {
|
||||
return false
|
||||
}
|
||||
if account.IsOpenAIPassthroughEnabled() {
|
||||
return true
|
||||
}
|
||||
if account.IsOpenAIOAuthLike() {
|
||||
return true
|
||||
}
|
||||
@@ -1435,12 +1442,12 @@ func normalizeOpenAIServiceTier(raw string) *string {
|
||||
if value == "fast" {
|
||||
value = "priority"
|
||||
}
|
||||
// 放过 OpenAI 官方文档定义的所有合法 tier 值:priority/flex/auto/default/scale。
|
||||
// 对 Codex 客户端零影响(Codex 只发 priority 或 flex,见 codex-rs/core/src/client.rs),
|
||||
// 但能让直连 OpenAI SDK 的用户透传 auto/default/scale 以便抓包/调试。
|
||||
// 真未知值仍返回 nil,由 normalizeResponsesBodyServiceTier 从 body 中删除。
|
||||
// 放过 OpenAI 官方文档定义的合法 tier 值,以及 Codex/API 新增的 ultrafast。
|
||||
// Codex 客户端会发 priority、flex 或 ultrafast;直连 OpenAI SDK 的用户还会
|
||||
// 透传 auto/default/scale。真未知值仍返回 nil,由
|
||||
// normalizeResponsesBodyServiceTier 从 body 中删除。
|
||||
switch value {
|
||||
case "priority", "flex", "auto", "default", "scale":
|
||||
case "priority", "flex", "auto", "default", "scale", OpenAIFastTierUltrafast:
|
||||
return &value
|
||||
default:
|
||||
return nil
|
||||
@@ -1457,7 +1464,7 @@ type ErrInvalidOpenAIServiceTier struct {
|
||||
}
|
||||
|
||||
func (e *ErrInvalidOpenAIServiceTier) Error() string {
|
||||
return fmt.Sprintf("invalid service_tier %q: must be one of auto, default, fast, flex, priority, scale", e.Value)
|
||||
return fmt.Sprintf("invalid service_tier %q: must be one of auto, default, fast, flex, priority, scale, ultrafast", e.Value)
|
||||
}
|
||||
|
||||
const invalidOpenAIServiceTierValueMaxLen = 64
|
||||
@@ -1475,7 +1482,7 @@ func boundInvalidOpenAIServiceTierValue(raw string) string {
|
||||
// - absent / null → valid, returns "" (field omitted keeps current behavior)
|
||||
// - "fast" → normalized to "priority" (the two are equivalent; the canonical
|
||||
// value is what reaches the OpenAI upstream)
|
||||
// - "priority" / "flex" / "auto" / "default" / "scale" → valid, returned as-is
|
||||
// - "priority" / "flex" / "auto" / "default" / "scale" / "ultrafast" → valid, returned as-is
|
||||
// - an explicitly present non-string value, an empty string, or any other
|
||||
// unknown value → *ErrInvalidOpenAIServiceTier (handler maps to HTTP 400),
|
||||
// matching OpenAI's enum validation semantics
|
||||
@@ -2162,7 +2169,7 @@ func normalizeOpenAIReasoningEffortForModel(raw, model string) string {
|
||||
// supportsOpenAIReasoningEffortMax reports model families whose upstream scale
|
||||
// has a distinct max level. Other models keep the legacy max -> xhigh behavior.
|
||||
func supportsOpenAIReasoningEffortMax(model string) bool {
|
||||
if isOpenAIGPT56Model(model) {
|
||||
if isOpenAIGPT6AstraModel(model) || isOpenAIGPT56Model(model) {
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -331,6 +331,23 @@ func TestFilterOpenAIResponsesNoneReasoningEffortForAccount(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterOpenAIResponsesNoneReasoningEffortForAccount_APIKeyAutomaticPassthroughPreservesRequest(t *testing.T) {
|
||||
body := []byte(`{"model":"qwen3.8-27b","input":"hi","max_output_tokens":20,"reasoning":{"effort":"none"},"presence_penalty":1.5}`)
|
||||
account := &Account{
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"base_url": "https://compat.example/v1",
|
||||
},
|
||||
Extra: map[string]any{"openai_passthrough": true},
|
||||
}
|
||||
|
||||
got, err := filterOpenAIResponsesNoneReasoningEffortForAccount(account, body)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, string(body), string(got))
|
||||
}
|
||||
|
||||
// Lite 工具迁移到 input[].additional_tools 后,仍应按有工具请求处理。
|
||||
func TestNormalizeOpenAIParallelToolCallsWithoutTools_KeepsResponsesLiteAdditionalTools(t *testing.T) {
|
||||
liteBody := []byte(`{"input":[{"type":"message","role":"user","content":"hi"},{"type":"additional_tools","tools":[{"type":"function","name":"spawn_agent"}]}],"parallel_tool_calls":false}`)
|
||||
|
||||
@@ -483,7 +483,7 @@ type OpenAIGatewayService struct {
|
||||
openaiWSRetryMetrics openAIWSRetryMetrics
|
||||
responseHeaderFilter *responseheaders.CompiledHeaderFilter
|
||||
codexSnapshotThrottle *accountWriteThrottle
|
||||
codexModelsManifestCache codexModelsManifestCache
|
||||
openAIModelsCache openAIModelsCache
|
||||
openaiCompatSessionResponses sync.Map
|
||||
openaiCompatAnthropicDigestSessions sync.Map
|
||||
// openaiCodexTurnStateOrigins: 下游会话 seed → openAICodexTurnStateOrigin,
|
||||
|
||||
@@ -356,9 +356,9 @@ func TestShouldFailoverOpenAIUpstreamResponseContextWindow502(t *testing.T) {
|
||||
svc := &OpenAIGatewayService{}
|
||||
body := []byte(`{"error":{"message":"Your input exceeds the context window of this model. Please adjust your input and try again.","type":"upstream_error","code":null}}`)
|
||||
|
||||
require.False(t, svc.shouldFailoverOpenAIUpstreamResponse(http.StatusBadGateway, "", body))
|
||||
require.True(t, svc.shouldFailoverOpenAIUpstreamResponse(http.StatusBadGateway, "temporary upstream outage", []byte(`{"error":{"message":"temporary upstream outage"}}`)))
|
||||
require.True(t, svc.shouldFailoverOpenAIUpstreamResponse(
|
||||
require.False(t, svc.shouldFailoverOpenAIUpstreamResponse(newOpenAIUpstreamErrorTestAccount(), http.StatusBadGateway, "", body))
|
||||
require.True(t, svc.shouldFailoverOpenAIUpstreamResponse(newOpenAIUpstreamErrorTestAccount(), http.StatusBadGateway, "temporary upstream outage", []byte(`{"error":{"message":"temporary upstream outage"}}`)))
|
||||
require.True(t, svc.shouldFailoverOpenAIUpstreamResponse(newOpenAIUpstreamErrorTestAccount(),
|
||||
http.StatusBadGateway,
|
||||
"temporary upstream outage",
|
||||
[]byte(`{"error":{"message":"temporary upstream outage"},"echo":"context_length_exceeded"}`),
|
||||
|
||||
@@ -250,7 +250,7 @@ func (s *OpenAIGatewayService) shouldFailoverUpstreamError(statusCode int) bool
|
||||
}
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) shouldFailoverOpenAIUpstreamResponse(statusCode int, upstreamMsg string, upstreamBody []byte) bool {
|
||||
func (s *OpenAIGatewayService) shouldFailoverOpenAIUpstreamResponse(account *Account, statusCode int, upstreamMsg string, upstreamBody []byte) bool {
|
||||
// cyber_policy is request-scoped even when an intermediary wraps the
|
||||
// provider response in a retryable 5xx status. Never punish or rotate the
|
||||
// selected credential for it.
|
||||
@@ -266,12 +266,46 @@ func (s *OpenAIGatewayService) shouldFailoverOpenAIUpstreamResponse(statusCode i
|
||||
if isOpenAIRequestBodyTooLargeError(statusCode, upstreamMsg, upstreamBody) {
|
||||
return true
|
||||
}
|
||||
// A missing model is account/provider availability, not a malformed client
|
||||
// request. Keep this unconditional exception inside the OpenAI-compatible
|
||||
// gateway and require an eligible account so Anthropic/Gemini paths retain
|
||||
// their existing opt-in 400 behavior.
|
||||
// A bare forwarding service has no account-selection owner to consume a
|
||||
// failover sentinel. In that mode (used by direct/single-account callers),
|
||||
// preserve the deterministic upstream 400 instead of returning an unwritten
|
||||
// retry signal. Managed gateway instances always have an account repository;
|
||||
// their handler can exclude this account and actually select another one.
|
||||
if s != nil && s.accountRepo != nil && account != nil && account.IsOpenAICompatible() && statusCode == http.StatusBadRequest &&
|
||||
isOpenAICompatibleModelNotFound400(upstreamBody) {
|
||||
return true
|
||||
}
|
||||
if s.shouldFailoverUpstreamError(statusCode) {
|
||||
return true
|
||||
}
|
||||
return isOpenAITransientProcessingError(statusCode, upstreamMsg, upstreamBody)
|
||||
}
|
||||
|
||||
func isOpenAICompatibleModelNotFound400(respBody []byte) bool {
|
||||
code := strings.TrimSpace(extractUpstreamErrorCode(respBody))
|
||||
if code != "" {
|
||||
return strings.EqualFold(code, "model_not_found")
|
||||
}
|
||||
|
||||
msg := strings.ToLower(strings.TrimSpace(extractUpstreamErrorMessage(respBody)))
|
||||
if msg == "" && !gjson.ValidBytes(respBody) {
|
||||
msg = strings.ToLower(strings.TrimSpace(string(respBody)))
|
||||
}
|
||||
return strings.Contains(msg, "unknown provider for model") ||
|
||||
strings.Contains(msg, "model not found") ||
|
||||
strings.Contains(msg, "model is not supported")
|
||||
}
|
||||
|
||||
// IsOpenAICompatibleModelNotFound400 reports whether an OpenAI-compatible 400
|
||||
// is an account-specific missing-model response eligible for failover.
|
||||
func IsOpenAICompatibleModelNotFound400(respBody []byte) bool {
|
||||
return isOpenAICompatibleModelNotFound400(respBody)
|
||||
}
|
||||
|
||||
// OpenAIRequestBodyTooLargeClientMessage is the fixed downstream message used
|
||||
// after all account-specific request body limit failovers are exhausted.
|
||||
const OpenAIRequestBodyTooLargeClientMessage = "Request payload is too large"
|
||||
|
||||
@@ -611,6 +611,7 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageCost(
|
||||
pricingAt,
|
||||
tokens,
|
||||
serviceTier,
|
||||
optionalStringValue(result.ReasoningEffort),
|
||||
longContextBillingGate,
|
||||
)
|
||||
if err == nil {
|
||||
@@ -704,6 +705,7 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageTokenCost(
|
||||
pricingAt time.Time,
|
||||
tokens UsageTokens,
|
||||
serviceTier string,
|
||||
reasoningEffort string,
|
||||
longContextBillingGate *bool,
|
||||
) (*CostBreakdown, error) {
|
||||
if s.resolver != nil && apiKey.Group != nil {
|
||||
@@ -711,17 +713,21 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageTokenCost(
|
||||
return s.billingService.CalculateCostUnified(CostInput{
|
||||
Ctx: ctx, Model: billingModel, GroupID: &gid, Group: apiKey.Group,
|
||||
Tokens: tokens, RequestCount: 1, RateMultiplier: multiplier, PricingAt: pricingAt,
|
||||
ServiceTier: serviceTier, Resolver: s.resolver,
|
||||
ServiceTier: serviceTier, ReasoningEffort: reasoningEffort, Resolver: s.resolver,
|
||||
LongContextBillingEnabled: longContextBillingGate,
|
||||
})
|
||||
}
|
||||
return s.billingService.calculateCostWithServiceTierPolicy(
|
||||
breakdown, err := s.billingService.calculateCostWithServiceTierPolicy(
|
||||
billingModel,
|
||||
tokens,
|
||||
multiplier,
|
||||
serviceTier,
|
||||
longContextBillingGate == nil || *longContextBillingGate,
|
||||
)
|
||||
if err == nil {
|
||||
applyCostBreakdownMultiplier(breakdown, maxReasoningEffortBillingMultiplier(billingModel, reasoningEffort, nil))
|
||||
}
|
||||
return breakdown, err
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) calculateOpenAIImageCost(
|
||||
|
||||
@@ -2,6 +2,8 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -14,13 +16,55 @@ import (
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestNormalizeOpenAIReasoningEffortForGPT56(t *testing.T) {
|
||||
func TestAstraForwardPreservesMaxInPayloadAndUsage(t *testing.T) {
|
||||
for _, requestedModel := range []string{"gpt-6-astra", "astra-public"} {
|
||||
for _, stream := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/stream=%t", requestedModel, stream), func(t *testing.T) {
|
||||
response := `{"id":"resp_astra","model":"gpt-6-astra","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":2}}`
|
||||
contentType := "application/json"
|
||||
if stream {
|
||||
response = "data: {\"type\":\"response.completed\",\"response\":" + response + "}\n\ndata: [DONE]\n\n"
|
||||
contentType = "text/event-stream"
|
||||
}
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(response))}}
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream}
|
||||
account := rawGPT56ResponsesAPIKeyAccount(requestedModel, "gpt-6-astra")
|
||||
body, err := json.Marshal(map[string]any{"model": requestedModel, "stream": stream, "input": "hello", "reasoning": map[string]string{"effort": "max"}})
|
||||
require.NoError(t, err)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(string(body)))
|
||||
SetOpenAIClientTransport(c, OpenAIClientTransportHTTP)
|
||||
result, err := svc.Forward(context.Background(), c, account, body)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, "gpt-6-astra", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
require.Equal(t, "max", gjson.GetBytes(upstream.lastBody, "reasoning.effort").String())
|
||||
require.NotNil(t, result.ReasoningEffort)
|
||||
require.Equal(t, "max", *result.ReasoningEffort)
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}}
|
||||
usageService := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil)
|
||||
err = usageService.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
|
||||
Result: result, Account: account, User: &User{ID: 21}, APIKey: &APIKey{ID: 22, Group: &Group{RateMultiplier: 1}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Equal(t, "max", *usageRepo.lastLog.ReasoningEffort)
|
||||
require.Equal(t, "max", *usageRepo.lastLog.RequestedReasoningEffort)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeOpenAIReasoningEffortForMaxCapableModels(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
model string
|
||||
want string
|
||||
}{
|
||||
{name: "Astra 保留 max", raw: "max", model: "gpt-6-astra", want: "max"},
|
||||
{name: "Sol 保留 max", raw: "max", model: "gpt-5.6-sol", want: "max"},
|
||||
{name: "Terra 保留 max", raw: "max", model: "openai/gpt-5.6-terra", want: "max"},
|
||||
{name: "Luna 后缀保留 max", raw: "max", model: "gpt-5.6-luna-2026-07-09", want: "max"},
|
||||
|
||||
@@ -650,7 +650,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesAPIKey(
|
||||
resp.Body = io.NopCloser(bytes.NewReader(respBody))
|
||||
upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody))
|
||||
upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg)
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(resp.StatusCode, upstreamMsg, respBody) {
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMsg, respBody) {
|
||||
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
|
||||
ProxyID: opsUpstreamProxyID(account),
|
||||
ProxyName: opsUpstreamProxyName(account),
|
||||
@@ -722,7 +722,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesAPIKey(
|
||||
ImageOutputSizes: imageOutputSizes,
|
||||
}, nil
|
||||
} else {
|
||||
nonStreamUsage, nonStreamCount, nonStreamSizes, err := s.handleOpenAIImagesNonStreamingResponse(resp, c)
|
||||
nonStreamUsage, nonStreamCount, nonStreamSizes, err := s.handleOpenAIImagesNonStreamingResponse(upstreamCtx, resp, c, account, parsed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -894,11 +894,18 @@ func cloneMultipartHeader(src textproto.MIMEHeader) textproto.MIMEHeader {
|
||||
return dst
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) handleOpenAIImagesNonStreamingResponse(resp *http.Response, c *gin.Context) (OpenAIUsage, int, []string, error) {
|
||||
func (s *OpenAIGatewayService) handleOpenAIImagesNonStreamingResponse(
|
||||
ctx context.Context,
|
||||
resp *http.Response,
|
||||
c *gin.Context,
|
||||
account *Account,
|
||||
parsed *OpenAIImagesRequest,
|
||||
) (OpenAIUsage, int, []string, error) {
|
||||
body, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, openAITooLargeError)
|
||||
if err != nil {
|
||||
return OpenAIUsage{}, 0, nil, err
|
||||
}
|
||||
body = s.backfillOpenAIImagesB64JSON(ctx, account, parsed, body)
|
||||
responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter)
|
||||
contentType := "application/json"
|
||||
if s.cfg != nil && !s.cfg.Security.ResponseHeaders.Enabled {
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
"github.com/Wei-Shaw/sub2api/internal/util/urlvalidator"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// AccountExtraImagesURLToB64JSON 是账户 extra 中的开关键。开启后,Images 端点的非流式响应里
|
||||
// b64_json 缺失或为空但 url 非空的图片项,由网关下载 url 内容并以 base64 回填到 b64_json。
|
||||
const AccountExtraImagesURLToB64JSON = "images_url_to_b64_json"
|
||||
|
||||
// openAIImageURLDownloadTimeout 是单张图片 url 下载的超时上限。
|
||||
const openAIImageURLDownloadTimeout = 60 * time.Second
|
||||
|
||||
// ImagesURLToB64JSONEnabled 返回账户是否开启了 url 转 b64_json 回填。
|
||||
func ImagesURLToB64JSONEnabled(account *Account) bool {
|
||||
return account != nil && account.getExtraBool(AccountExtraImagesURLToB64JSON)
|
||||
}
|
||||
|
||||
// backfillOpenAIImagesB64JSON 对 Images 端点的非流式响应做 url 转 b64_json 回填。
|
||||
//
|
||||
// 只处理 data[i].b64_json 缺失或为空且 url 非空的项;url 字段原样保留。
|
||||
// 单项失败仅记日志并保留该项原样,响应整体照常返回。
|
||||
// 客户端显式要求 response_format=url 时不做回填。
|
||||
func (s *OpenAIGatewayService) backfillOpenAIImagesB64JSON(
|
||||
ctx context.Context,
|
||||
account *Account,
|
||||
parsed *OpenAIImagesRequest,
|
||||
body []byte,
|
||||
) []byte {
|
||||
if !ImagesURLToB64JSONEnabled(account) {
|
||||
return body
|
||||
}
|
||||
if parsed != nil && parsed.ResponseFormat == "url" {
|
||||
return body
|
||||
}
|
||||
if len(body) == 0 || !gjson.ValidBytes(body) {
|
||||
return body
|
||||
}
|
||||
items := gjson.GetBytes(body, "data")
|
||||
if !items.IsArray() {
|
||||
return body
|
||||
}
|
||||
for index, item := range items.Array() {
|
||||
if !item.IsObject() {
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(item.Get("b64_json").String()) != "" {
|
||||
continue
|
||||
}
|
||||
rawURL := strings.TrimSpace(item.Get("url").String())
|
||||
if rawURL == "" {
|
||||
continue
|
||||
}
|
||||
encoded, err := s.fetchOpenAIImageURLBase64(ctx, account, rawURL)
|
||||
if err != nil {
|
||||
logger.LegacyPrintf(
|
||||
"service.openai_gateway",
|
||||
"[OpenAI] Images b64_json backfill skipped account_id=%d index=%d err=%s",
|
||||
account.ID,
|
||||
index,
|
||||
sanitizeUpstreamErrorMessage(err.Error()),
|
||||
)
|
||||
continue
|
||||
}
|
||||
updated, err := sjson.SetBytes(body, fmt.Sprintf("data.%d.b64_json", index), encoded)
|
||||
if err != nil {
|
||||
logger.LegacyPrintf(
|
||||
"service.openai_gateway",
|
||||
"[OpenAI] Images b64_json backfill skipped account_id=%d index=%d err=%s",
|
||||
account.ID,
|
||||
index,
|
||||
sanitizeUpstreamErrorMessage(err.Error()),
|
||||
)
|
||||
continue
|
||||
}
|
||||
body = updated
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// fetchOpenAIImageURLBase64 取得图片 url 内容的标准 base64 编码。
|
||||
// data: 形式的 url 直接取其 base64 载荷;其余 url 先沿用 base_url 的出站 URL 策略校验,
|
||||
// 再无条件拒绝回环、私网、链路本地等目的地(含重定向的每一跳),经账户代理下载,
|
||||
// 大小上限与 OAuth 路径的单图下载一致,且前 512 字节须嗅探为 png/jpeg/webp/gif。
|
||||
func (s *OpenAIGatewayService) fetchOpenAIImageURLBase64(ctx context.Context, account *Account, rawURL string) (string, error) {
|
||||
if strings.HasPrefix(strings.ToLower(rawURL), "data:") {
|
||||
if encoded := normalizeOpenAIImageBase64(rawURL); encoded != "" {
|
||||
return encoded, nil
|
||||
}
|
||||
return "", errors.New("data url payload is not valid base64")
|
||||
}
|
||||
if s == nil || s.httpUpstream == nil {
|
||||
return "", errors.New("http upstream is not configured")
|
||||
}
|
||||
downloadURL, err := s.validateOutboundURL(rawURL)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid image url: %w", err)
|
||||
}
|
||||
if err := rejectPrivateImageHost(downloadURL); err != nil {
|
||||
return "", err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(WithHTTPUpstreamPublicHostsOnly(ctx), openAIImageURLDownloadTimeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("build image download request: %w", err)
|
||||
}
|
||||
req.Header.Set("Accept", "image/*,*/*;q=0.8")
|
||||
proxyURL := ""
|
||||
if account.ProxyID != nil && account.Proxy != nil {
|
||||
proxyURL = account.Proxy.URL()
|
||||
}
|
||||
resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("download image: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||
return "", fmt.Errorf("download image: unexpected status %d", resp.StatusCode)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, openAIImageMaxDownloadBytes+1))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read image body: %w", err)
|
||||
}
|
||||
if int64(len(data)) > openAIImageMaxDownloadBytes {
|
||||
return "", fmt.Errorf("downloaded image exceeds %d bytes", openAIImageMaxDownloadBytes)
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return "", errors.New("download image: empty body")
|
||||
}
|
||||
if !isBackfillImageContent(data) {
|
||||
return "", errors.New("download image: content is not an allowed image format")
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
// rejectPrivateImageHost 拒绝主机为 localhost 或回环、私网、链路本地、未指定地址字面量的下载 URL。
|
||||
// 不受 security.url_allowlist 配置影响;域名的解析结果与重定向的每一跳由上游客户端按
|
||||
// WithHTTPUpstreamPublicHostsOnly 标记校验。
|
||||
func rejectPrivateImageHost(downloadURL string) error {
|
||||
parsed, err := url.Parse(downloadURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid image url: %w", err)
|
||||
}
|
||||
if host := parsed.Hostname(); urlvalidator.IsBlockedHost(host) {
|
||||
return fmt.Errorf("image url host is not allowed: %s", host)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// openAIImageBackfillContentTypes 是允许回填的图片格式,以字节嗅探结果为准,响应头不作为依据。
|
||||
var openAIImageBackfillContentTypes = map[string]struct{}{
|
||||
"image/png": {},
|
||||
"image/jpeg": {},
|
||||
"image/webp": {},
|
||||
"image/gif": {},
|
||||
}
|
||||
|
||||
// isBackfillImageContent 报告 data 的前 512 字节是否嗅探为允许回填的图片格式。
|
||||
func isBackfillImageContent(data []byte) bool {
|
||||
_, ok := openAIImageBackfillContentTypes[detectedImageContentType(data)]
|
||||
return ok
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// 8 字节 PNG 魔数足以让字节嗅探判定为 image/png。
|
||||
var b64BackfillPNGBytes = []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n', 0, 0, 0, 0}
|
||||
|
||||
func b64BackfillImageResponse(status int, contentType string, payload []byte) *http.Response {
|
||||
header := http.Header{}
|
||||
if contentType != "" {
|
||||
header.Set("Content-Type", contentType)
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: status,
|
||||
Header: header,
|
||||
Body: io.NopCloser(bytes.NewReader(payload)),
|
||||
}
|
||||
}
|
||||
|
||||
func b64BackfillAccount(enabled bool) *Account {
|
||||
account := &Account{
|
||||
ID: 7,
|
||||
Name: "openai-apikey",
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"base_url": "https://relay.example.com/v1",
|
||||
},
|
||||
}
|
||||
if enabled {
|
||||
account.Extra = map[string]any{AccountExtraImagesURLToB64JSON: true}
|
||||
}
|
||||
return account
|
||||
}
|
||||
|
||||
func TestImagesURLToB64JSONEnabled(t *testing.T) {
|
||||
require.False(t, ImagesURLToB64JSONEnabled(nil))
|
||||
require.False(t, ImagesURLToB64JSONEnabled(&Account{}))
|
||||
require.False(t, ImagesURLToB64JSONEnabled(&Account{Extra: map[string]any{AccountExtraImagesURLToB64JSON: "true"}}))
|
||||
require.False(t, ImagesURLToB64JSONEnabled(&Account{Extra: map[string]any{AccountExtraImagesURLToB64JSON: false}}))
|
||||
require.True(t, ImagesURLToB64JSONEnabled(&Account{Extra: map[string]any{AccountExtraImagesURLToB64JSON: true}}))
|
||||
}
|
||||
|
||||
func TestBackfillOpenAIImagesB64JSON(t *testing.T) {
|
||||
wantB64 := base64.StdEncoding.EncodeToString(b64BackfillPNGBytes)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
enabled bool
|
||||
parsed *OpenAIImagesRequest
|
||||
body string
|
||||
upstream *httpUpstreamRecorder
|
||||
wantB64 []string
|
||||
wantDownloads int
|
||||
}{
|
||||
{
|
||||
name: "开关关闭时原样返回",
|
||||
enabled: false,
|
||||
body: `{"created":1,"data":[{"url":"https://cdn.example.com/a.png"}]}`,
|
||||
upstream: &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes)},
|
||||
wantB64: []string{""},
|
||||
wantDownloads: 0,
|
||||
},
|
||||
{
|
||||
name: "缺少 b64_json 且有 url 时下载回填并保留 url",
|
||||
enabled: true,
|
||||
body: `{"created":1,"data":[{"url":"https://cdn.example.com/a.png","revised_prompt":"a cat"}]}`,
|
||||
upstream: &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes)},
|
||||
wantB64: []string{wantB64},
|
||||
wantDownloads: 1,
|
||||
},
|
||||
{
|
||||
name: "b64_json 为空串时同样回填",
|
||||
enabled: true,
|
||||
body: `{"created":1,"data":[{"b64_json":"","url":"https://cdn.example.com/a.png"}]}`,
|
||||
upstream: &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes)},
|
||||
wantB64: []string{wantB64},
|
||||
wantDownloads: 1,
|
||||
},
|
||||
{
|
||||
name: "b64_json 已有值时不下载",
|
||||
enabled: true,
|
||||
body: `{"created":1,"data":[{"b64_json":"aW1n","url":"https://cdn.example.com/a.png"}]}`,
|
||||
upstream: &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes)},
|
||||
wantB64: []string{"aW1n"},
|
||||
wantDownloads: 0,
|
||||
},
|
||||
{
|
||||
name: "多项混合时只回填缺失项",
|
||||
enabled: true,
|
||||
body: `{"created":1,"data":[{"b64_json":"aW1n"},{"url":"https://cdn.example.com/b.png"},{"revised_prompt":"none"}]}`,
|
||||
upstream: &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes)},
|
||||
wantB64: []string{"aW1n", wantB64, ""},
|
||||
wantDownloads: 1,
|
||||
},
|
||||
{
|
||||
name: "data URL 直接取载荷不下载",
|
||||
enabled: true,
|
||||
body: `{"created":1,"data":[{"url":"data:image/png;base64,` + wantB64 + `"}]}`,
|
||||
upstream: &httpUpstreamRecorder{},
|
||||
wantB64: []string{wantB64},
|
||||
wantDownloads: 0,
|
||||
},
|
||||
{
|
||||
name: "客户端显式要求 url 时不回填",
|
||||
enabled: true,
|
||||
parsed: &OpenAIImagesRequest{ResponseFormat: "url"},
|
||||
body: `{"created":1,"data":[{"url":"https://cdn.example.com/a.png"}]}`,
|
||||
upstream: &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes)},
|
||||
wantB64: []string{""},
|
||||
wantDownloads: 0,
|
||||
},
|
||||
{
|
||||
name: "下载非 2xx 时保留原样",
|
||||
enabled: true,
|
||||
body: `{"created":1,"data":[{"url":"https://cdn.example.com/a.png"}]}`,
|
||||
upstream: &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusNotFound, "text/plain", []byte("gone"))},
|
||||
wantB64: []string{""},
|
||||
wantDownloads: 1,
|
||||
},
|
||||
{
|
||||
name: "下载内容不是图片时保留原样",
|
||||
enabled: true,
|
||||
body: `{"created":1,"data":[{"url":"https://cdn.example.com/a.png"}]}`,
|
||||
upstream: &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "text/html", []byte("<html>login required</html>"))},
|
||||
wantB64: []string{""},
|
||||
wantDownloads: 1,
|
||||
},
|
||||
{
|
||||
name: "响应头未声明图片类型但字节嗅探为图片时回填",
|
||||
enabled: true,
|
||||
body: `{"created":1,"data":[{"url":"https://cdn.example.com/a"}]}`,
|
||||
upstream: &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "application/octet-stream", b64BackfillPNGBytes)},
|
||||
wantB64: []string{wantB64},
|
||||
wantDownloads: 1,
|
||||
},
|
||||
{
|
||||
name: "响应头声明图片但字节不是图片时保留原样",
|
||||
enabled: true,
|
||||
body: `{"created":1,"data":[{"url":"https://cdn.example.com/a.png"}]}`,
|
||||
upstream: &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "image/svg+xml", []byte(`<svg xmlns="http://www.w3.org/2000/svg"></svg>`))},
|
||||
wantB64: []string{""},
|
||||
wantDownloads: 1,
|
||||
},
|
||||
{
|
||||
name: "非 http(s) 协议的 url 不下载",
|
||||
enabled: true,
|
||||
body: `{"created":1,"data":[{"url":"ftp://cdn.example.com/a.png"}]}`,
|
||||
upstream: &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes)},
|
||||
wantB64: []string{""},
|
||||
wantDownloads: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: tt.upstream}
|
||||
got := svc.backfillOpenAIImagesB64JSON(context.Background(), b64BackfillAccount(tt.enabled), tt.parsed, []byte(tt.body))
|
||||
require.True(t, gjson.ValidBytes(got))
|
||||
items := gjson.GetBytes(got, "data").Array()
|
||||
require.Len(t, items, len(tt.wantB64))
|
||||
for i, want := range tt.wantB64 {
|
||||
require.Equal(t, want, items[i].Get("b64_json").String(), "data.%d.b64_json", i)
|
||||
}
|
||||
require.Len(t, tt.upstream.requests, tt.wantDownloads)
|
||||
// 除 b64_json 外的字段必须原样保留。
|
||||
original := gjson.Parse(tt.body)
|
||||
original.Get("data").ForEach(func(key, item gjson.Result) bool {
|
||||
item.ForEach(func(field, value gjson.Result) bool {
|
||||
if field.String() == "b64_json" {
|
||||
return true
|
||||
}
|
||||
require.Equal(t, value.Raw, gjson.GetBytes(got, "data."+key.String()+"."+field.String()).Raw)
|
||||
return true
|
||||
})
|
||||
return true
|
||||
})
|
||||
require.Equal(t, original.Get("created").Raw, gjson.GetBytes(got, "created").Raw)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackfillOpenAIImagesB64JSON_DownloadRequestShape(t *testing.T) {
|
||||
upstream := &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes)}
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream}
|
||||
account := b64BackfillAccount(true)
|
||||
proxyID := int64(3)
|
||||
account.ProxyID = &proxyID
|
||||
account.Proxy = &Proxy{Protocol: "http", Host: "127.0.0.1", Port: 7890}
|
||||
|
||||
body := []byte(`{"created":1,"data":[{"url":"https://cdn.example.com/a.png?sig=abc"}]}`)
|
||||
got := svc.backfillOpenAIImagesB64JSON(context.Background(), account, nil, body)
|
||||
require.Equal(t, base64.StdEncoding.EncodeToString(b64BackfillPNGBytes), gjson.GetBytes(got, "data.0.b64_json").String())
|
||||
|
||||
require.Len(t, upstream.requests, 1)
|
||||
req := upstream.requests[0]
|
||||
require.Equal(t, http.MethodGet, req.Method)
|
||||
require.Equal(t, "https://cdn.example.com/a.png?sig=abc", req.URL.String())
|
||||
require.Equal(t, "http://127.0.0.1:7890", upstream.lastProxyURL)
|
||||
_, hasDeadline := req.Context().Deadline()
|
||||
require.True(t, hasDeadline)
|
||||
// 目的地与重定向各跳都必须解析到公网地址;重定向本身保持跟随。
|
||||
require.True(t, HTTPUpstreamPublicHostsOnly(req.Context()))
|
||||
require.False(t, HTTPUpstreamRedirectsDisabled(req.Context()))
|
||||
}
|
||||
|
||||
func TestBackfillOpenAIImagesB64JSON_RejectsPrivateHosts(t *testing.T) {
|
||||
upstream := &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes)}
|
||||
cfg := &config.Config{}
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream}
|
||||
account := b64BackfillAccount(true)
|
||||
|
||||
for _, rawURL := range []string{
|
||||
"http://localhost:8080/api/v1/admin/accounts",
|
||||
"http://Foo.LocalHost/a.png",
|
||||
"http://127.0.0.1:8080/a.png",
|
||||
"https://127.0.0.1/a.png",
|
||||
"http://[::1]:8080/a.png",
|
||||
"http://10.0.0.5/a.png",
|
||||
"http://172.16.0.9:9000/bucket/a.png",
|
||||
"http://192.168.1.10:9000/bucket/a.png",
|
||||
"http://169.254.169.254/latest/meta-data/",
|
||||
"http://0.0.0.0:8080/a.png",
|
||||
"http://[fe80::1]/a.png",
|
||||
"http://[::ffff:127.0.0.1]/a.png",
|
||||
} {
|
||||
body := `{"created":1,"data":[{"url":"` + rawURL + `"}]}`
|
||||
got := svc.backfillOpenAIImagesB64JSON(context.Background(), account, nil, []byte(body))
|
||||
require.Equal(t, body, string(got), "url=%s", rawURL)
|
||||
}
|
||||
require.Empty(t, upstream.requests, "private destinations must never be requested")
|
||||
|
||||
// 同一配置下公网主机照常下载,证明拒绝依据是目的地而非协议。
|
||||
got := svc.backfillOpenAIImagesB64JSON(context.Background(), account, nil, []byte(`{"created":1,"data":[{"url":"http://cdn.example.com/a.png"}]}`))
|
||||
require.Equal(t, base64.StdEncoding.EncodeToString(b64BackfillPNGBytes), gjson.GetBytes(got, "data.0.b64_json").String())
|
||||
require.Len(t, upstream.requests, 1)
|
||||
}
|
||||
|
||||
func TestIsBackfillImageContent(t *testing.T) {
|
||||
webp := append([]byte("RIFF\x24\x00\x00\x00WEBPVP8 "), make([]byte, 8)...)
|
||||
tests := []struct {
|
||||
name string
|
||||
data []byte
|
||||
want bool
|
||||
}{
|
||||
{name: "png", data: b64BackfillPNGBytes, want: true},
|
||||
{name: "jpeg", data: []byte{0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 'J', 'F', 'I', 'F', 0x00}, want: true},
|
||||
{name: "webp", data: webp, want: true},
|
||||
{name: "gif", data: []byte("GIF89a\x01\x00\x01\x00"), want: true},
|
||||
{name: "bmp 不在允许列表", data: []byte("BM\x00\x00\x00\x00\x00\x00\x00\x00"), want: false},
|
||||
{name: "ico 不在允许列表", data: []byte{0x00, 0x00, 0x01, 0x00, 0x01, 0x00}, want: false},
|
||||
{name: "svg 文本", data: []byte(`<svg xmlns="http://www.w3.org/2000/svg"></svg>`), want: false},
|
||||
{name: "html", data: []byte("<html>login required</html>"), want: false},
|
||||
{name: "json", data: []byte(`{"error":"unauthorized"}`), want: false},
|
||||
{name: "空", data: nil, want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, isBackfillImageContent(tt.data))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackfillOpenAIImagesB64JSON_NonObjectBodies(t *testing.T) {
|
||||
upstream := &httpUpstreamRecorder{resp: b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes)}
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream}
|
||||
account := b64BackfillAccount(true)
|
||||
|
||||
for _, body := range []string{``, `not json`, `{"created":1}`, `{"created":1,"data":{}}`, `{"created":1,"data":[]}`, `{"created":1,"data":["x"]}`} {
|
||||
got := svc.backfillOpenAIImagesB64JSON(context.Background(), account, nil, []byte(body))
|
||||
require.Equal(t, body, string(got), "body=%q", body)
|
||||
}
|
||||
require.Empty(t, upstream.requests)
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayServiceForwardImages_APIKeyBackfillsB64JSONFromURL(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","size":"1024x1024"}`)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("api_key", &APIKey{ID: 42})
|
||||
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{}}
|
||||
parsed, err := svc.ParseOpenAIImagesRequest(c, body)
|
||||
require.NoError(t, err)
|
||||
|
||||
upstream := &httpUpstreamRecorder{
|
||||
responses: []*http.Response{
|
||||
{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{
|
||||
"Content-Type": []string{"application/json"},
|
||||
"X-Request-Id": []string{"req_img_url"},
|
||||
},
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
`{"created":1710000000,"data":[{"url":"https://cdn.example.com/cat.png","revised_prompt":"a cat"}],"usage":{"input_tokens":10,"output_tokens":20}}`,
|
||||
)),
|
||||
},
|
||||
b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes),
|
||||
},
|
||||
}
|
||||
svc.httpUpstream = upstream
|
||||
|
||||
result, err := svc.ForwardImages(context.Background(), c, b64BackfillAccount(true), body, parsed, "")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, 1, result.ImageCount)
|
||||
require.False(t, result.Stream)
|
||||
|
||||
require.Len(t, upstream.requests, 2)
|
||||
require.Equal(t, http.MethodPost, upstream.requests[0].Method)
|
||||
require.Equal(t, "https://relay.example.com/v1/images/generations", upstream.requests[0].URL.String())
|
||||
require.Equal(t, http.MethodGet, upstream.requests[1].Method)
|
||||
require.Equal(t, "https://cdn.example.com/cat.png", upstream.requests[1].URL.String())
|
||||
require.True(t, HTTPUpstreamPublicHostsOnly(upstream.requests[1].Context()))
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
wantB64 := base64.StdEncoding.EncodeToString(b64BackfillPNGBytes)
|
||||
require.Equal(t, wantB64, gjson.Get(rec.Body.String(), "data.0.b64_json").String())
|
||||
require.Equal(t, "https://cdn.example.com/cat.png", gjson.Get(rec.Body.String(), "data.0.url").String())
|
||||
require.Equal(t, "a cat", gjson.Get(rec.Body.String(), "data.0.revised_prompt").String())
|
||||
require.Equal(t, int64(1710000000), gjson.Get(rec.Body.String(), "created").Int())
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayServiceForwardImages_APIKeyLeavesURLOnlyResponseWhenDisabled(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","size":"1024x1024"}`)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("api_key", &APIKey{ID: 42})
|
||||
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{}}
|
||||
parsed, err := svc.ParseOpenAIImagesRequest(c, body)
|
||||
require.NoError(t, err)
|
||||
|
||||
upstreamBody := `{"created":1710000000,"data":[{"url":"https://cdn.example.com/cat.png"}]}`
|
||||
upstream := &httpUpstreamRecorder{
|
||||
responses: []*http.Response{
|
||||
{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(upstreamBody)),
|
||||
},
|
||||
b64BackfillImageResponse(http.StatusOK, "image/png", b64BackfillPNGBytes),
|
||||
},
|
||||
}
|
||||
svc.httpUpstream = upstream
|
||||
|
||||
result, err := svc.ForwardImages(context.Background(), c, b64BackfillAccount(false), body, parsed, "")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, 1, result.ImageCount)
|
||||
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, upstreamBody, rec.Body.String())
|
||||
}
|
||||
@@ -1856,7 +1856,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth(
|
||||
resp.Body = io.NopCloser(bytes.NewReader(respBody))
|
||||
upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody))
|
||||
upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg)
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(resp.StatusCode, upstreamMsg, respBody) {
|
||||
if s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMsg, respBody) {
|
||||
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
|
||||
ProxyID: opsUpstreamProxyID(account),
|
||||
ProxyName: opsUpstreamProxyName(account),
|
||||
|
||||
@@ -199,7 +199,7 @@ func (s *OpenAIGatewayService) CreateLiveCall(
|
||||
selection.ReleaseFunc()
|
||||
if createErr != nil {
|
||||
s.releaseLiveLease(account.ID, identity.UserID, identity.APIKeyID, leaseID)
|
||||
if !s.shouldFailoverLiveCreateError(createErr) {
|
||||
if !s.shouldFailoverLiveCreateError(account, createErr) {
|
||||
return nil, createErr
|
||||
}
|
||||
excluded[account.ID] = struct{}{}
|
||||
@@ -245,13 +245,13 @@ func (s *OpenAIGatewayService) CreateLiveCall(
|
||||
return nil, ErrLiveUnavailable
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) shouldFailoverLiveCreateError(err error) bool {
|
||||
func (s *OpenAIGatewayService) shouldFailoverLiveCreateError(account *Account, err error) bool {
|
||||
var upstreamErr *UpstreamFailoverError
|
||||
if !errors.As(err, &upstreamErr) {
|
||||
// 凭证读取和网络传输错误都可能只影响当前账号或代理。
|
||||
return true
|
||||
}
|
||||
return s.shouldFailoverOpenAIUpstreamResponse(
|
||||
return s.shouldFailoverOpenAIUpstreamResponse(account,
|
||||
upstreamErr.StatusCode,
|
||||
"",
|
||||
upstreamErr.ResponseBody,
|
||||
|
||||
@@ -210,17 +210,18 @@ func TestLiveSidebandNormalCloseEndsCall(t *testing.T) {
|
||||
|
||||
func TestLiveCreateFailoverUsesExistingOpenAIPolicy(t *testing.T) {
|
||||
service := &OpenAIGatewayService{}
|
||||
require.False(t, service.shouldFailoverLiveCreateError(&UpstreamFailoverError{
|
||||
account := newOpenAIUpstreamErrorTestAccount()
|
||||
require.False(t, service.shouldFailoverLiveCreateError(account, &UpstreamFailoverError{
|
||||
StatusCode: http.StatusBadRequest,
|
||||
ResponseBody: []byte(`{"error":{"message":"invalid session"}}`),
|
||||
}))
|
||||
require.True(t, service.shouldFailoverLiveCreateError(&UpstreamFailoverError{
|
||||
require.True(t, service.shouldFailoverLiveCreateError(account, &UpstreamFailoverError{
|
||||
StatusCode: http.StatusForbidden,
|
||||
}))
|
||||
require.True(t, service.shouldFailoverLiveCreateError(&UpstreamFailoverError{
|
||||
require.True(t, service.shouldFailoverLiveCreateError(account, &UpstreamFailoverError{
|
||||
StatusCode: http.StatusBadGateway,
|
||||
}))
|
||||
require.True(t, service.shouldFailoverLiveCreateError(errors.New("transport failed")))
|
||||
require.True(t, service.shouldFailoverLiveCreateError(account, errors.New("transport failed")))
|
||||
}
|
||||
|
||||
func TestLiveCallIDFromLocation(t *testing.T) {
|
||||
|
||||
@@ -133,7 +133,9 @@ func isOpenAICompatPreviousResponseUnsupported(statusCode int, upstreamMsg strin
|
||||
}
|
||||
return strings.Contains(lower, "unsupported parameter") ||
|
||||
strings.Contains(lower, "only supported on responses websocket") ||
|
||||
strings.Contains(lower, "not supported")
|
||||
strings.Contains(lower, "not supported") ||
|
||||
strings.Contains(lower, "is not available for this user") ||
|
||||
strings.Contains(lower, "requires an openai api-key account for http requests")
|
||||
}
|
||||
if check(upstreamMsg) || check(string(upstreamBody)) {
|
||||
return true
|
||||
|
||||
@@ -65,6 +65,8 @@ func normalizeKnownOpenAICodexModel(model string) string {
|
||||
}
|
||||
|
||||
switch {
|
||||
case normalized == "gpt-6" || normalized == "gpt-6-astra":
|
||||
return "gpt-6-astra"
|
||||
case strings.Contains(normalized, "gpt-5.6-sol"):
|
||||
return "gpt-5.6-sol"
|
||||
case strings.Contains(normalized, "gpt-5.6-terra"):
|
||||
@@ -124,6 +126,13 @@ func isOpenAIGPT56Model(model string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// isOpenAIGPT6AstraModel reports GPT-6 Astra and dated/provider-prefixed variants.
|
||||
// The public "gpt-6" alias routes to Astra; unrelated GPT-6 families stay excluded.
|
||||
func isOpenAIGPT6AstraModel(model string) bool {
|
||||
normalized := canonicalizeOpenAIModelAliasSpelling(model)
|
||||
return normalized == "gpt-6" || normalized == "gpt-6-astra" || strings.HasPrefix(normalized, "gpt-6-astra-")
|
||||
}
|
||||
|
||||
func appendUsageBillingModelCandidate(candidates []string, seen map[string]struct{}, model string) []string {
|
||||
trimmed := strings.TrimSpace(model)
|
||||
if trimmed == "" {
|
||||
|
||||
@@ -6,6 +6,12 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNormalizeKnownOpenAICodexModelGPT6Astra(t *testing.T) {
|
||||
for _, model := range []string{"gpt-6-astra", "openai/gpt-6-astra", "gpt-6", "openai/gpt-6"} {
|
||||
require.Equal(t, "gpt-6-astra", normalizeKnownOpenAICodexModel(model))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeKnownOpenAICodexModel_BareGPT56RoutesToSol(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"gpt-5.6": "gpt-5.6-sol",
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
)
|
||||
|
||||
// FetchOpenAIModelsList discovers a single account's raw public model catalog.
|
||||
// API keys use the standard endpoint; OAuth reuses the authenticated, cached
|
||||
// Codex source. Account mappings and group policy are applied after this cache.
|
||||
func (s *OpenAIGatewayService) FetchOpenAIModelsList(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) {
|
||||
if s == nil || account == nil {
|
||||
return nil, infraerrors.New(http.StatusInternalServerError, "OPENAI_MODELS_ACCOUNT_REQUIRED", "OpenAI account is required")
|
||||
}
|
||||
credentialAccount, err := resolveCredentialAccount(ctx, s.accountRepo, account)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve model list credentials: %w", err)
|
||||
}
|
||||
if credentialAccount.IsOpenAIOAuth() {
|
||||
clientVersion := CodexCanonicalClientVersion()
|
||||
if s.settingService != nil {
|
||||
clientVersion = s.settingService.GetOpenAICodexClientVersion(ctx)
|
||||
}
|
||||
response, err := s.FetchCodexModelsManifest(ctx, account, clientVersion, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body, err := standardOpenAIModelsBody(response.Body, true)
|
||||
if err != nil {
|
||||
return nil, invalidOpenAIModelsList(err)
|
||||
}
|
||||
return &OpenAIModelsResponse{Body: body, ETag: codexModelsManifestBodyETag(body)}, nil
|
||||
}
|
||||
req, err := buildOpenAIAPIKeyModelsRequest(ctx, credentialAccount, s.validateUpstreamBaseURL)
|
||||
if err != nil {
|
||||
return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_MODELS_REQUEST_INVALID", "cannot build upstream model list request: %v", err)
|
||||
}
|
||||
request := openAIModelsRequest{
|
||||
url: req.URL.String(), headers: req.Header,
|
||||
proxyURL: upstreamModelsProxyURL(account), accountID: account.ID,
|
||||
credentialAccountID: credentialAccount.ID, credentialAccount: credentialAccount,
|
||||
accountConcurrency: account.Concurrency, useAPIKeyUpstream: true,
|
||||
standardModelsList: true,
|
||||
}
|
||||
response, err := s.fetchCachedOpenAIModels(ctx, request, func(fetchCtx context.Context, etag string) (*OpenAIModelsResponse, error) {
|
||||
response, err := s.fetchOpenAIModelsUpstream(fetchCtx, request, etag)
|
||||
if err != nil || response.NotModified {
|
||||
return response, err
|
||||
}
|
||||
body, err := standardOpenAIModelsBody(response.Body, false)
|
||||
if err != nil {
|
||||
return nil, invalidOpenAIModelsList(err)
|
||||
}
|
||||
response.Body = body
|
||||
response.ETag = codexModelsManifestBodyETag(body)
|
||||
return response, nil
|
||||
}, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.NotModified {
|
||||
return nil, invalidOpenAIModelsList(fmt.Errorf("upstream returned 304 without a cached catalog"))
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func invalidOpenAIModelsList(err error) error {
|
||||
return &codexModelsManifestUpstreamError{
|
||||
err: infraerrors.Newf(http.StatusBadGateway, "OPENAI_MODELS_UPSTREAM_INVALID", "invalid upstream model list: %v", err),
|
||||
retryable: true,
|
||||
}
|
||||
}
|
||||
|
||||
// modelCatalogEntries requires a real array. An empty array is authoritative;
|
||||
// absent fields, null and error envelopes must not become successful empty lists.
|
||||
func modelCatalogEntries(body []byte, field string) (map[string]json.RawMessage, []json.RawMessage, error) {
|
||||
var envelope map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &envelope); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
raw := bytes.TrimSpace(envelope[field])
|
||||
if len(raw) == 0 || raw[0] != '[' {
|
||||
return nil, nil, fmt.Errorf("missing or invalid %s array", field)
|
||||
}
|
||||
var entries []json.RawMessage
|
||||
if err := json.Unmarshal(raw, &entries); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return envelope, entries, nil
|
||||
}
|
||||
|
||||
func standardOpenAIModelsBody(body []byte, fromManifest bool) ([]byte, error) {
|
||||
field, idField := "data", "id"
|
||||
if fromManifest {
|
||||
field, idField = "models", "slug"
|
||||
}
|
||||
_, entries, err := modelCatalogEntries(body, field)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
models := make([]json.RawMessage, 0, len(entries))
|
||||
seen := make(map[string]struct{}, len(entries))
|
||||
for _, raw := range entries {
|
||||
var entry map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &entry); err != nil || entry == nil {
|
||||
return nil, fmt.Errorf("model entry must be an object")
|
||||
}
|
||||
var id string
|
||||
if err := json.Unmarshal(entry[idField], &id); err != nil || strings.TrimSpace(id) == "" {
|
||||
return nil, fmt.Errorf("model entry has no valid %s", idField)
|
||||
}
|
||||
id = strings.TrimSpace(id)
|
||||
if _, ok := seen[id]; ok || strings.Contains(id, "*") {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if fromManifest {
|
||||
entry = make(map[string]json.RawMessage)
|
||||
}
|
||||
entry["id"], _ = json.Marshal(id)
|
||||
entry["object"] = json.RawMessage(`"model"`)
|
||||
if len(entry["created"]) == 0 || string(entry["created"]) == "null" {
|
||||
entry["created"] = json.RawMessage(`0`)
|
||||
}
|
||||
if len(entry["owned_by"]) == 0 || string(entry["owned_by"]) == "null" {
|
||||
entry["owned_by"] = json.RawMessage(`"openai"`)
|
||||
}
|
||||
encoded, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
models = append(models, encoded)
|
||||
}
|
||||
return json.Marshal(struct {
|
||||
Object string `json:"object"`
|
||||
Data []json.RawMessage `json:"data"`
|
||||
}{Object: "list", Data: models})
|
||||
}
|
||||
|
||||
// projectAccountModelsBody applies the same public-name mapping to both model
|
||||
// representations while retaining the source entry's metadata. It never changes
|
||||
// the shared response and never synthesizes models absent from this account.
|
||||
func projectAccountModelsBody(body []byte, account *Account, group *Group, codex bool) ([]byte, error) {
|
||||
if account.IsOpenAIPassthroughEnabled() || len(account.GetModelMapping()) == 0 {
|
||||
return body, nil
|
||||
}
|
||||
field, idField := "data", "id"
|
||||
if codex {
|
||||
field, idField = "models", "slug"
|
||||
}
|
||||
envelope, entries, err := modelCatalogEntries(body, field)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byID := make(map[string]json.RawMessage, len(entries))
|
||||
candidates := make([]string, 0, len(entries))
|
||||
for _, raw := range entries {
|
||||
var entry map[string]json.RawMessage
|
||||
if json.Unmarshal(raw, &entry) != nil {
|
||||
continue
|
||||
}
|
||||
var id string
|
||||
if json.Unmarshal(entry[idField], &id) != nil {
|
||||
continue
|
||||
}
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" || strings.Contains(id, "*") {
|
||||
continue
|
||||
}
|
||||
// Apply the allowlist to public names after mapping, not upstream targets.
|
||||
if codex {
|
||||
if isCodexDedicatedMediaModel(id) {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(id, codexAutoModelPrefix) && len(FilterCodexModelIDsForGroup([]string{id}, group)) == 0 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if _, ok := byID[id]; !ok {
|
||||
byID[id] = raw
|
||||
candidates = append(candidates, id)
|
||||
}
|
||||
}
|
||||
aliases := make([]string, 0, len(account.GetModelMapping()))
|
||||
for alias := range account.GetModelMapping() {
|
||||
aliases = append(aliases, alias)
|
||||
}
|
||||
sort.Strings(aliases)
|
||||
candidates = append(candidates, aliases...)
|
||||
if group.ModelAllowlistEnabled() {
|
||||
candidates = append(candidates, group.ModelAllowlist.Models...)
|
||||
}
|
||||
projected := make([]json.RawMessage, 0, len(candidates))
|
||||
seen := make(map[string]struct{}, len(candidates))
|
||||
for _, id := range candidates {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" || strings.Contains(id, "*") {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
target, matched := account.ResolveMappedModel(id)
|
||||
raw, available := byID[strings.TrimSpace(target)]
|
||||
if !matched || !available {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
var entry map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &entry); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entry[idField], _ = json.Marshal(id)
|
||||
if id != target {
|
||||
entry["display_name"], _ = json.Marshal(id)
|
||||
}
|
||||
encoded, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
projected = append(projected, encoded)
|
||||
}
|
||||
envelope[field], err = json.Marshal(projected)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(envelope)
|
||||
}
|
||||
|
||||
// ApplyPinnedCodexModelsMapping is used by pinned discovery and its scheduler
|
||||
// fallback. The ordinary (non-pinned) Codex path retains its local catalog policy.
|
||||
func ApplyPinnedCodexModelsMapping(response *OpenAIModelsResponse, account *Account, group *Group) error {
|
||||
if group == nil || group.Platform != PlatformOpenAI || !group.CodexModelsManifestConfig.Enabled {
|
||||
return nil
|
||||
}
|
||||
body, err := projectAccountModelsBody(response.Body, account, group, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
response.Body = body
|
||||
response.ETag = codexModelsManifestBodyETag(body)
|
||||
return nil
|
||||
}
|
||||
|
||||
// FetchPinnedOpenAIModelsList includes explicitly enabled scheduler fallback.
|
||||
// An authoritative empty catalog is success, including after group filtering.
|
||||
func (s *OpenAIGatewayService) FetchPinnedOpenAIModelsList(ctx context.Context, group *Group, maxAccountSwitches int, ifNoneMatch string) (*OpenAIModelsResponse, *Account, error) {
|
||||
fetch := func(ctx context.Context, account *Account) (*OpenAIModelsResponse, error) {
|
||||
response, err := s.FetchOpenAIModelsList(ctx, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.Body, err = projectAccountModelsBody(response.Body, account, group, false)
|
||||
return response, err
|
||||
}
|
||||
results, err := s.fetchPinnedOpenAIModels(ctx, group, fetch)
|
||||
if err != nil && ctx.Err() == nil && group != nil && group.CodexModelsManifestConfig.FallbackToScheduler {
|
||||
results, err = s.fetchScheduledOpenAIModels(ctx, group, maxAccountSwitches, fetch)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
models := make([]json.RawMessage, 0)
|
||||
modelIDs := make([]string, 0)
|
||||
byID := make(map[string]json.RawMessage)
|
||||
for _, result := range results {
|
||||
_, entries, err := modelCatalogEntries(result.response.Body, "data")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, raw := range entries {
|
||||
var model struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &model); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if _, exists := byID[model.ID]; !exists {
|
||||
byID[model.ID] = raw
|
||||
modelIDs = append(modelIDs, model.ID)
|
||||
models = append(models, raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
if group.ModelAllowlistEnabled() {
|
||||
models = selectModelCatalogEntries(byID, group.ModelAllowlist.FilterForListing(modelIDs))
|
||||
}
|
||||
body, err := json.Marshal(struct {
|
||||
Object string `json:"object"`
|
||||
Data []json.RawMessage `json:"data"`
|
||||
}{Object: "list", Data: models})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
response := &OpenAIModelsResponse{Body: body, ETag: codexModelsManifestBodyETag(body)}
|
||||
return openAIModelsResponseForClient(response, ifNoneMatch), results[0].account, nil
|
||||
}
|
||||
|
||||
func selectModelCatalogEntries(byID map[string]json.RawMessage, selected []string) []json.RawMessage {
|
||||
models := make([]json.RawMessage, 0, len(selected))
|
||||
seen := make(map[string]struct{}, len(selected))
|
||||
for _, id := range selected {
|
||||
id = strings.TrimSpace(id)
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
if raw, exists := byID[id]; exists {
|
||||
models = append(models, raw)
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
}
|
||||
return models
|
||||
}
|
||||
|
||||
func orderPinnedCodexModelsBySelection(body []byte, allowlist GroupModelAllowlist) ([]byte, error) {
|
||||
envelope, entries, err := modelCatalogEntries(body, "models")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byID := make(map[string]json.RawMessage, len(entries))
|
||||
modelIDs := make([]string, 0, len(entries))
|
||||
for _, raw := range entries {
|
||||
var entry struct {
|
||||
Slug string `json:"slug"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &entry); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byID[entry.Slug] = raw
|
||||
modelIDs = append(modelIDs, entry.Slug)
|
||||
}
|
||||
envelope["models"], err = json.Marshal(selectModelCatalogEntries(byID, allowlist.FilterForListing(modelIDs)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(envelope)
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) fetchScheduledOpenAIModels(ctx context.Context, group *Group, maxSwitches int, fetch func(context.Context, *Account) (*OpenAIModelsResponse, error)) ([]pinnedOpenAIModelsResult, error) {
|
||||
if maxSwitches <= 0 {
|
||||
maxSwitches = 3
|
||||
}
|
||||
excluded := make(map[int64]struct{})
|
||||
var lastErr error
|
||||
for attempt := 0; attempt <= maxSwitches; attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account, err := s.SelectAccountForModelWithExclusions(ctx, &group.ID, "", "", excluded)
|
||||
if err != nil {
|
||||
if lastErr != nil {
|
||||
return nil, lastErr
|
||||
}
|
||||
return nil, ErrNoPinnedCodexModelsAccounts
|
||||
}
|
||||
response, err := fetch(ctx, account)
|
||||
if err == nil {
|
||||
return []pinnedOpenAIModelsResult{{account: account, response: response}}, nil
|
||||
}
|
||||
lastErr = err
|
||||
if !IsRetryableCodexModelsManifestError(err) {
|
||||
return nil, err
|
||||
}
|
||||
excluded[account.ID] = struct{}{}
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func ordinaryModelsUpstreamResponse(body string) *http.Response {
|
||||
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}
|
||||
}
|
||||
|
||||
func TestFetchOpenAIModelsListUsesStandardRequestAndIsolatesCodexCache(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
s := newCodexModelsAPIKeyTestService(&codexModelsHTTPUpstreamStub{do: func(req *http.Request, _ string, accountID int64, concurrency int) (*http.Response, error) {
|
||||
calls.Add(1)
|
||||
assert.EqualValues(t, 2, accountID)
|
||||
assert.EqualValues(t, 3, concurrency)
|
||||
assert.Equal(t, "/v1/models", req.URL.Path)
|
||||
assert.Equal(t, "value", getHeaderRaw(req.Header, "x-account-header"))
|
||||
if req.URL.Query().Has("client_version") {
|
||||
return ordinaryModelsUpstreamResponse(`{"models":[{"slug":"codex-only"}]}`), nil
|
||||
}
|
||||
assert.Empty(t, req.Header.Get("Originator"))
|
||||
assert.Empty(t, req.Header.Get("Version"))
|
||||
return ordinaryModelsUpstreamResponse(`{"object":"list","data":[{"id":"special-upstream-model","owned_by":"provider","created":1234,"custom":true},{"id":"gpt-image-1"},{"id":"text-embedding-3-large"}]}`), nil
|
||||
}})
|
||||
account := newCodexModelsAPIKeyTestAccount("https://models.example/v1")
|
||||
account.Credentials["header_overrides"] = map[string]any{"X-Account-Header": "value"}
|
||||
account.Credentials["header_override_enabled"] = true
|
||||
response, err := s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(response.Body), `"id":"gpt-image-1"`)
|
||||
require.Contains(t, string(response.Body), `"id":"text-embedding-3-large"`)
|
||||
require.Contains(t, string(response.Body), `"created":1234`)
|
||||
require.Contains(t, string(response.Body), `"custom":true`)
|
||||
manifest, err := s.FetchCodexModelsManifest(context.Background(), account, CodexCanonicalClientVersion(), "")
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(manifest.Body), `"slug":"codex-only"`)
|
||||
again, err := s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(response.Body), string(again.Body))
|
||||
require.EqualValues(t, 2, calls.Load())
|
||||
account.Credentials["api_key"] = "rotated-token"
|
||||
_, err = s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 3, calls.Load(), "credentials must participate in the cache key")
|
||||
}
|
||||
|
||||
func TestFetchOpenAIModelsListOAuthSharesManifestCache(t *testing.T) {
|
||||
_, calls := newCodexModelsOAuthCacheServer(t, `{"models":[{"slug":"special-oauth-model"},{"slug":"gpt-image-1"}]}`)
|
||||
s := &OpenAIGatewayService{}
|
||||
account := newCodexModelsTestAccount()
|
||||
response, err := s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, `{"object":"list","data":[{"id":"special-oauth-model","object":"model","owned_by":"openai","created":0},{"id":"gpt-image-1","object":"model","owned_by":"openai","created":0}]}`, string(response.Body))
|
||||
manifest, err := s.FetchCodexModelsManifest(context.Background(), account, CodexCanonicalClientVersion(), "")
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(manifest.Body), `"slug":"special-oauth-model"`)
|
||||
require.NotContains(t, string(manifest.Body), `"data"`)
|
||||
require.EqualValues(t, 1, calls.Load())
|
||||
_, err = s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, calls.Load())
|
||||
}
|
||||
|
||||
func TestFetchOpenAIModelsListCacheWindowsAndSingleflight(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
started := make(chan int32, 3)
|
||||
release := make(chan struct{}, 3)
|
||||
t.Cleanup(func() { close(release) })
|
||||
s := newCodexModelsAPIKeyTestService(&codexModelsHTTPUpstreamStub{do: func(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
call := calls.Add(1)
|
||||
if call > 1 && call < 4 {
|
||||
started <- call
|
||||
<-release
|
||||
}
|
||||
if call >= 4 {
|
||||
response := ordinaryModelsUpstreamResponse(`{"error":"unavailable"}`)
|
||||
response.StatusCode = http.StatusServiceUnavailable
|
||||
return response, nil
|
||||
}
|
||||
return ordinaryModelsUpstreamResponse(`{"data":[{"id":"version-` + string(rune('0'+call)) + `"}]}`), nil
|
||||
}})
|
||||
account := newCodexModelsAPIKeyTestAccount("https://models.example/v1")
|
||||
first, err := s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
for range 5 {
|
||||
_, err = s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.EqualValues(t, 1, calls.Load())
|
||||
expireCodexModelsManifestCache(s, 2*time.Minute)
|
||||
stale, err := s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(first.Body), string(stale.Body))
|
||||
select {
|
||||
case call := <-started:
|
||||
require.EqualValues(t, 2, call)
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("stale response did not start a background refresh")
|
||||
}
|
||||
for range 5 {
|
||||
cached, err := s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(first.Body), string(cached.Body))
|
||||
}
|
||||
require.EqualValues(t, 2, calls.Load(), "concurrent stale reads must share the refresh")
|
||||
release <- struct{}{}
|
||||
require.Eventually(t, func() bool {
|
||||
s.openAIModelsCache.mu.Lock()
|
||||
defer s.openAIModelsCache.mu.Unlock()
|
||||
for _, entry := range s.openAIModelsCache.entries {
|
||||
if strings.Contains(string(entry.manifest.Body), "version-2") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}, 2*time.Second, time.Millisecond)
|
||||
|
||||
expireCodexModelsManifestCache(s, 6*time.Minute)
|
||||
responses := make(chan *OpenAIModelsResponse, 2)
|
||||
fetchErrors := make(chan error, 2)
|
||||
var wait sync.WaitGroup
|
||||
for range 2 {
|
||||
wait.Add(1)
|
||||
go func() {
|
||||
defer wait.Done()
|
||||
response, err := s.FetchOpenAIModelsList(context.Background(), account)
|
||||
responses <- response
|
||||
fetchErrors <- err
|
||||
}()
|
||||
}
|
||||
select {
|
||||
case call := <-started:
|
||||
require.EqualValues(t, 3, call)
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("expired catalog did not start a synchronous refresh")
|
||||
}
|
||||
select {
|
||||
case <-responses:
|
||||
t.Fatal("expired catalog returned before the upstream refresh completed")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
release <- struct{}{}
|
||||
wait.Wait()
|
||||
for range 2 {
|
||||
require.NoError(t, <-fetchErrors)
|
||||
require.Contains(t, string((<-responses).Body), "version-3")
|
||||
}
|
||||
require.EqualValues(t, 3, calls.Load())
|
||||
expireCodexModelsManifestCache(s, 6*time.Minute)
|
||||
response, err := s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, response)
|
||||
require.Equal(t, http.StatusBadGateway, infraerrors.Code(err))
|
||||
}
|
||||
|
||||
func TestFetchOpenAIModelsListRevalidatesUpstreamETag(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
s := newCodexModelsAPIKeyTestService(&codexModelsHTTPUpstreamStub{do: func(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
response := ordinaryModelsUpstreamResponse(`{"data":[{"id":"unchanged"}]}`)
|
||||
response.Header.Set("ETag", `"upstream"`)
|
||||
if calls.Add(1) > 1 {
|
||||
assert.Equal(t, `"upstream"`, req.Header.Get("If-None-Match"))
|
||||
response.StatusCode = http.StatusNotModified
|
||||
}
|
||||
return response, nil
|
||||
}})
|
||||
account := newCodexModelsAPIKeyTestAccount("https://models.example/v1")
|
||||
first, err := s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
expireCodexModelsManifestCache(s, 2*time.Minute)
|
||||
_, err = s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
require.Eventually(t, func() bool {
|
||||
s.openAIModelsCache.mu.Lock()
|
||||
defer s.openAIModelsCache.mu.Unlock()
|
||||
for _, entry := range s.openAIModelsCache.entries {
|
||||
return entry.expiresAt.After(time.Now())
|
||||
}
|
||||
return false
|
||||
}, 2*time.Second, time.Millisecond)
|
||||
again, err := s.FetchOpenAIModelsList(context.Background(), account)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, first.ETag, again.ETag)
|
||||
require.Equal(t, string(first.Body), string(again.Body))
|
||||
require.EqualValues(t, 2, calls.Load())
|
||||
}
|
||||
|
||||
func TestProjectAccountModelsPassthroughIgnoresStaleMappings(t *testing.T) {
|
||||
account := newCodexModelsAPIKeyTestAccount("https://models.example/v1")
|
||||
account.Extra = map[string]any{"openai_passthrough": true}
|
||||
account.Credentials["model_mapping"] = map[string]any{"obsolete": "missing"}
|
||||
body := []byte(`{"object":"list","data":[{"id":"live-model"}]}`)
|
||||
projected, err := projectAccountModelsBody(body, account, nil, false)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, string(body), string(projected))
|
||||
}
|
||||
|
||||
func TestFetchOpenAIModelsListEmptyAndMalformedResponses(t *testing.T) {
|
||||
for _, body := range []string{`{"data":[]}`, `{"data":null}`, `{}`, `{"data":{}}`, `{"data":[{}]}`, `{"data":[null]}`} {
|
||||
t.Run(body, func(t *testing.T) {
|
||||
s := newCodexModelsAPIKeyTestService(&codexModelsHTTPUpstreamStub{do: func(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
return ordinaryModelsUpstreamResponse(body), nil
|
||||
}})
|
||||
response, err := s.FetchOpenAIModelsList(context.Background(), newCodexModelsAPIKeyTestAccount("https://models.example/v1"))
|
||||
if body != `{"data":[]}` {
|
||||
require.Error(t, err)
|
||||
require.Equal(t, http.StatusBadGateway, infraerrors.Code(err))
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
var result struct {
|
||||
Data []json.RawMessage `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(response.Body, &result))
|
||||
require.NotNil(t, result.Data)
|
||||
require.Empty(t, result.Data)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinnedOpenAIModelsListMixedAccountsShareColdCacheAcrossGroups(t *testing.T) {
|
||||
_, oauthCalls := newCodexModelsOAuthCacheServer(t, `{"models":[{"slug":"shared-model"},{"slug":"oauth-special"}]}`)
|
||||
var apiCalls atomic.Int32
|
||||
s := newCodexModelsAPIKeyTestService(&codexModelsHTTPUpstreamStub{do: func(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
apiCalls.Add(1)
|
||||
return ordinaryModelsUpstreamResponse(`{"data":[{"id":"shared-model","owned_by":"api-provider"},{"id":"api-special"}]}`), nil
|
||||
}})
|
||||
apiAccount := newCodexModelsAPIKeyTestAccount("https://models.example/v1")
|
||||
oauthAccount := newCodexModelsTestAccount()
|
||||
for _, account := range []*Account{apiAccount, oauthAccount} {
|
||||
account.Status, account.Schedulable = StatusActive, true
|
||||
}
|
||||
accounts := []Account{*apiAccount, *oauthAccount}
|
||||
s.accountRepo = splitCodexModelsAccountRepo{all: map[int64][]Account{10: accounts, 11: accounts}}
|
||||
groups := []*Group{
|
||||
{ID: 10, Platform: PlatformOpenAI, CodexModelsManifestConfig: GroupCodexModelsManifestConfig{Enabled: true, AccountIDs: []int64{2, 1}},
|
||||
ModelAllowlist: GroupModelAllowlist{Enabled: true, Models: []string{"oauth-special", "shared-model"}}},
|
||||
{ID: 11, Platform: PlatformOpenAI, CodexModelsManifestConfig: GroupCodexModelsManifestConfig{Enabled: true, AccountIDs: []int64{2, 1}}},
|
||||
}
|
||||
type result struct {
|
||||
response *OpenAIModelsResponse
|
||||
account *Account
|
||||
err error
|
||||
}
|
||||
results := make([]result, len(groups))
|
||||
var wait sync.WaitGroup
|
||||
for i, group := range groups {
|
||||
wait.Add(1)
|
||||
go func() {
|
||||
defer wait.Done()
|
||||
results[i].response, results[i].account, results[i].err = s.FetchPinnedOpenAIModelsList(context.Background(), group, 3, "")
|
||||
}()
|
||||
}
|
||||
wait.Wait()
|
||||
for i, result := range results {
|
||||
require.NoError(t, result.err)
|
||||
require.EqualValues(t, 2, result.account.ID)
|
||||
var catalog struct {
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
Owner string `json:"owned_by"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(result.response.Body, &catalog))
|
||||
ids := make([]string, 0, len(catalog.Data))
|
||||
for _, model := range catalog.Data {
|
||||
ids = append(ids, model.ID)
|
||||
if model.ID == "shared-model" {
|
||||
require.Equal(t, "api-provider", model.Owner)
|
||||
}
|
||||
}
|
||||
if i == 0 {
|
||||
require.Equal(t, []string{"oauth-special", "shared-model"}, ids)
|
||||
} else {
|
||||
require.Equal(t, []string{"shared-model", "api-special", "oauth-special"}, ids)
|
||||
}
|
||||
}
|
||||
require.EqualValues(t, 1, apiCalls.Load())
|
||||
require.EqualValues(t, 1, oauthCalls.Load())
|
||||
}
|
||||
|
||||
func TestFetchOpenAIModelsListResolvesShadowOAuthCredentials(t *testing.T) {
|
||||
_, calls := newCodexModelsOAuthCacheServer(t, `{"models":[{"slug":"parent-model"}]}`)
|
||||
parent := newCodexModelsTestAccount()
|
||||
shadow := &Account{ID: 9, Platform: PlatformOpenAI, Type: AccountTypeOAuth, ParentAccountID: &parent.ID}
|
||||
s := &OpenAIGatewayService{accountRepo: newStubCredRepo(parent)}
|
||||
response, err := s.FetchOpenAIModelsList(context.Background(), shadow)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(response.Body), `"id":"parent-model"`)
|
||||
require.EqualValues(t, 1, calls.Load())
|
||||
}
|
||||
|
||||
func TestProjectAccountModelsCannotExposeCodexMediaThroughAlias(t *testing.T) {
|
||||
account := newCodexModelsAPIKeyTestAccount("https://models.example/v1")
|
||||
account.Credentials["model_mapping"] = map[string]any{"image-alias": "gpt-image-1", "auto-alias": "codex-auto-fast"}
|
||||
body := []byte(`{"models":[{"slug":"gpt-image-1"},{"slug":"codex-auto-fast"}]}`)
|
||||
projected, err := projectAccountModelsBody(body, account, &Group{}, true)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, `{"models":[]}`, string(projected))
|
||||
}
|
||||
|
||||
func TestFetchOpenAIModelsListRejectsUnexpectedCold304(t *testing.T) {
|
||||
s := newCodexModelsAPIKeyTestService(&codexModelsHTTPUpstreamStub{do: func(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: http.StatusNotModified, Header: make(http.Header), Body: http.NoBody}, nil
|
||||
}})
|
||||
response, err := s.FetchOpenAIModelsList(context.Background(), newCodexModelsAPIKeyTestAccount("https://models.example/v1"))
|
||||
require.Error(t, err)
|
||||
require.Nil(t, response)
|
||||
require.Equal(t, http.StatusBadGateway, infraerrors.Code(err))
|
||||
}
|
||||
|
||||
func TestOpenAIModelsCacheSeparatesRepresentationsForIdenticalRequests(t *testing.T) {
|
||||
s := &OpenAIGatewayService{}
|
||||
request := openAIModelsRequest{url: "https://models.example/v1/models", accountID: 7}
|
||||
var calls atomic.Int32
|
||||
fetch := func(body string) func(context.Context, string) (*OpenAIModelsResponse, error) {
|
||||
return func(context.Context, string) (*OpenAIModelsResponse, error) {
|
||||
calls.Add(1)
|
||||
return &OpenAIModelsResponse{Body: []byte(body)}, nil
|
||||
}
|
||||
}
|
||||
manifestBody := `{"models":[{"slug":"shared"}]}`
|
||||
listBody := `{"object":"list","data":[{"id":"shared"}]}`
|
||||
_, err := s.fetchCachedOpenAIModels(context.Background(), request, fetch(manifestBody), "")
|
||||
require.NoError(t, err)
|
||||
request.standardModelsList = true
|
||||
list, err := s.fetchCachedOpenAIModels(context.Background(), request, fetch(listBody), "")
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, listBody, string(list.Body))
|
||||
request.standardModelsList = false
|
||||
manifest, err := s.fetchCachedOpenAIModels(context.Background(), request, fetch(manifestBody), "")
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, manifestBody, string(manifest.Body))
|
||||
require.EqualValues(t, 2, calls.Load())
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const openCodeSessionHeader = "X-OpenCode-Session"
|
||||
|
||||
// applyOpenCodeSessionHeader forwards the caller-owned conversation identifier
|
||||
// only to OpenCode's official API origin. The caller applies this after account
|
||||
// header overrides so a per-conversation value cannot be replaced by a fixed
|
||||
// account-wide override.
|
||||
func applyOpenCodeSessionHeader(c *gin.Context, account *Account, targetURL string, headers http.Header) {
|
||||
if c == nil || c.Request == nil || account == nil || account.Type != AccountTypeAPIKey || headers == nil {
|
||||
return
|
||||
}
|
||||
|
||||
parsed, err := url.Parse(targetURL)
|
||||
if err != nil || !strings.EqualFold(parsed.Scheme, "https") || !strings.EqualFold(parsed.Hostname(), "opencode.ai") {
|
||||
return
|
||||
}
|
||||
|
||||
sessionID := strings.TrimSpace(c.GetHeader(openCodeSessionHeader))
|
||||
if sessionID == "" {
|
||||
return
|
||||
}
|
||||
for key := range headers {
|
||||
if strings.EqualFold(key, openCodeSessionHeader) {
|
||||
delete(headers, key)
|
||||
}
|
||||
}
|
||||
headers.Set(openCodeSessionHeader, sessionID)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newOpenCodeSessionTestContext(t *testing.T, value string) *gin.Context {
|
||||
t.Helper()
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
|
||||
if value != "" {
|
||||
c.Request.Header.Set(openCodeSessionHeader, value)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func openCodeSessionTestService() *OpenAIGatewayService {
|
||||
return &OpenAIGatewayService{cfg: &config.Config{
|
||||
Security: config.SecurityConfig{
|
||||
URLAllowlist: config.URLAllowlistConfig{Enabled: false},
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
func openCodeSessionTestAccount(baseURL string) *Account {
|
||||
return &Account{
|
||||
ID: 1,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"base_url": baseURL,
|
||||
credKeyHeaderOverrideEnabled: true,
|
||||
credKeyHeaderOverrides: map[string]any{"x-opencode-session": "fixed-account-value"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func requireSingleOpenCodeSessionHeader(t *testing.T, headers http.Header, want string) {
|
||||
t.Helper()
|
||||
count := 0
|
||||
for key, values := range headers {
|
||||
if strings.EqualFold(key, openCodeSessionHeader) {
|
||||
count += len(values)
|
||||
require.Equal(t, []string{want}, values)
|
||||
}
|
||||
}
|
||||
require.Equal(t, 1, count)
|
||||
}
|
||||
|
||||
func TestApplyOpenCodeSessionHeaderTrustBoundary(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
account *Account
|
||||
targetURL string
|
||||
incoming string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "official origin",
|
||||
account: openCodeSessionTestAccount("https://opencode.ai/zen/v1"),
|
||||
targetURL: "https://opencode.ai/zen/v1/chat/completions",
|
||||
incoming: " conversation-123 ",
|
||||
want: "conversation-123",
|
||||
},
|
||||
{
|
||||
name: "lookalike origin",
|
||||
account: openCodeSessionTestAccount("https://opencode.ai.evil.example/v1"),
|
||||
targetURL: "https://opencode.ai.evil.example/v1/responses",
|
||||
incoming: "conversation-123",
|
||||
},
|
||||
{
|
||||
name: "subdomain is not implicitly trusted",
|
||||
account: openCodeSessionTestAccount("https://api.opencode.ai/v1"),
|
||||
targetURL: "https://api.opencode.ai/v1/responses",
|
||||
incoming: "conversation-123",
|
||||
},
|
||||
{
|
||||
name: "insecure official origin",
|
||||
account: openCodeSessionTestAccount("http://opencode.ai/zen/v1"),
|
||||
targetURL: "http://opencode.ai/zen/v1/responses",
|
||||
incoming: "conversation-123",
|
||||
},
|
||||
{
|
||||
name: "missing caller value",
|
||||
account: openCodeSessionTestAccount("https://opencode.ai/zen/v1"),
|
||||
targetURL: "https://opencode.ai/zen/v1/responses",
|
||||
},
|
||||
{
|
||||
name: "oauth account",
|
||||
account: &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth},
|
||||
targetURL: "https://opencode.ai/zen/v1/responses",
|
||||
incoming: "conversation-123",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
headers := make(http.Header)
|
||||
applyOpenCodeSessionHeader(newOpenCodeSessionTestContext(t, tt.incoming), tt.account, tt.targetURL, headers)
|
||||
require.Equal(t, tt.want, headers.Get(openCodeSessionHeader))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenCodeSessionForwardedByResponsesBuildersAfterAccountOverride(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
svc := openCodeSessionTestService()
|
||||
account := openCodeSessionTestAccount("https://opencode.ai/zen/v1")
|
||||
body := []byte(`{"model":"gpt-5","input":"hello"}`)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
build func(*gin.Context) (*http.Request, error)
|
||||
}{
|
||||
{
|
||||
name: "normal responses",
|
||||
build: func(c *gin.Context) (*http.Request, error) {
|
||||
return svc.buildUpstreamRequest(context.Background(), c, account, body, "token", false, "", false)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "passthrough responses",
|
||||
build: func(c *gin.Context) (*http.Request, error) {
|
||||
return svc.buildUpstreamRequestOpenAIPassthrough(context.Background(), c, account, body, "token")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := newOpenCodeSessionTestContext(t, "conversation-456")
|
||||
req, err := tt.build(c)
|
||||
require.NoError(t, err)
|
||||
requireSingleOpenCodeSessionHeader(t, req.Header, "conversation-456")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenCodeSessionMissingCallerValueKeepsExistingOverrideBehavior(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
svc := openCodeSessionTestService()
|
||||
account := openCodeSessionTestAccount("https://opencode.ai/zen/v1")
|
||||
c := newOpenCodeSessionTestContext(t, "")
|
||||
|
||||
req, err := svc.buildUpstreamRequest(
|
||||
context.Background(), c, account,
|
||||
[]byte(`{"model":"gpt-5","input":"hello"}`), "token", false, "", false,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "fixed-account-value", getHeaderRaw(req.Header, "x-opencode-session"))
|
||||
}
|
||||
|
||||
type openCodeSessionHTTPUpstream struct {
|
||||
request *http.Request
|
||||
}
|
||||
|
||||
func (u *openCodeSessionHTTPUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
u.request = req
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(`{}`)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (u *openCodeSessionHTTPUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
return u.Do(req, proxyURL, accountID, concurrency)
|
||||
}
|
||||
|
||||
func TestOpenCodeSessionForwardedByRawChatCompletionsAfterAccountOverride(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
upstream := &openCodeSessionHTTPUpstream{}
|
||||
svc := openCodeSessionTestService()
|
||||
svc.httpUpstream = upstream
|
||||
account := openCodeSessionTestAccount("https://opencode.ai/zen/v1")
|
||||
c := newOpenCodeSessionTestContext(t, "conversation-789")
|
||||
|
||||
resp, err := svc.sendCCUpstreamRequest(
|
||||
context.Background(), c, account,
|
||||
"https://opencode.ai/zen/v1/chat/completions", []byte(`{"model":"gpt-5"}`),
|
||||
false, "token", "", "",
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, resp.Body.Close())
|
||||
require.NotNil(t, upstream.request)
|
||||
requireSingleOpenCodeSessionHeader(t, upstream.request.Header, "conversation-789")
|
||||
}
|
||||
|
||||
func TestOpenCodeSessionIsNotForwardedToOtherUpstreams(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
svc := openCodeSessionTestService()
|
||||
body := []byte(`{"model":"gpt-5","input":"hello"}`)
|
||||
|
||||
for _, baseURL := range []string{
|
||||
"https://api.openai.com/v1",
|
||||
"https://opencode.ai.evil.example/v1",
|
||||
"https://api.opencode.ai/v1",
|
||||
} {
|
||||
t.Run(baseURL, func(t *testing.T) {
|
||||
account := &Account{
|
||||
ID: 1,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"base_url": baseURL},
|
||||
}
|
||||
c := newOpenCodeSessionTestContext(t, "private-conversation")
|
||||
req, err := svc.buildUpstreamRequest(context.Background(), c, account, body, "token", false, "", false)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, req.Header.Get(openCodeSessionHeader))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ const (
|
||||
)
|
||||
|
||||
var openAIReasoningEffortValues = []string{"minimal", "low", "medium", "high", "xhigh", "max"}
|
||||
var anthropicReasoningEffortValues = []string{"low", "medium", "high", "xhigh", "max"}
|
||||
|
||||
func normalizeReasoningEffortMappingSource(raw string) string {
|
||||
if strings.EqualFold(strings.TrimSpace(raw), "none") {
|
||||
@@ -90,10 +91,14 @@ func NormalizeMaxReasoningEffort(raw string) string {
|
||||
}
|
||||
|
||||
func reasoningEffortValuesForPlatform(platform string) []string {
|
||||
if platform != PlatformOpenAI && platform != PlatformComposite {
|
||||
switch platform {
|
||||
case PlatformOpenAI, PlatformComposite:
|
||||
return openAIReasoningEffortValues
|
||||
case PlatformAnthropic:
|
||||
return anthropicReasoningEffortValues
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return openAIReasoningEffortValues
|
||||
}
|
||||
|
||||
func normalizeMaxReasoningEffortForPlatform(platform, raw string) (string, error) {
|
||||
@@ -104,7 +109,8 @@ func normalizeMaxReasoningEffortForPlatform(platform, raw string) (string, error
|
||||
allowedValues := reasoningEffortValuesForPlatform(platform)
|
||||
if len(allowedValues) == 0 {
|
||||
return "", fmt.Errorf(
|
||||
"reasoning effort policy is only supported for platforms %q and %q",
|
||||
"reasoning effort policy is only supported for platforms %q, %q, and %q",
|
||||
PlatformAnthropic,
|
||||
PlatformOpenAI,
|
||||
PlatformComposite,
|
||||
)
|
||||
@@ -152,7 +158,8 @@ func normalizeMaxReasoningEffortOverLimitForPlatform(platform, raw string) (stri
|
||||
}
|
||||
if len(reasoningEffortValuesForPlatform(platform)) == 0 {
|
||||
return "", fmt.Errorf(
|
||||
"reasoning effort policy is only supported for platforms %q and %q",
|
||||
"reasoning effort policy is only supported for platforms %q, %q, and %q",
|
||||
PlatformAnthropic,
|
||||
PlatformOpenAI,
|
||||
PlatformComposite,
|
||||
)
|
||||
@@ -279,7 +286,7 @@ func selectReasoningEffortMapping(mappings []ReasoningEffortMapping, from, reque
|
||||
}
|
||||
|
||||
// NormalizeReasoningEffortMappings validates group mapping rules against the
|
||||
// fixed effort values supported by OpenAI routes. Optional model scopes are
|
||||
// fixed effort values supported by the selected platform. Optional model scopes are
|
||||
// canonicalized to exact/prefix/suffix match; empty type and model keep the
|
||||
// global all-models rule.
|
||||
func NormalizeReasoningEffortMappings(platform string, raw []ReasoningEffortMapping) ([]ReasoningEffortMapping, error) {
|
||||
@@ -421,7 +428,7 @@ func sanitizeGroupReasoningEffortPolicy(group *Group) {
|
||||
if mappingsErr != nil {
|
||||
mappings = []ReasoningEffortMapping{}
|
||||
}
|
||||
if overLimit == "" || (group.Platform != PlatformOpenAI && group.Platform != PlatformComposite) {
|
||||
if overLimit == "" || (group.Platform != PlatformAnthropic && group.Platform != PlatformOpenAI && group.Platform != PlatformComposite) {
|
||||
overLimit = ReasoningEffortOverLimitDowngrade
|
||||
}
|
||||
group.MaxReasoningEffort = maxEffort
|
||||
@@ -429,12 +436,13 @@ func sanitizeGroupReasoningEffortPolicy(group *Group) {
|
||||
group.ReasoningEffortMappings = mappings
|
||||
}
|
||||
|
||||
// ApplyOpenAIReasoningEffortPolicy applies one mapping (optionally scoped to
|
||||
// ApplyReasoningEffortPolicy applies one mapping (optionally scoped to
|
||||
// the request model by exact name, prefix, or suffix) and then either caps
|
||||
// known effort levels or rejects the request when the group is configured to
|
||||
// deny values above the ceiling. Omitted values remain untouched so upstream
|
||||
// defaults stay in control.
|
||||
func ApplyOpenAIReasoningEffortPolicy(body []byte, maxEffort string, mappings []ReasoningEffortMapping, overLimit string) ([]byte, bool, error) {
|
||||
// defaults stay in control. It understands both OpenAI and Anthropic request
|
||||
// field shapes.
|
||||
func ApplyReasoningEffortPolicy(body []byte, maxEffort string, mappings []ReasoningEffortMapping, overLimit string) ([]byte, bool, error) {
|
||||
maxRank, hasMax := reasoningEffortRank(maxEffort)
|
||||
if len(body) == 0 || (!hasMax && len(mappings) == 0) {
|
||||
return body, false, nil
|
||||
@@ -445,7 +453,7 @@ func ApplyOpenAIReasoningEffortPolicy(body []byte, maxEffort string, mappings []
|
||||
requestModel := strings.TrimSpace(gjson.GetBytes(body, "model").String())
|
||||
result := body
|
||||
changed := false
|
||||
for _, path := range []string{"reasoning.effort", "reasoning_effort"} {
|
||||
for _, path := range []string{"reasoning.effort", "reasoning_effort", "output_config.effort"} {
|
||||
field := gjson.GetBytes(result, path)
|
||||
if !field.Exists() || field.Type != gjson.String {
|
||||
continue
|
||||
@@ -492,3 +500,8 @@ func applyOpenAIWSReasoningEffortPolicy(payload []byte, hooks *OpenAIWSIngressHo
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
// ApplyOpenAIReasoningEffortPolicy is retained for OpenAI forwarding callers.
|
||||
func ApplyOpenAIReasoningEffortPolicy(body []byte, maxEffort string, mappings []ReasoningEffortMapping, overLimit string) ([]byte, bool, error) {
|
||||
return ApplyReasoningEffortPolicy(body, maxEffort, mappings, overLimit)
|
||||
}
|
||||
@@ -147,9 +147,9 @@ func TestNormalizeReasoningEffortMappings(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("rejects mappings for non OpenAI platforms", func(t *testing.T) {
|
||||
for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformAntigravity, PlatformGrok} {
|
||||
for _, platform := range []string{PlatformGemini, PlatformAntigravity, PlatformGrok} {
|
||||
_, err := NormalizeReasoningEffortMappings(platform, []ReasoningEffortMapping{{From: "low", To: "high"}})
|
||||
require.ErrorContains(t, err, "only supported for platforms \"openai\" and \"composite\"")
|
||||
require.ErrorContains(t, err, "only supported for platforms")
|
||||
}
|
||||
|
||||
_, err := NormalizeReasoningEffortMappings(PlatformOpenAI, []ReasoningEffortMapping{{From: "ultra", To: "high"}})
|
||||
@@ -166,6 +166,15 @@ func TestNormalizeReasoningEffortMappings(t *testing.T) {
|
||||
_, err := NormalizeReasoningEffortMappings(PlatformOpenAI, []ReasoningEffortMapping{{From: "low", To: "none"}})
|
||||
require.ErrorContains(t, err, "empty or unknown")
|
||||
})
|
||||
|
||||
t.Run("supports Anthropic values except minimal", func(t *testing.T) {
|
||||
got, err := NormalizeReasoningEffortMappings(PlatformAnthropic, []ReasoningEffortMapping{{From: " MAX ", To: " x-high "}})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []ReasoningEffortMapping{{From: "max", To: "xhigh"}}, got)
|
||||
|
||||
_, err = NormalizeReasoningEffortMappings(PlatformAnthropic, []ReasoningEffortMapping{{From: "minimal", To: "low"}})
|
||||
require.ErrorContains(t, err, "not supported for platform \"anthropic\"")
|
||||
})
|
||||
}
|
||||
|
||||
func TestNormalizeMaxReasoningEffortForPlatform(t *testing.T) {
|
||||
@@ -176,9 +185,15 @@ func TestNormalizeMaxReasoningEffortForPlatform(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "max", value)
|
||||
|
||||
for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformAntigravity, PlatformGrok} {
|
||||
value, err = normalizeMaxReasoningEffortForPlatform(PlatformAnthropic, "xhigh")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "xhigh", value)
|
||||
_, err = normalizeMaxReasoningEffortForPlatform(PlatformAnthropic, "minimal")
|
||||
require.ErrorContains(t, err, "not supported")
|
||||
|
||||
for _, platform := range []string{PlatformGemini, PlatformAntigravity, PlatformGrok} {
|
||||
_, err = normalizeMaxReasoningEffortForPlatform(platform, "low")
|
||||
require.ErrorContains(t, err, "only supported for platforms \"openai\" and \"composite\"")
|
||||
require.ErrorContains(t, err, "only supported for platforms")
|
||||
}
|
||||
|
||||
_, err = normalizeMaxReasoningEffortForPlatform(PlatformOpenAI, "none")
|
||||
@@ -205,8 +220,9 @@ func TestNormalizeMaxReasoningEffortOverLimitForPlatform(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, ReasoningEffortOverLimitDowngrade, value)
|
||||
|
||||
_, err = normalizeMaxReasoningEffortOverLimitForPlatform(PlatformAnthropic, "deny")
|
||||
require.ErrorContains(t, err, "only supported for platforms \"openai\" and \"composite\"")
|
||||
value, err = normalizeMaxReasoningEffortOverLimitForPlatform(PlatformAnthropic, "deny")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, ReasoningEffortOverLimitDeny, value)
|
||||
|
||||
_, err = normalizeMaxReasoningEffortOverLimitForPlatform(PlatformOpenAI, "block")
|
||||
require.ErrorContains(t, err, "not supported")
|
||||
@@ -251,6 +267,8 @@ func TestApplyOpenAIReasoningEffortPolicy(t *testing.T) {
|
||||
}{
|
||||
{name: "nested caps high", body: `{"reasoning":{"effort":"xhigh"}}`, max: "medium", path: "reasoning.effort", want: "medium", changed: true},
|
||||
{name: "flat caps high", body: `{"reasoning_effort":"high"}`, max: "low", path: "reasoning_effort", want: "low", changed: true},
|
||||
{name: "Anthropic output config caps max", body: `{"output_config":{"effort":"max"}}`, max: "xhigh", path: "output_config.effort", want: "xhigh", changed: true},
|
||||
{name: "Anthropic output config maps before cap", body: `{"output_config":{"effort":"max"}}`, max: "high", mappings: []ReasoningEffortMapping{{From: "max", To: "xhigh"}}, path: "output_config.effort", want: "high", changed: true},
|
||||
{name: "does not raise omitted", body: `{"model":"gpt-5"}`, max: "low", path: "reasoning_effort", want: "", changed: false},
|
||||
{name: "keeps lower value", body: `{"reasoning_effort":"low"}`, max: "high", path: "reasoning_effort", want: "low", changed: false},
|
||||
{name: "normalizes request alias", body: `{"reasoning_effort":"x-high"}`, max: "xhigh", path: "reasoning_effort", want: "xhigh", changed: true},
|
||||
|
||||
@@ -7,7 +7,8 @@ import (
|
||||
const openAIResponsesInputTextMaxChars = 10000000
|
||||
|
||||
// sanitizeOpenAIResponsesOrphanToolOutputs removes tool-output items that have
|
||||
// no matching call or item reference anywhere in the current input.
|
||||
// no matching call or item reference anywhere in the current input. Named
|
||||
// function outputs without a call ID are standalone inputs, not orphan results.
|
||||
func sanitizeOpenAIResponsesOrphanToolOutputs(reqBody map[string]any, input []any, hasPreviousResponseID bool) bool {
|
||||
if len(input) == 0 || hasPreviousResponseID {
|
||||
return false
|
||||
@@ -45,6 +46,15 @@ func sanitizeOpenAIResponsesOrphanToolOutputs(reqBody map[string]any, input []an
|
||||
}
|
||||
|
||||
callID := strings.TrimSpace(firstNonEmptyString(item["call_id"]))
|
||||
// Codex sends externally supplied inputs (such as task delegation) as
|
||||
// named function outputs without a preceding function call. Preserve
|
||||
// their native type, namespace and output instead of silently dropping
|
||||
// the request that started the turn.
|
||||
if callID == "" && strings.TrimSpace(firstNonEmptyString(item["type"])) == "function_call_output" &&
|
||||
strings.TrimSpace(firstNonEmptyString(item["name"])) != "" {
|
||||
normalized = append(normalized, rawItem)
|
||||
continue
|
||||
}
|
||||
_, hasToolCall := toolCallIDs[callID]
|
||||
_, hasReference := referenceIDs[callID]
|
||||
if callID != "" && (hasToolCall || hasReference) {
|
||||
|
||||
@@ -2,6 +2,8 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -11,6 +13,21 @@ import (
|
||||
)
|
||||
|
||||
func TestSanitizeOpenAIResponsesOrphanToolOutputs(t *testing.T) {
|
||||
t.Run("named standalone inputs do not legitimize orphan results", func(t *testing.T) {
|
||||
named := map[string]any{"type": "function_call_output", "name": "send_message_to_thread", "namespace": "codex_app", "output": "delegation"}
|
||||
input := []any{
|
||||
named,
|
||||
map[string]any{"type": "function_call_output", "output": "missing name and call id"},
|
||||
map[string]any{"type": "function_call_output", "name": " ", "output": "blank name"},
|
||||
map[string]any{"type": "function_call_output", "name": "send_message_to_thread", "call_id": "missing", "output": "orphan result"},
|
||||
map[string]any{"type": "custom_tool_call_output", "name": "apply_patch", "output": "missing call id"},
|
||||
}
|
||||
reqBody := map[string]any{"input": input}
|
||||
|
||||
require.True(t, sanitizeOpenAIResponsesOrphanToolOutputs(reqBody, input, false))
|
||||
require.Equal(t, []any{named}, reqBody["input"])
|
||||
})
|
||||
|
||||
t.Run("preserves matches regardless of item order", func(t *testing.T) {
|
||||
input := []any{
|
||||
map[string]any{"type": "tool_search_output", "call_id": "search_1", "output": "first"},
|
||||
@@ -71,6 +88,48 @@ func TestSanitizeOpenAIResponsesOrphanToolOutputs(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestWebSocketCompatibilityPreservesNamedDelegation(t *testing.T) {
|
||||
for _, toolName := range []string{"create_thread", "send_message_to_thread"} {
|
||||
for _, withHistory := range []bool{false, true} {
|
||||
for _, previousResponseID := range []string{"", "resp_previous"} {
|
||||
name := fmt.Sprintf("%s/history=%t/previous=%t", toolName, withHistory, previousResponseID != "")
|
||||
t.Run(name, func(t *testing.T) {
|
||||
input := []any{}
|
||||
if withHistory {
|
||||
input = append(input,
|
||||
map[string]any{"type": "function_call", "call_id": "fc_history", "name": "lookup", "arguments": "{}"},
|
||||
map[string]any{"type": "function_call_output", "call_id": "fc_history", "output": "historical result"},
|
||||
)
|
||||
}
|
||||
input = append(input,
|
||||
map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": "Updated environment context."}}},
|
||||
map[string]any{"type": "function_call_output", "name": toolName, "namespace": "codex_app", "output": "<codex_delegation>\n <source_thread_id>source-task</source_thread_id>\n <input>Reply with DELEGATION_OK.</input>\n</codex_delegation>"},
|
||||
)
|
||||
reqBody := map[string]any{"type": "response.create", "model": "gpt-5.5", "input": input}
|
||||
if previousResponseID != "" {
|
||||
reqBody["previous_response_id"] = previousResponseID
|
||||
}
|
||||
body, err := json.Marshal(reqBody)
|
||||
require.NoError(t, err)
|
||||
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
|
||||
|
||||
normalized, _, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, account, false)
|
||||
require.NoError(t, err)
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(normalized, &got))
|
||||
require.Equal(t, input, got["input"], "preserve the delegation envelope, native type and history in order")
|
||||
require.Equal(t, reqBody["previous_response_id"], got["previous_response_id"])
|
||||
|
||||
again, changed, err := normalizeOpenAIResponsesWebSocketCompatibilityBody(normalized, account, false)
|
||||
require.NoError(t, err)
|
||||
require.False(t, changed, "normalization must be idempotent")
|
||||
require.JSONEq(t, string(normalized), string(again))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIResponsesInputTextIsNeverSilentlyTruncated(t *testing.T) {
|
||||
atLimit := strings.Repeat("z", openAIResponsesInputTextMaxChars)
|
||||
oversized := strings.Repeat("a", openAIResponsesInputTextMaxChars) + "中"
|
||||
|
||||
@@ -37,14 +37,14 @@ func setOpenAICodexRoutingHint(headers http.Header, account *Account, model stri
|
||||
|
||||
// Codex treats "default" as an explicit standard-routing sentinel, not as a
|
||||
// service tier sent to the backend. Fast follows the gateway's existing
|
||||
// canonicalization and therefore becomes "priority"; flex stays "flex".
|
||||
// canonicalization and therefore becomes "priority"; flex and ultrafast
|
||||
// stay as themselves.
|
||||
canonicalTier := normalizedOpenAIServiceTierValue(serviceTier)
|
||||
// This backport has no Codex model-catalog snapshot with which to validate
|
||||
// arbitrary tier ids. Keep the hint to the two effective tiers Codex itself
|
||||
// selects; default, missing, and other gateway-compatible API values remain
|
||||
// model-only rather than expanding the ChatGPT routing protocol here.
|
||||
// Keep the hint to the effective tiers Codex itself selects. default,
|
||||
// missing, auto, and scale remain model-only rather than expanding the
|
||||
// ChatGPT routing protocol here.
|
||||
switch canonicalTier {
|
||||
case OpenAIFastTierPriority, OpenAIFastTierFlex:
|
||||
case OpenAIFastTierPriority, OpenAIFastTierFlex, OpenAIFastTierUltrafast:
|
||||
default:
|
||||
canonicalTier = ""
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ func TestSetOpenAICodexRoutingHintCanonicalizesOfficialServiceTiers(t *testing.T
|
||||
{name: "fast alias", model: "gpt-5.6", serviceTier: " fast ", want: "model=gpt-5.6;tier=priority"},
|
||||
{name: "priority", model: "gpt-5.6", serviceTier: "priority", want: "model=gpt-5.6;tier=priority"},
|
||||
{name: "flex", model: "gpt-5.6", serviceTier: "flex", want: "model=gpt-5.6;tier=flex"},
|
||||
{name: "ultrafast", model: "gpt-5.6", serviceTier: "ultrafast", want: "model=gpt-5.6;tier=ultrafast"},
|
||||
{name: "explicit default sentinel", model: "gpt-5.6", serviceTier: "default", want: "model=gpt-5.6"},
|
||||
{name: "omitted tier", model: "gpt-5.6", want: "model=gpt-5.6"},
|
||||
{name: "auto is not expanded without catalog support", model: "gpt-5.6", serviceTier: "auto", want: "model=gpt-5.6"},
|
||||
@@ -90,6 +91,7 @@ func TestOpenAIOAuthHTTPBuildersSendRoutingHintFromFinalBody(t *testing.T) {
|
||||
}{
|
||||
{name: "fast", body: []byte(`{"model":"gpt-5.6-codex","service_tier":"fast"}`), want: "model=gpt-5.6-codex;tier=priority"},
|
||||
{name: "flex", body: []byte(`{"model":"gpt-5.6-codex","service_tier":"flex"}`), want: "model=gpt-5.6-codex;tier=flex"},
|
||||
{name: "ultrafast", body: []byte(`{"model":"gpt-5.6-codex","service_tier":"ultrafast"}`), want: "model=gpt-5.6-codex;tier=ultrafast"},
|
||||
{name: "default", body: []byte(`{"model":"gpt-5.6-codex","service_tier":"default"}`), want: "model=gpt-5.6-codex"},
|
||||
{name: "omitted", body: []byte(`{"model":"gpt-5.6-codex"}`), want: "model=gpt-5.6-codex"},
|
||||
}
|
||||
@@ -216,6 +218,7 @@ func TestBuildOpenAIWSHeadersSendsOAuthRoutingHintOnly(t *testing.T) {
|
||||
},
|
||||
}
|
||||
require.Equal(t, "model=gpt-5.6-codex;tier=priority", build(t, oauthAccount, "fast").Get(openAICodexRoutingHintHeader))
|
||||
require.Equal(t, "model=gpt-5.6-codex;tier=ultrafast", build(t, oauthAccount, "ultrafast").Get(openAICodexRoutingHintHeader))
|
||||
require.Equal(t, "model=gpt-5.6-codex", build(t, oauthAccount, "default").Get(openAICodexRoutingHintHeader))
|
||||
require.Empty(t, build(t, &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, "priority").Get(openAICodexRoutingHintHeader))
|
||||
}
|
||||
|
||||
@@ -55,3 +55,9 @@ func writeOpenAIUpstreamClientError(c *gin.Context, statusCode int, body []byte,
|
||||
|
||||
c.JSON(statusCode, gin.H{"error": errorPayload})
|
||||
}
|
||||
|
||||
// WriteOpenAIUpstreamClientError preserves a structured deterministic upstream
|
||||
// client error when the handler has exhausted all eligible accounts.
|
||||
func WriteOpenAIUpstreamClientError(c *gin.Context, statusCode int, body []byte, upstreamMsg string) {
|
||||
writeOpenAIUpstreamClientError(c, statusCode, body, upstreamMsg)
|
||||
}
|
||||
@@ -45,6 +45,67 @@ func newOpenAIUpstreamErrorTestAccount() *Account {
|
||||
return &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Name: "acct"}
|
||||
}
|
||||
|
||||
type modelNotFoundManagedAccountRepo struct{ AccountRepository }
|
||||
|
||||
func TestOpenAICompatibleModelNotFound400FailoverScope(t *testing.T) {
|
||||
svc := &OpenAIGatewayService{accountRepo: &modelNotFoundManagedAccountRepo{}}
|
||||
body := []byte(`{"error":{"code":"model_not_found","message":"model not found"}}`)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
account *Account
|
||||
want bool
|
||||
}{
|
||||
{name: "openai api key", account: &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, want: true},
|
||||
{name: "compatible provider", account: &Account{Platform: PlatformDeepseek, Type: AccountTypeAPIKey}, want: true},
|
||||
{name: "anthropic account", account: &Account{Platform: PlatformAnthropic, Type: AccountTypeAPIKey}, want: false},
|
||||
{name: "missing account", account: nil, want: false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.Equal(t, tc.want, svc.shouldFailoverOpenAIUpstreamResponse(
|
||||
tc.account, http.StatusBadRequest, "model not found", body,
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
require.False(t, svc.shouldFailoverOpenAIUpstreamResponse(
|
||||
&Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey},
|
||||
http.StatusBadRequest,
|
||||
"Invalid value for temperature",
|
||||
[]byte(`{"error":{"code":"invalid_request_error","message":"Invalid value for temperature"}}`),
|
||||
))
|
||||
}
|
||||
|
||||
func TestOpenAICompatibleModelNotFound400WithoutManagedCandidatesRemainsTerminal(t *testing.T) {
|
||||
svc := &OpenAIGatewayService{}
|
||||
body := []byte(`{"error":{"code":"model_not_found","message":"model not found"}}`)
|
||||
|
||||
require.False(t, svc.shouldFailoverOpenAIUpstreamResponse(
|
||||
&Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth},
|
||||
http.StatusBadRequest,
|
||||
"model not found",
|
||||
body,
|
||||
))
|
||||
}
|
||||
|
||||
func TestFailoverOpenAIUpstreamHTTPError_ModelNotFoundIsNextAccountEligible(t *testing.T) {
|
||||
c, _ := newOpenAIUpstreamErrorTestContext(t)
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{}, accountRepo: &modelNotFoundManagedAccountRepo{}}
|
||||
account := &Account{ID: 42, Name: "compatible", Platform: PlatformOpenAI, Type: AccountTypeAPIKey}
|
||||
body := []byte(`{"error":{"code":"model_not_found","message":"model not found"}}`)
|
||||
resp := newOpenAIUpstreamErrorResponse(http.StatusBadRequest, string(body))
|
||||
|
||||
failoverErr := svc.failoverOpenAIUpstreamHTTPError(
|
||||
context.Background(), c, account, resp, body, "model not found", "missing-model",
|
||||
)
|
||||
|
||||
require.NotNil(t, failoverErr)
|
||||
require.Equal(t, http.StatusBadRequest, failoverErr.StatusCode)
|
||||
require.Equal(t, body, failoverErr.ResponseBody)
|
||||
require.True(t, failoverErr.ShouldRetryNextAccount())
|
||||
require.False(t, IsResponseCommitted(c), "failover must remain eligible before writing downstream")
|
||||
}
|
||||
|
||||
// 主复现:原生 Responses 路径必须回真实的 400 与上游诊断信息,而不是可重试的 502。
|
||||
//
|
||||
// 归一成 502 时下游网关(CCH 等)会把确定性的 Schema 错误当成临时上游故障重试,
|
||||
|
||||
@@ -137,9 +137,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
|
||||
forceHTTPBridge = true
|
||||
break
|
||||
}
|
||||
// 透传 relay 通过 TurnStarted 记录每个 turn 的开始时刻,但不触发
|
||||
// BeforeTurn;因此仍只有建连时的利润准入门,没有 turn 级复核。
|
||||
// handler 计费在 turn 定价未冻结时回退到对应的 turn 开始时刻。
|
||||
// 首轮准入由握手路径完成;后续 response.create 会在写入上游前
|
||||
// 依次回调 BeforeRequest 和 BeforeTurn,并在终止或失败时回调
|
||||
// AfterTurn,从而覆盖 turn 级利润复核、定价冻结和并发槽位释放。
|
||||
return s.proxyResponsesWebSocketV2Passthrough(
|
||||
ctx,
|
||||
c,
|
||||
@@ -521,6 +521,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
|
||||
return err
|
||||
}
|
||||
|
||||
useHTTPBridge := forceHTTPBridge || s.shouldBridgeOpenAIWSHTTP(account, firstPayload.payloadBytes, firstPayload.previousResponseID)
|
||||
turnState := strings.TrimSpace(c.GetHeader(openAIWSTurnStateHeader))
|
||||
stateStore := s.getOpenAIWSStateStore()
|
||||
groupID := getOpenAIGroupIDFromContext(c)
|
||||
@@ -530,20 +531,25 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
|
||||
storeDisabled := false
|
||||
refreshIngressRouteState := func(payload openAIWSClientPayload) {
|
||||
sessionHash = s.GenerateSessionHash(c, payload.rawForHash)
|
||||
preferredConnID = ""
|
||||
storeDisabled = s.isOpenAIWSStoreDisabledInRequestRaw(payload.payloadRaw, account)
|
||||
if useHTTPBridge {
|
||||
// Sticky account affinity may be shared, but an HTTP bridge must not
|
||||
// inherit another connection's native WS turn state or socket binding.
|
||||
return
|
||||
}
|
||||
if turnState == "" && stateStore != nil && sessionHash != "" {
|
||||
if savedTurnState, ok := stateStore.GetSessionTurnState(groupID, sessionHash); ok {
|
||||
turnState = savedTurnState
|
||||
}
|
||||
}
|
||||
|
||||
preferredConnID = ""
|
||||
if stateStore != nil && payload.previousResponseID != "" {
|
||||
if connID, ok := stateStore.GetResponseConn(payload.previousResponseID); ok {
|
||||
preferredConnID = connID
|
||||
}
|
||||
}
|
||||
|
||||
storeDisabled = s.isOpenAIWSStoreDisabledInRequestRaw(payload.payloadRaw, account)
|
||||
if stateStore != nil && storeDisabled && payload.previousResponseID == "" && sessionHash != "" {
|
||||
if connID, ok := stateStore.GetSessionConn(groupID, sessionHash); ok {
|
||||
preferredConnID = connID
|
||||
@@ -552,7 +558,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
|
||||
}
|
||||
refreshIngressRouteState(firstPayload)
|
||||
|
||||
if forceHTTPBridge || s.shouldBridgeOpenAIWSHTTP(account, firstPayload.payloadBytes, firstPayload.previousResponseID) {
|
||||
if useHTTPBridge {
|
||||
logOpenAIWSModeInfo(
|
||||
"ingress_ws_http_bridge_start account_id=%d account_type=%s payload_bytes=%d threshold_bytes=%d has_session_hash=%v store_disabled=%v",
|
||||
account.ID,
|
||||
@@ -725,10 +731,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
|
||||
bridgeAccountFailoverInputExists = true
|
||||
}
|
||||
if bridgeTurnState := strings.TrimSpace(result.ResponseHeaders.Get(openAIWSTurnStateHeader)); bridgeTurnState != "" {
|
||||
// Follow-up turns on this bridge retain their own upstream state;
|
||||
// publishing it by session hash would leak it to independent bridges.
|
||||
turnState = bridgeTurnState
|
||||
if stateStore != nil && sessionHash != "" {
|
||||
stateStore.BindSessionTurnState(groupID, sessionHash, bridgeTurnState, s.openAIWSSessionStickyTTL())
|
||||
}
|
||||
}
|
||||
responseID := strings.TrimSpace(result.RequestID)
|
||||
if responseID != "" && stateStore != nil {
|
||||
@@ -1021,6 +1026,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
|
||||
}
|
||||
lastEventType = eventType
|
||||
}
|
||||
if openAIWSMessageShouldParseUsage(eventType, upstreamMessage) {
|
||||
parseOpenAIWSResponseUsageFromCompletedEvent(upstreamMessage, &usage)
|
||||
}
|
||||
if eventType == "error" || eventType == "response.failed" {
|
||||
markOpenAICyberPolicyEvent(c, upstreamMessage, http.StatusOK, &usage)
|
||||
}
|
||||
if eventType == "error" {
|
||||
s.handleOpenAIWSErrorEventTransientFailure(ctx, account, mappedModel, lease.HandshakeHeaders(), upstreamMessage)
|
||||
errCodeRaw, errTypeRaw, errMsgRaw := parseOpenAIWSErrorEventFields(upstreamMessage)
|
||||
@@ -1135,23 +1146,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
|
||||
ms := int(time.Since(turnStart).Milliseconds())
|
||||
firstTokenMs = &ms
|
||||
}
|
||||
if openAIWSMessageShouldParseUsage(eventType, upstreamMessage) {
|
||||
parseOpenAIWSResponseUsageFromCompletedEvent(upstreamMessage, &usage)
|
||||
}
|
||||
imageCounter.AddSSEData(upstreamMessage)
|
||||
|
||||
if eventType == "response.failed" {
|
||||
if hit, code, msg := detectOpenAICyberPolicy(upstreamMessage); hit {
|
||||
MarkOpsCyberPolicy(c, CyberPolicyMark{
|
||||
Code: code,
|
||||
Message: msg,
|
||||
Body: truncateString(string(upstreamMessage), 4096),
|
||||
UpstreamStatus: http.StatusOK,
|
||||
UpstreamInTok: usage.InputTokens,
|
||||
UpstreamOutTok: usage.OutputTokens,
|
||||
})
|
||||
}
|
||||
}
|
||||
if !clientDisconnected {
|
||||
if needModelReplace && len(mappedModelBytes) > 0 && openAIWSEventMayContainModel(eventType) && bytes.Contains(upstreamMessage, mappedModelBytes) {
|
||||
upstreamMessage = replaceOpenAIWSMessageModel(upstreamMessage, mappedModel, originalModel)
|
||||
|
||||
@@ -585,17 +585,8 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2(
|
||||
}
|
||||
imageCounter.AddSSEData(message)
|
||||
|
||||
if eventType == "response.failed" {
|
||||
if hit, code, msg := detectOpenAICyberPolicy(message); hit {
|
||||
MarkOpsCyberPolicy(c, CyberPolicyMark{
|
||||
Code: code,
|
||||
Message: msg,
|
||||
Body: truncateString(string(message), 4096),
|
||||
UpstreamStatus: http.StatusOK,
|
||||
UpstreamInTok: usage.InputTokens,
|
||||
UpstreamOutTok: usage.OutputTokens,
|
||||
})
|
||||
}
|
||||
if eventType == "error" || eventType == "response.failed" {
|
||||
markOpenAICyberPolicyEvent(c, message, http.StatusOK, usage)
|
||||
}
|
||||
|
||||
if eventType == "error" {
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -94,3 +95,76 @@ func TestForwardOpenAIWSV2_KeepsOutboundAndObservedServiceTiersSeparate(t *testi
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardOpenAIWSV2_MarksCyberPolicyForFailureEventShapes(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
upstreamEvent []byte
|
||||
wantError bool
|
||||
wantInput int
|
||||
wantOutput int
|
||||
}{
|
||||
{
|
||||
name: "error_before_return",
|
||||
upstreamEvent: []byte(`{"type":"error","error":{"type":"rate_limit_error","code":"cyber_policy","message":"rate limit exceeded by cyber policy"},"usage":{"input_tokens":5,"output_tokens":1}}`),
|
||||
wantError: true,
|
||||
wantInput: 5,
|
||||
wantOutput: 1,
|
||||
},
|
||||
{
|
||||
name: "response_failed_terminal",
|
||||
upstreamEvent: []byte(`{"type":"response.failed","response":{"id":"resp_cyber","status":"failed","error":{"code":"cyber_policy","message":"blocked by cyber policy"},"usage":{"input_tokens":9,"output_tokens":2}}}`),
|
||||
wantInput: 9,
|
||||
wantOutput: 2,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil)
|
||||
|
||||
cfg := newOpenAIWSV2TestConfig()
|
||||
cfg.Security.URLAllowlist.Enabled = false
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
cfg.Gateway.OpenAIWS.MinIdlePerAccount = 0
|
||||
captureConn := &openAIWSCaptureConn{events: [][]byte{append([]byte(nil), tt.upstreamEvent...)}}
|
||||
pool := newOpenAIWSConnPool(cfg)
|
||||
pool.setClientDialerForTest(&openAIWSCaptureDialer{conn: captureConn})
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: cfg,
|
||||
httpUpstream: &httpUpstreamRecorder{},
|
||||
cache: &stubGatewayCache{},
|
||||
openaiWSResolver: NewOpenAIWSProtocolResolver(cfg),
|
||||
toolCorrector: NewCodexToolCorrector(),
|
||||
openaiWSPool: pool,
|
||||
}
|
||||
account := &Account{
|
||||
ID: 5883, Name: "openai-ws-v2-cyber", Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{"responses_websockets_v2_enabled": true},
|
||||
}
|
||||
|
||||
result, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-5.5","stream":false,"input":"hello"}`))
|
||||
if tt.wantError {
|
||||
require.Error(t, err)
|
||||
require.Nil(t, result)
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.False(t, errors.As(err, &failoverErr))
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
}
|
||||
|
||||
mark := GetOpsCyberPolicy(c)
|
||||
require.NotNil(t, mark)
|
||||
require.Equal(t, "cyber_policy", mark.Code)
|
||||
require.Equal(t, tt.wantInput, mark.UpstreamInTok)
|
||||
require.Equal(t, tt.wantOutput, mark.UpstreamOutTok)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -563,6 +563,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn(
|
||||
|
||||
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, openAIWSHTTPBridgeErrorBodyLimitBytes))
|
||||
_ = resp.Body.Close()
|
||||
markOpenAICyberPolicyEvent(c, respBody, resp.StatusCode, nil)
|
||||
if resp.StatusCode == http.StatusBadRequest &&
|
||||
extractUpstreamErrorCode(respBody) == openAIWSFallbackReasonInvalidEncryptedContent {
|
||||
s.markOpenAIWSInvalidEncryptedContentLineageFromPayload(
|
||||
@@ -589,7 +590,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn(
|
||||
if upstreamMsg == "" {
|
||||
upstreamMsg = http.StatusText(resp.StatusCode)
|
||||
}
|
||||
shouldFailover := s.shouldFailoverOpenAIUpstreamResponse(resp.StatusCode, upstreamMsg, respBody)
|
||||
shouldFailover := s.shouldFailoverOpenAIUpstreamResponse(account, resp.StatusCode, upstreamMsg, respBody)
|
||||
if account.Platform == PlatformGrok {
|
||||
shouldFailover = s.shouldFailoverGrokUpstreamError(resp.StatusCode, respBody)
|
||||
s.handleGrokAccountUpstreamError(withGrokTeamRateLimitModel(ctx, resolveGrokWSUpstreamModel(account, body, originalModel)), account, resp.StatusCode, resp.Header, respBody)
|
||||
@@ -776,6 +777,9 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn(
|
||||
if openAIWSMessageShouldParseUsage(eventType, upstreamMessage) {
|
||||
parseOpenAIWSResponseUsageFromCompletedEvent(upstreamMessage, &usage)
|
||||
}
|
||||
if eventType == "error" || eventType == "response.failed" {
|
||||
markOpenAICyberPolicyEvent(c, upstreamMessage, http.StatusOK, &usage)
|
||||
}
|
||||
imageCounter.AddSSEData(upstreamMessage)
|
||||
|
||||
if needModelReplace && len(mappedModelBytes) > 0 && openAIWSEventMayContainModel(eventType) && strings.Contains(trimmedData, mappedModel) {
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"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/pkg/tlsfingerprint"
|
||||
coderws "github.com/coder/websocket"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type httpBridgeIsolationBody struct {
|
||||
ctx context.Context
|
||||
prefix *bytes.Reader
|
||||
suffix *bytes.Reader
|
||||
release <-chan struct{}
|
||||
closed chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (b *httpBridgeIsolationBody) Read(p []byte) (int, error) {
|
||||
if b.prefix.Len() > 0 {
|
||||
return b.prefix.Read(p)
|
||||
}
|
||||
select {
|
||||
case <-b.release:
|
||||
return b.suffix.Read(p)
|
||||
case <-b.closed:
|
||||
return 0, io.EOF
|
||||
case <-b.ctx.Done():
|
||||
return 0, b.ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (b *httpBridgeIsolationBody) Close() error {
|
||||
b.once.Do(func() { close(b.closed) })
|
||||
return nil
|
||||
}
|
||||
|
||||
type httpBridgeIsolationRequest struct {
|
||||
input []string
|
||||
state string
|
||||
}
|
||||
|
||||
type httpBridgeIsolationUpstream struct {
|
||||
ctx context.Context
|
||||
mu sync.Mutex
|
||||
requests []httpBridgeIsolationRequest
|
||||
firstRelease chan struct{}
|
||||
}
|
||||
|
||||
func (u *httpBridgeIsolationUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = req.Body.Close()
|
||||
input := gjson.GetBytes(body, "input")
|
||||
var texts []string
|
||||
if input.Type == gjson.String {
|
||||
texts = append(texts, input.String())
|
||||
} else {
|
||||
for _, item := range input.Array() {
|
||||
if item.Type == gjson.String {
|
||||
texts = append(texts, item.String())
|
||||
continue
|
||||
}
|
||||
if item.Get("type").String() == "function_call" {
|
||||
texts = append(texts, item.Get("call_id").String())
|
||||
continue
|
||||
}
|
||||
if item.Get("type").String() == "function_call_output" {
|
||||
texts = append(texts, item.Get("output").String())
|
||||
continue
|
||||
}
|
||||
content := item.Get("content")
|
||||
if content.Type == gjson.String {
|
||||
texts = append(texts, content.String())
|
||||
} else {
|
||||
for _, part := range content.Array() {
|
||||
if text := part.Get("text"); text.Exists() {
|
||||
texts = append(texts, text.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(texts) == 0 {
|
||||
return nil, fmt.Errorf("missing bridge input")
|
||||
}
|
||||
u.mu.Lock()
|
||||
u.requests = append(u.requests, httpBridgeIsolationRequest{input: texts, state: req.Header.Get(openAIWSTurnStateHeader)})
|
||||
u.mu.Unlock()
|
||||
|
||||
id := texts[0]
|
||||
turn := 1
|
||||
if input.IsArray() {
|
||||
turn = 2
|
||||
}
|
||||
responseID := fmt.Sprintf("resp_%s_%d", id, turn)
|
||||
prefix := fmt.Sprintf("data: {\"type\":\"response.created\",\"response\":{\"id\":%q,\"status\":\"in_progress\"}}\n\n", responseID)
|
||||
if turn == 1 {
|
||||
prefix += "data: {\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"id\":\"rs_test\",\"type\":\"reasoning\",\"encrypted_content\":\"opaque\"}}\n\n"
|
||||
}
|
||||
output := "[]"
|
||||
if turn == 1 {
|
||||
output = fmt.Sprintf(`[{"type":"function_call","id":%q,"call_id":%q,"name":"lookup","arguments":"{}","status":"completed"}]`, "fc_"+id, "call_"+id)
|
||||
}
|
||||
suffix := fmt.Sprintf("data: {\"type\":\"response.completed\",\"response\":{\"id\":%q,\"status\":\"completed\",\"output\":%s,\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n", responseID, output)
|
||||
headers := http.Header{"Content-Type": []string{"text/event-stream"}}
|
||||
headers.Set(openAIWSTurnStateHeader, "turn-"+id)
|
||||
responseBody := io.NopCloser(strings.NewReader(prefix + suffix))
|
||||
if turn == 1 {
|
||||
responseBody = &httpBridgeIsolationBody{ctx: u.ctx, prefix: bytes.NewReader([]byte(prefix)), suffix: bytes.NewReader([]byte(suffix)), release: u.firstRelease, closed: make(chan struct{})}
|
||||
}
|
||||
return &http.Response{StatusCode: http.StatusOK, Header: headers, Body: responseBody}, nil
|
||||
}
|
||||
|
||||
func (u *httpBridgeIsolationUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
return u.Do(req, proxyURL, accountID, concurrency)
|
||||
}
|
||||
|
||||
func TestOpenAIWSHTTPBridgeSessionIsolationAcrossSameSessionHash(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
cfg := &config.Config{}
|
||||
cfg.Gateway.OpenAIWS.Enabled = true
|
||||
cfg.Gateway.OpenAIWS.OAuthEnabled = true
|
||||
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
|
||||
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
|
||||
cfg.Gateway.OpenAIWS.IngressModeDefault = OpenAIWSIngressModeHTTPBridge
|
||||
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 5
|
||||
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 5
|
||||
upstream := &httpBridgeIsolationUpstream{ctx: ctx, firstRelease: make(chan struct{})}
|
||||
stateStore := NewOpenAIWSStateStore(nil)
|
||||
svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), openaiWSStateStore: stateStore}
|
||||
account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth,
|
||||
Credentials: map[string]any{"access_token": "test-token"},
|
||||
Extra: map[string]any{"openai_oauth_responses_websockets_v2_mode": OpenAIWSIngressModeHTTPBridge},
|
||||
Concurrency: 2, Status: StatusActive, Schedulable: true}
|
||||
groupID := int64(7)
|
||||
newContext := func(r *http.Request) *gin.Context {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = r.Clone(ctx)
|
||||
c.Request.Header.Set("session-id", "shared-session")
|
||||
c.Set("api_key", &APIKey{ID: 11, GroupID: &groupID})
|
||||
return c
|
||||
}
|
||||
seedHash := svc.GenerateSessionHash(newContext(httptest.NewRequest(http.MethodGet, "/v1/responses", nil)), nil)
|
||||
stateStore.BindSessionTurnState(groupID, seedHash, "sentinel-turn-state", time.Hour)
|
||||
stateStore.BindSessionConn(groupID, seedHash, "sentinel-native-conn", time.Hour)
|
||||
|
||||
serverResults := make(chan error, 2)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := coderws.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
serverResults <- err
|
||||
return
|
||||
}
|
||||
defer func() { _ = conn.CloseNow() }()
|
||||
_, firstMessage, err := conn.Read(ctx)
|
||||
if err != nil {
|
||||
serverResults <- err
|
||||
return
|
||||
}
|
||||
c := newContext(r)
|
||||
// Match the handler-owned registration and nested forwarding call.
|
||||
preemptCtx, cleanup, _ := svc.BeginOpenAIWSIngressSessionPreemption(ctx, c, account, firstMessage)
|
||||
defer cleanup()
|
||||
hooks := &OpenAIWSIngressHooks{ClientLifecycleContext: ctx}
|
||||
serverResults <- svc.ProxyResponsesWebSocketFromClient(preemptCtx, c, conn, account, "test-token", firstMessage, hooks)
|
||||
}))
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(upstream.firstRelease) }) }
|
||||
defer func() {
|
||||
release()
|
||||
cancel()
|
||||
server.Close()
|
||||
}()
|
||||
|
||||
readEvent := func(conn *coderws.Conn, wantType string) []byte {
|
||||
t.Helper()
|
||||
_, event, err := conn.Read(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, wantType, gjson.GetBytes(event, "type").String(), "event: %s", event)
|
||||
return event
|
||||
}
|
||||
clients := make([]*coderws.Conn, 0, 2)
|
||||
for _, id := range []string{"alpha", "beta"} {
|
||||
conn, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http"), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = conn.CloseNow() }()
|
||||
clients = append(clients, conn)
|
||||
payload := fmt.Sprintf(`{"type":"response.create","model":"gpt-5","prompt_cache_key":%q,"client_metadata":{"thread_id":%q},"input":%q}`, id+"-cache", id+"-thread", id)
|
||||
require.NoError(t, conn.Write(ctx, coderws.MessageText, []byte(payload)))
|
||||
readEvent(conn, "response.created")
|
||||
readEvent(conn, "response.output_item.added")
|
||||
}
|
||||
// Both HTTP streams are now in flight. Neither may replace the other.
|
||||
release()
|
||||
for i, id := range []string{"alpha", "beta"} {
|
||||
event := readEvent(clients[i], "response.completed")
|
||||
require.Equal(t, "resp_"+id+"_1", gjson.GetBytes(event, "response.id").String())
|
||||
}
|
||||
for i, id := range []string{"alpha", "beta"} {
|
||||
payload := fmt.Sprintf(`{"type":"response.create","model":"gpt-5","previous_response_id":%q,"input":[{"type":"function_call_output","call_id":%q,"output":%q}]}`, "resp_"+id+"_1", "call_"+id, id+"-result")
|
||||
require.NoError(t, clients[i].Write(ctx, coderws.MessageText, []byte(payload)))
|
||||
readEvent(clients[i], "response.created")
|
||||
event := readEvent(clients[i], "response.completed")
|
||||
require.Equal(t, "resp_"+id+"_2", gjson.GetBytes(event, "response.id").String())
|
||||
require.NoError(t, clients[i].Close(coderws.StatusNormalClosure, "done"))
|
||||
}
|
||||
for range clients {
|
||||
select {
|
||||
case err := <-serverResults:
|
||||
require.NoError(t, err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
}
|
||||
|
||||
upstream.mu.Lock()
|
||||
requests := append([]httpBridgeIsolationRequest(nil), upstream.requests...)
|
||||
upstream.mu.Unlock()
|
||||
require.ElementsMatch(t, []httpBridgeIsolationRequest{
|
||||
{input: []string{"alpha"}},
|
||||
{input: []string{"beta"}},
|
||||
{input: []string{"alpha", "call_alpha", "alpha-result"}, state: "turn-alpha"},
|
||||
{input: []string{"beta", "call_beta", "beta-result"}, state: "turn-beta"},
|
||||
}, requests)
|
||||
gotState, ok := stateStore.GetSessionTurnState(groupID, seedHash)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "sentinel-turn-state", gotState)
|
||||
gotConn, ok := stateStore.GetSessionConn(groupID, seedHash)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "sentinel-native-conn", gotConn)
|
||||
}
|
||||
Loaded 100 of 252 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user