mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 16:04:24 +00:00
644 lines
27 KiB
Go
644 lines
27 KiB
Go
package handler
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"net/http"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/Wei-Shaw/sub2api/internal/pkg/ip"
|
||
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/tidwall/gjson"
|
||
"go.uber.org/zap"
|
||
)
|
||
|
||
// ChatCompletions handles OpenAI Chat Completions API endpoint for Anthropic platform groups.
|
||
// POST /v1/chat/completions
|
||
// This converts Chat Completions requests to Anthropic format (via Responses format chain),
|
||
// forwards to Anthropic upstream, and converts responses back to Chat Completions format.
|
||
func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||
streamStarted := false
|
||
|
||
requestStart := time.Now()
|
||
|
||
apiKey, ok := middleware2.GetAPIKeyFromContext(c)
|
||
if !ok {
|
||
h.chatCompletionsErrorResponse(c, http.StatusUnauthorized, "authentication_error", "Invalid API key")
|
||
return
|
||
}
|
||
|
||
subject, ok := middleware2.GetAuthSubjectFromContext(c)
|
||
if !ok {
|
||
h.chatCompletionsErrorResponse(c, http.StatusInternalServerError, "api_error", "User context not found")
|
||
return
|
||
}
|
||
reqLog := requestLogger(
|
||
c,
|
||
"handler.gateway.chat_completions",
|
||
zap.Int64("user_id", subject.UserID),
|
||
zap.Int64("api_key_id", apiKey.ID),
|
||
zap.Any("group_id", apiKey.GroupID),
|
||
)
|
||
|
||
// Read request body
|
||
body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
|
||
if err != nil {
|
||
if handleRequestBodyReadError(c, reqLog, err) {
|
||
return
|
||
}
|
||
status, message := requestBodyReadFailure(reqLog, c.Request, err)
|
||
h.chatCompletionsErrorResponse(c, status, "invalid_request_error", message)
|
||
return
|
||
}
|
||
|
||
if len(body) == 0 {
|
||
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Request body is empty")
|
||
return
|
||
}
|
||
|
||
setOpsRequestContext(c, "", false)
|
||
|
||
// Validate JSON
|
||
if !gjson.ValidBytes(body) {
|
||
logRequestBodyParseFailure(reqLog, body, nil)
|
||
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body")
|
||
return
|
||
}
|
||
|
||
// Extract model and stream
|
||
modelResult := gjson.GetBytes(body, "model")
|
||
if !modelResult.Exists() || modelResult.Type != gjson.String || modelResult.String() == "" {
|
||
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required")
|
||
return
|
||
}
|
||
reqModel := modelResult.String()
|
||
bindRequestedReasoningEffort(c, body, reqModel)
|
||
ensureCompositeTargetPlatform(c, apiKey, reqModel)
|
||
if !compositeTargetPlatformResolved(c, apiKey, reqModel) {
|
||
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by composite groups")
|
||
return
|
||
}
|
||
if rejectSystemOneOnlyPlatform(c, apiKey, h.chatCompletionsErrorResponse) {
|
||
return
|
||
}
|
||
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
|
||
respondOpenAIReasoningEffortPolicyError(c, err, h.chatCompletionsErrorResponse)
|
||
return
|
||
} else if changed {
|
||
body = cappedBody
|
||
}
|
||
reqStream, ok := parseOpenAICompatibleStream(body)
|
||
if !ok {
|
||
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
|
||
return
|
||
}
|
||
if service.IsGPTImageGenerationModel(reqModel) {
|
||
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "This model is not supported on the Chat Completions endpoint")
|
||
return
|
||
}
|
||
reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream))
|
||
|
||
setOpsRequestContext(c, reqModel, reqStream)
|
||
setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(reqStream, false)))
|
||
pricingCtx, pricingAt := service.WithGatewayTokenRequestPricing(c.Request.Context())
|
||
c.Request = c.Request.WithContext(pricingCtx)
|
||
|
||
// 解析渠道级模型映射
|
||
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
|
||
|
||
// Claude Code only restriction: /v1/chat/completions is never a Claude Code
|
||
// endpoint. With a fallback group the request continues and account selection
|
||
// (checkClaudeCodeRestriction) schedules it in the fallback group; without one
|
||
// it is rejected here.
|
||
if apiKey.Group != nil && apiKey.Group.ClaudeCodeOnly && apiKey.Group.FallbackGroupID == nil {
|
||
h.chatCompletionsErrorResponse(c, http.StatusForbidden, "permission_error",
|
||
"This group is restricted to Claude Code clients (/v1/messages only)")
|
||
return
|
||
}
|
||
if geminiImageGenerationRejected(c, apiKey, nil, reqModel, channelMapping.MappedModel) {
|
||
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage())
|
||
return
|
||
}
|
||
|
||
if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIChat, reqModel, body); decision != nil && !decision.AllowNextStage {
|
||
h.openAISecurityAuditError(c, decision)
|
||
return
|
||
}
|
||
|
||
// Error passthrough binding
|
||
if h.errorPassthroughService != nil {
|
||
service.BindErrorPassthroughService(c, h.errorPassthroughService)
|
||
}
|
||
|
||
subscription, _ := middleware2.GetSubscriptionFromContext(c)
|
||
|
||
service.SetOpsLatencyMs(c, service.OpsAuthLatencyMsKey, time.Since(requestStart).Milliseconds())
|
||
|
||
userReleaseFunc, err := h.concurrencyHelper.AcquireUserSlotWithWait(c, subject.UserID, subject.Concurrency, reqStream, &streamStarted)
|
||
if err != nil {
|
||
reqLog.Warn("gateway.cc.user_slot_acquire_failed", zap.Error(err))
|
||
h.handleConcurrencyError(c, err, "user", streamStarted)
|
||
return
|
||
}
|
||
userReleaseFunc = wrapReleaseOnDone(c.Request.Context(), userReleaseFunc)
|
||
if userReleaseFunc != nil {
|
||
defer userReleaseFunc()
|
||
}
|
||
|
||
// 2. Re-check billing
|
||
if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil {
|
||
reqLog.Info("gateway.cc.billing_check_failed", zap.Error(err))
|
||
status, code, message, retryAfter := billingErrorDetails(err)
|
||
if retryAfter > 0 {
|
||
c.Header("Retry-After", strconv.Itoa(retryAfter))
|
||
}
|
||
h.chatCompletionsErrorResponse(c, status, code, message)
|
||
return
|
||
}
|
||
|
||
// 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。
|
||
inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body))
|
||
if err != nil {
|
||
reqLog.Info("gateway.cc.inflight_reservation_rejected", zap.Error(err))
|
||
status, code, message, retryAfter := billingErrorDetails(err)
|
||
if retryAfter > 0 {
|
||
c.Header("Retry-After", strconv.Itoa(retryAfter))
|
||
}
|
||
h.chatCompletionsErrorResponse(c, status, code, message)
|
||
return
|
||
}
|
||
defer inflightRelease()
|
||
|
||
// Parse request for session hash
|
||
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
|
||
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。
|
||
bodyRef := service.NewRequestBodyRef(body)
|
||
parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "chat_completions")
|
||
if parsedReq == nil {
|
||
parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef}
|
||
}
|
||
parsedReq.SessionContext = &service.SessionContext{
|
||
ClientIP: ip.GetClientIP(c),
|
||
UserAgent: c.GetHeader("User-Agent"),
|
||
APIKeyID: apiKey.ID,
|
||
}
|
||
sessionHash := h.gatewayService.GenerateSessionHash(parsedReq)
|
||
groupPlatform := effectiveAPIKeyPlatform(c, apiKey)
|
||
selectionSessionHash := sessionHash
|
||
if groupPlatform == service.PlatformGemini && selectionSessionHash != "" {
|
||
selectionSessionHash = "gemini:" + selectionSessionHash
|
||
}
|
||
// composite 账号池请求状态(B2:generic CC 循环池化)。池激活判定与 generic
|
||
// 调度器共用同一谓词(ctx 携带候选池且无 resolved 平台);非池请求 poolDenials
|
||
// 恒为空、attempt 策略与委派分支不生效,整条路径零变化。
|
||
isPoolRequest := service.GenericCompositePoolActive(c.Request.Context())
|
||
if isPoolRequest && h.rejectCompositePoolCyberSessionBlocked(c, apiKey, body, reqModel, cyberBlockFormatChat) {
|
||
return
|
||
}
|
||
poolDenials := newCompositePoolPlatformDenials()
|
||
// 委派 CC 链的 promptCacheKey 语义对齐 OpenAI handler CC 路径(headers →
|
||
// prompt_cache_key 提取,仅池激活时计算,非池请求不新增解析)。
|
||
var poolPromptCacheKey string
|
||
if isPoolRequest {
|
||
poolPromptCacheKey = h.openAIGatewayService.ExtractSessionID(c, body)
|
||
}
|
||
// 3. Account selection + failover loop
|
||
fs := NewFailoverState(h.maxAccountSwitches, false)
|
||
if groupPlatform == service.PlatformGemini {
|
||
fs = NewFailoverState(h.maxAccountSwitchesGemini, false)
|
||
}
|
||
var lastPolicyFailure compositePoolAttemptPolicyFailure
|
||
schedAPIKey := apiKey
|
||
schedChannelMapping := channelMapping
|
||
schedReqModel := reqModel
|
||
|
||
for {
|
||
if failoverClientGone(c) {
|
||
return
|
||
}
|
||
// 池请求把业务限制 deny 过的平台按 deniedPlatforms 整平台 mask 后重选
|
||
//(候选池 immutable,mask 只叠加在当前请求 ctx 之上);无 deny 时
|
||
// 返回原 ctx,非池请求不经此分支,选号 ctx 与原行为一致。
|
||
selectCtx := c.Request.Context()
|
||
if isPoolRequest {
|
||
if maskedCtx, ok := compositePoolSelectionRetryContext(selectCtx, poolDenials); ok {
|
||
selectCtx = maskedCtx
|
||
}
|
||
}
|
||
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(selectCtx, schedAPIKey.GroupID, selectionSessionHash, schedReqModel, fs.FailedAccountIDs, "", int64(0))
|
||
if err != nil {
|
||
if failoverClientGone(c) {
|
||
reqLog.Info("gateway.cc.account_select_aborted_client_disconnected", zap.Error(err))
|
||
return
|
||
}
|
||
if len(fs.FailedAccountIDs) == 0 {
|
||
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, reqModel, reqModel, groupPlatform)
|
||
cls = classifySelectionFailureError(err, cls)
|
||
if !cls.ModelNotFound {
|
||
markOpsRoutingCapacityLimitedIfNoAvailable(c, err)
|
||
}
|
||
message := cls.Message
|
||
if !cls.ModelNotFound {
|
||
message = "No available accounts: " + err.Error()
|
||
}
|
||
h.chatCompletionsErrorResponse(c, cls.Status, cls.ErrType, message)
|
||
return
|
||
}
|
||
action := fs.HandleSelectionExhausted(c.Request.Context())
|
||
switch action {
|
||
case FailoverContinue:
|
||
continue
|
||
case FailoverCanceled:
|
||
failoverClientGone(c)
|
||
return
|
||
default:
|
||
if fs.LastFailoverErr != nil {
|
||
h.handleCCFailoverExhausted(c, fs.LastFailoverErr, streamStarted)
|
||
} else if lastPolicyFailure.denied() {
|
||
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
|
||
if streamStarted {
|
||
h.handleStreamingAwareError(cc, status, code, message, true)
|
||
return
|
||
}
|
||
h.chatCompletionsErrorResponse(cc, status, code, message)
|
||
}
|
||
respondCompositePoolAttemptPolicyFailure(c, lastPolicyFailure, streamAwareWrite)
|
||
} else if streamStarted {
|
||
h.handleStreamingAwareError(c, http.StatusBadGateway, "server_error", "All available accounts exhausted", true)
|
||
} else {
|
||
h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "server_error", "All available accounts exhausted")
|
||
}
|
||
return
|
||
}
|
||
}
|
||
account := selection.Account
|
||
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
|
||
return
|
||
}
|
||
prevQuotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||
var switchedGroup bool
|
||
var nextCtx context.Context
|
||
schedAPIKey, nextCtx, schedChannelMapping, schedReqModel, isPoolRequest, poolDenials, switchedGroup = h.syncSelectionEffectiveGroup(
|
||
c, apiKey, schedAPIKey, c.Request.Context(), schedChannelMapping, reqModel, schedReqModel, isPoolRequest, poolDenials, selection)
|
||
if switchedGroup && compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && poolPromptCacheKey == "" && h.openAIGatewayService != nil {
|
||
poolPromptCacheKey = h.openAIGatewayService.ExtractSessionID(c, body)
|
||
}
|
||
if switchedGroup && !isPoolRequest {
|
||
if nextQuotaPlatform := service.QuotaPlatform(nextCtx, apiKey); nextQuotaPlatform != "" && nextQuotaPlatform != prevQuotaPlatform {
|
||
if quotaErr := compositePoolAttemptQuotaError(h.billingCacheService, nextCtx, apiKey, subscription, nextQuotaPlatform); quotaErr != nil {
|
||
releaseCompositePoolSelection(selection)
|
||
h.gatewayService.ReleaseAccountSession(context.Background(), account, selectionSessionHash)
|
||
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
|
||
if streamStarted {
|
||
h.handleStreamingAwareError(cc, status, code, message, true)
|
||
return
|
||
}
|
||
h.chatCompletionsErrorResponse(cc, status, code, message)
|
||
}
|
||
respondCompositePoolAttemptPolicyFailure(c, compositePoolAttemptPolicyFailure{QuotaErr: quotaErr}, streamAwareWrite)
|
||
return
|
||
}
|
||
}
|
||
}
|
||
setOpsSelectedAccount(c, account.ID, account.Platform)
|
||
|
||
// composite 账号池 per-attempt 平台策略:对实际选中平台补做 user×platform
|
||
// 配额预检与渠道映射/限制(准入 CheckBillingEligibility 时池没有 resolved
|
||
// 平台、这两个维度被跳过;不得只后扣不预检)。检查为纯读,不写 RPM/计数,
|
||
// 放在槽位获取前:deny 不占并发槽。CC 循环无 previous_response_id 状态,
|
||
// 无 pinned 分支;deny 记入 poolDenials 后按 masked 候选池整平台重选,
|
||
// 候选全部被业务限制时按原语义终止,不误报 model unsupported。
|
||
attemptPolicy := compositePoolAttemptPolicy{AttemptCtx: c.Request.Context(), Mapping: schedChannelMapping}
|
||
isPoolAttempt := false
|
||
if isPoolRequest && compositePoolAttemptPolicyApplies(c, schedAPIKey) {
|
||
attemptPolicy = evaluateCompositePoolAttemptPolicyForBillingGroup(
|
||
c.Request.Context(), h.billingCacheService, h.openAIGatewayService, apiKey, schedAPIKey, subscription, account, reqModel, false)
|
||
isPoolAttempt = true
|
||
if attemptPolicy.Failure.denied() {
|
||
releaseCompositePoolSelection(selection)
|
||
// 选号链可能已为该账号注册会话槽(键与选号一致):排除前释放
|
||
//(镜像 Messages 池分支)。
|
||
h.gatewayService.ReleaseAccountSession(context.Background(), account, selectionSessionHash)
|
||
if attemptPolicy.Failure.deniesPlatform() {
|
||
poolDenials.deny(account.Platform)
|
||
}
|
||
lastPolicyFailure = attemptPolicy.Failure
|
||
fs.FailedAccountIDs[account.ID] = struct{}{}
|
||
// 候选全部被业务限制:按 deny 原因明确终止(后续重选不再尝试)。
|
||
if _, ok := compositePoolSelectionRetryContext(c.Request.Context(), poolDenials); !ok {
|
||
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
|
||
if streamStarted {
|
||
h.handleStreamingAwareError(cc, status, code, message, true)
|
||
return
|
||
}
|
||
h.chatCompletionsErrorResponse(cc, status, code, message)
|
||
}
|
||
respondCompositePoolAttemptPolicyFailure(c, attemptPolicy.Failure, streamAwareWrite)
|
||
return
|
||
}
|
||
continue
|
||
}
|
||
}
|
||
|
||
// 4. Acquire account concurrency slot
|
||
accountReleaseFunc := selection.ReleaseFunc
|
||
if !selection.Acquired {
|
||
if selection.WaitPlan == nil {
|
||
markOpsRoutingCapacityLimited(c)
|
||
h.chatCompletionsErrorResponse(c, http.StatusServiceUnavailable, "api_error", "No available accounts")
|
||
return
|
||
}
|
||
accountReleaseFunc, err = h.concurrencyHelper.AcquireAccountSlotWithWaitTimeout(
|
||
c,
|
||
account.ID,
|
||
selection.WaitPlan.MaxConcurrency,
|
||
selection.WaitPlan.Timeout,
|
||
reqStream,
|
||
&streamStarted,
|
||
)
|
||
if err != nil {
|
||
reqLog.Warn("gateway.cc.account_slot_acquire_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||
h.handleConcurrencyError(c, err, "account", streamStarted)
|
||
return
|
||
}
|
||
}
|
||
// 终检与准入后绑定使用选号结果携带的门(见 responses 同名注释)。
|
||
admissionCtx := service.ContextWithSelectionProfitGate(c.Request.Context(), selection)
|
||
latest, vetoed, reason := h.gatewayService.GatewayProfitControlVetoLatest(admissionCtx, account)
|
||
if vetoed {
|
||
if accountReleaseFunc != nil {
|
||
accountReleaseFunc()
|
||
}
|
||
reqLog.Debug("gateway.cc.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
|
||
if fs.RecordProfitVeto(account.ID) == FailoverExhausted {
|
||
reqLog.Warn("gateway.cc.profit_veto_attempts_exhausted", zap.Int("profit_veto_count", fs.ProfitVetoCount()))
|
||
h.chatCompletionsErrorResponse(c, http.StatusServiceUnavailable, "api_error", profitVetoExhaustedMessage)
|
||
return
|
||
}
|
||
continue
|
||
}
|
||
account = latest
|
||
selection.Account = latest
|
||
if selection.ProfitGateActive() {
|
||
if err := h.gatewayService.BindStickySessionAfterProfitAdmission(admissionCtx, apiKey.GroupID, selectionSessionHash, account.ID); err != nil {
|
||
reqLog.Warn("gateway.cc.bind_sticky_session_after_profit_admission_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||
}
|
||
}
|
||
accountReleaseFunc = wrapReleaseOnDone(c.Request.Context(), accountReleaseFunc)
|
||
|
||
if groupPlatform == service.PlatformGemini && account.Platform != service.PlatformGemini {
|
||
if accountReleaseFunc != nil {
|
||
accountReleaseFunc()
|
||
}
|
||
fs.FailedAccountIDs[account.ID] = struct{}{}
|
||
continue
|
||
}
|
||
|
||
// 5. Forward request
|
||
writerSizeBeforeForward := c.Writer.Size()
|
||
// 渠道模型映射只作用于本次账号尝试:池请求按选中平台的渠道映射(attempt
|
||
// 策略产出,platform-scoped)派生,非池保持请求级映射语义不变。
|
||
attemptChannelMapping := schedChannelMapping
|
||
if isPoolAttempt {
|
||
attemptChannelMapping = attemptPolicy.Mapping
|
||
}
|
||
billingChannelMapping := resolveBillingChannelMappingForAttempt(apiKey, schedAPIKey, channelMapping, attemptChannelMapping)
|
||
forwardBody := body
|
||
if attemptChannelMapping.Mapped {
|
||
forwardBody = h.gatewayService.ReplaceModelInBody(body, attemptChannelMapping.MappedModel)
|
||
}
|
||
// 账号池按选中账号应用分组推理强度策略(与单目标同语义,覆盖 openai / anthropic 账号)。
|
||
if isPoolRequest {
|
||
cappedBody, changed, policyErr := applyCompositePoolReasoningEffortPolicyForSelectedAccount(c, schedAPIKey, account, forwardBody)
|
||
if policyErr != nil {
|
||
if accountReleaseFunc != nil {
|
||
accountReleaseFunc()
|
||
}
|
||
h.gatewayService.ReleaseAccountSession(context.Background(), account, selectionSessionHash)
|
||
streamAwareWrite := func(cc *gin.Context, status int, code, message string) {
|
||
if streamStarted {
|
||
h.handleStreamingAwareError(cc, status, code, message, true)
|
||
return
|
||
}
|
||
h.chatCompletionsErrorResponse(cc, status, code, message)
|
||
}
|
||
respondOpenAIReasoningEffortPolicyError(c, policyErr, streamAwareWrite)
|
||
return
|
||
}
|
||
if changed {
|
||
forwardBody = cappedBody
|
||
}
|
||
}
|
||
var result *service.ForwardResult
|
||
// 池委派 OpenAI 网关链时的原始结果:按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。
|
||
var delegatedResult *service.OpenAIForwardResult
|
||
delegated := false
|
||
setActualUpstreamEndpoint(c, "")
|
||
// 池请求的 attempt 局部 ctx 携带选中平台(不写回 c.Request):forward 内的
|
||
// 渠道定价作用域与计费 QuotaPlatform 跟随实际平台,对齐 Messages 池 attempt 语义。
|
||
attemptCtx := c.Request.Context()
|
||
if isPoolRequest {
|
||
attemptCtx = compositePoolAttemptContext(attemptCtx, account)
|
||
}
|
||
if account.Platform == service.PlatformGemini {
|
||
if h.geminiCompatService == nil {
|
||
h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "upstream_error", "Gemini compatibility service is not configured")
|
||
if accountReleaseFunc != nil {
|
||
accountReleaseFunc()
|
||
}
|
||
return
|
||
}
|
||
result, err = h.geminiCompatService.ForwardAsChatCompletions(attemptCtx, c, account, forwardBody)
|
||
} else if shouldUseAntigravityCompat(account) {
|
||
if h.antigravityGatewayService == nil {
|
||
h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "upstream_error", "Antigravity compatibility service is not configured")
|
||
if accountReleaseFunc != nil {
|
||
accountReleaseFunc()
|
||
}
|
||
return
|
||
}
|
||
setActualUpstreamEndpoint(c, EndpointAntigravityGenerateContent)
|
||
result, err = h.antigravityGatewayService.ForwardAsChatCompletions(attemptCtx, c, account, forwardBody, parsedReq)
|
||
} else if compositeOrPoolDispatchActive(isPoolRequest, schedAPIKey) && compositePoolAccountDelegatesChatCompletionsToOpenAI(account) {
|
||
// OpenAI 兼容族账号在池激活时委派 OpenAI 网关 CC 链:入站同族优先
|
||
//(零转换,adaptive 账号由该链直转供应商原生 CC 端点),响应写回与
|
||
// failover 错误信封都由该链完成,错误信封已是 OpenAI CC 风格,不再二次
|
||
// 包装。defaultMappedModel 传 "",与 OpenAI handler CC 路径一致。
|
||
openAIResult, delegateErr := h.openAIGatewayService.ForwardAsChatCompletions(
|
||
attemptCtx, c, account, forwardBody, poolPromptCacheKey, "")
|
||
delegated = true
|
||
delegatedResult = openAIResult
|
||
result = adaptOpenAIForwardResultToForwardResult(openAIResult)
|
||
err = delegateErr
|
||
} else {
|
||
result, err = h.gatewayService.ForwardAsChatCompletions(attemptCtx, c, account, forwardBody, parsedReq)
|
||
}
|
||
|
||
if accountReleaseFunc != nil {
|
||
accountReleaseFunc()
|
||
}
|
||
if delegated {
|
||
h.recordDelegatedCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, body, clientRequestedUsageFields(c, billingChannelMapping, reqModel, ""))
|
||
}
|
||
|
||
// 池委派 OpenAI 网关链的结果按 OpenAI 口径入账(见 submitDelegatedOpenAIUsage)。
|
||
submitDelegatedUsage := func() {
|
||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||
if isPoolAttempt {
|
||
quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey)
|
||
}
|
||
h.submitDelegatedOpenAIUsage(c, delegatedOpenAIUsage{
|
||
Result: delegatedResult,
|
||
APIKey: apiKey,
|
||
Account: account,
|
||
Subscription: subscription,
|
||
QuotaPlatform: quotaPlatform,
|
||
PricingAt: pricingAt,
|
||
RequestPayloadHash: service.HashUsageRequestPayload(body),
|
||
ChannelUsageFields: clientRequestedUsageFields(c, billingChannelMapping, reqModel, delegatedResult.UpstreamModel),
|
||
LogComponent: "handler.gateway.chat_completions",
|
||
})
|
||
}
|
||
|
||
// 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果"
|
||
// 错误路径共用;failover 错误恒定 result=nil,不会重复计费。
|
||
submitForwardUsage := func(result *service.ForwardResult) {
|
||
userAgent := c.GetHeader("User-Agent")
|
||
clientIP := ip.GetClientIP(c)
|
||
requestPayloadHash := service.HashUsageRequestPayload(body)
|
||
inboundEndpoint := GetInboundEndpoint(c)
|
||
upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
|
||
|
||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||
// 池请求按选中平台计量 user×platform 配额(attempt ctx 携带 resolved
|
||
// 平台);非池保持准入语义不变。
|
||
if isPoolAttempt {
|
||
quotaPlatform = service.QuotaPlatform(attemptPolicy.AttemptCtx, apiKey)
|
||
}
|
||
sessionID := service.ExtractClientSessionID(c)
|
||
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
|
||
channelUsageFields := clientRequestedUsageFields(c, billingChannelMapping, reqModel, result.UpstreamModel)
|
||
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
|
||
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
|
||
Result: result,
|
||
QuotaPlatform: quotaPlatform,
|
||
APIKey: apiKey,
|
||
User: apiKey.User,
|
||
Account: account,
|
||
Subscription: subscription,
|
||
PricingAt: pricingAt,
|
||
InboundEndpoint: inboundEndpoint,
|
||
UpstreamEndpoint: upstreamEndpoint,
|
||
UserAgent: userAgent,
|
||
IPAddress: clientIP,
|
||
RequestPayloadHash: requestPayloadHash,
|
||
APIKeyService: h.apiKeyService,
|
||
SessionID: sessionID,
|
||
ChannelUsageFields: channelUsageFields,
|
||
}); err != nil {
|
||
reqLog.Error("gateway.cc.record_usage_failed",
|
||
zap.Int64("account_id", account.ID),
|
||
zap.Error(err),
|
||
)
|
||
}
|
||
})
|
||
}
|
||
|
||
if err != nil {
|
||
var failoverErr *service.UpstreamFailoverError
|
||
if errors.As(err, &failoverErr) {
|
||
if c.Writer.Size() != writerSizeBeforeForward {
|
||
h.handleCCFailoverExhausted(c, failoverErr, true)
|
||
return
|
||
}
|
||
action := fs.HandleFailoverError(c.Request.Context(), h.gatewayService, account.ID, account.Platform, account.GetPoolModeRetryCount(), failoverErr)
|
||
switch action {
|
||
case FailoverContinue:
|
||
continue
|
||
case FailoverExhausted:
|
||
h.handleCCFailoverExhausted(c, fs.LastFailoverErr, streamStarted)
|
||
return
|
||
case FailoverCanceled:
|
||
failoverClientGone(c)
|
||
return
|
||
}
|
||
}
|
||
upstreamErrorAlreadyCommunicated := compositePoolDelegatedForwardErrorAlreadyCommunicated(c, delegated, writerSizeBeforeForward, err)
|
||
wroteFallback := false
|
||
if !upstreamErrorAlreadyCommunicated {
|
||
wroteFallback = h.ensureForwardErrorResponse(c, streamStarted)
|
||
}
|
||
reqLog.Error("gateway.cc.forward_failed",
|
||
zap.Int64("account_id", account.ID),
|
||
zap.Bool("fallback_error_response_written", wroteFallback),
|
||
zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated),
|
||
zap.Error(err),
|
||
)
|
||
h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(c.Request.Context()), apiKey.GroupID, selectionSessionHash, account.ID, err)
|
||
// 委派链流中断与 OpenAI handler 同语义:上游已计量的部分 usage 照常入账(#5148);
|
||
// failover 错误恒定 result=nil,不会重复计费。
|
||
if delegatedResult != nil {
|
||
submitDelegatedUsage()
|
||
} else if result != nil {
|
||
submitForwardUsage(result)
|
||
}
|
||
return
|
||
}
|
||
|
||
// 6. Record usage
|
||
if delegatedResult != nil {
|
||
submitDelegatedUsage()
|
||
} else {
|
||
submitForwardUsage(result)
|
||
}
|
||
return
|
||
}
|
||
}
|
||
|
||
// chatCompletionsErrorResponse writes an error in OpenAI Chat Completions format.
|
||
func (h *GatewayHandler) chatCompletionsErrorResponse(c *gin.Context, status int, errType, message string) {
|
||
c.JSON(status, gin.H{
|
||
"error": gin.H{
|
||
"type": errType,
|
||
"message": message,
|
||
},
|
||
})
|
||
}
|
||
|
||
// handleCCFailoverExhausted writes a failover-exhausted error in CC format.
|
||
func (h *GatewayHandler) handleCCFailoverExhausted(c *gin.Context, lastErr *service.UpstreamFailoverError, streamStarted bool) {
|
||
if streamStarted {
|
||
return
|
||
}
|
||
if lastErr != nil {
|
||
applyRateLimitRetryAfter(c, lastErr, h.cfg)
|
||
}
|
||
if lastErr != nil && lastErr.IsCredentialFailure() {
|
||
status, message := credentialFailoverClientResponse(lastErr)
|
||
h.chatCompletionsErrorResponse(c, status, "server_error", message)
|
||
return
|
||
}
|
||
if lastErr != nil && lastErr.IsOpenAICapacityShed() && strings.TrimSpace(lastErr.ClientMessage) != "" {
|
||
status := lastErr.ClientStatusCode
|
||
if status <= 0 {
|
||
status = http.StatusServiceUnavailable
|
||
}
|
||
h.chatCompletionsErrorResponse(c, status, "server_error", lastErr.ClientMessage)
|
||
return
|
||
}
|
||
statusCode := http.StatusBadGateway
|
||
if lastErr != nil && lastErr.StatusCode > 0 {
|
||
statusCode = lastErr.StatusCode
|
||
}
|
||
if lastErr != nil && service.IsOpenAISilentRefusalErrorBody(lastErr.ResponseBody) {
|
||
service.SetOpsUpstreamError(c, statusCode, service.OpenAISilentRefusalClientMessage(), "")
|
||
h.chatCompletionsErrorResponse(c, http.StatusBadGateway, "upstream_error", service.OpenAISilentRefusalClientMessage())
|
||
return
|
||
}
|
||
h.chatCompletionsErrorResponse(c, statusCode, "server_error", "All available accounts exhausted")
|
||
}
|