mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 16:04:24 +00:00
refactor(signature): extract retry body-transform into Rectifier strategy
Introduce internal/service/signature package with ClaudeRectifier and AntigravityRectifier interfaces plus StripClaudeRectifier / StripAntigravityRectifier implementations that wrap the legacy FilterThinkingBlocksForRetry / FilterSignatureSensitiveBlocksForRetry and stripThinkingFromClaudeRequest / stripSignatureSensitiveBlocksFromClaudeRequest functions. Refactor the Claude and Antigravity retry loops (including count_tokens) to delegate body transformation to the rectifier, keeping all surrounding scaffolding (ops events, logging, time budget checks, HTTP plumbing) unchanged. Also extracts the looksLikeToolSignatureError predicate previously inlined as an anonymous closure. Zero behavior change: all existing unit tests pass unchanged. This prepares for Phase 2 where a Pool strategy will be plugged in via the same interface.
This commit is contained in:
1 parent
2a7272429f
commit
84adf1d6de
3 files changed
+228
-52
No files matched your search
@@ -22,6 +22,7 @@ import (
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service/signature"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/tidwall/gjson"
|
||||
@@ -870,14 +871,15 @@ func logPrefix(sessionID, accountName string) string {
|
||||
|
||||
// AntigravityGatewayService 处理 Antigravity 平台的 API 转发
|
||||
type AntigravityGatewayService struct {
|
||||
accountRepo AccountRepository
|
||||
tokenProvider *AntigravityTokenProvider
|
||||
rateLimitService *RateLimitService
|
||||
httpUpstream HTTPUpstream
|
||||
settingService *SettingService
|
||||
cache GatewayCache // 用于模型级限流时清除粘性会话绑定
|
||||
schedulerSnapshot *SchedulerSnapshotService
|
||||
internal500Cache Internal500CounterCache // INTERNAL 500 渐进惩罚计数器
|
||||
accountRepo AccountRepository
|
||||
tokenProvider *AntigravityTokenProvider
|
||||
rateLimitService *RateLimitService
|
||||
httpUpstream HTTPUpstream
|
||||
settingService *SettingService
|
||||
cache GatewayCache // 用于模型级限流时清除粘性会话绑定
|
||||
schedulerSnapshot *SchedulerSnapshotService
|
||||
internal500Cache Internal500CounterCache // INTERNAL 500 渐进惩罚计数器
|
||||
signatureRectifier signature.AntigravityRectifier
|
||||
}
|
||||
|
||||
func NewAntigravityGatewayService(
|
||||
@@ -899,6 +901,10 @@ func NewAntigravityGatewayService(
|
||||
cache: cache,
|
||||
schedulerSnapshot: schedulerSnapshot,
|
||||
internal500Cache: internal500Cache,
|
||||
signatureRectifier: &signature.StripAntigravityRectifier{
|
||||
StripStage1: stripThinkingFromClaudeRequest,
|
||||
StripStage2: stripSignatureSensitiveBlocksFromClaudeRequest,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1468,28 +1474,31 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context,
|
||||
Detail: upstreamDetail,
|
||||
})
|
||||
|
||||
// Conservative two-stage fallback:
|
||||
// Conservative two-stage fallback (Strip strategy):
|
||||
// 1) Disable top-level thinking + thinking->text
|
||||
// 2) Only if still signature-related 400: also downgrade tool_use/tool_result to text.
|
||||
// Pool strategy (Phase 3) replaces thinking signatures with valid ones from the pool instead.
|
||||
|
||||
retryStages := []struct {
|
||||
name string
|
||||
strip func(*antigravity.ClaudeRequest) (bool, error)
|
||||
}{
|
||||
{name: "thinking-only", strip: stripThinkingFromClaudeRequest},
|
||||
{name: "thinking+tools", strip: stripSignatureSensitiveBlocksFromClaudeRequest},
|
||||
}
|
||||
|
||||
for _, stage := range retryStages {
|
||||
for _, stage := range s.signatureRectifier.Stages() {
|
||||
retryClaudeReq := claudeReq
|
||||
retryClaudeReq.Messages = append([]antigravity.ClaudeMessage(nil), claudeReq.Messages...)
|
||||
|
||||
stripped, stripErr := stage.strip(&retryClaudeReq)
|
||||
if stripErr != nil || !stripped {
|
||||
sigIn := signature.AntigravityInput{
|
||||
AccountType: account.Type,
|
||||
AccountID: account.ID,
|
||||
Request: &retryClaudeReq,
|
||||
}
|
||||
applied, proceedAfter, stripErr := s.signatureRectifier.Apply(ctx, sigIn, stage)
|
||||
if stripErr != nil || !applied {
|
||||
if !proceedAfter {
|
||||
// Rectifier signaled abort (e.g. Pool is empty under rule A).
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
logger.LegacyPrintf("service.antigravity_gateway", "Antigravity account %d: detected signature-related 400, retrying once (%s)", account.ID, stage.name)
|
||||
stageName := stage.Name()
|
||||
logger.LegacyPrintf("service.antigravity_gateway", "Antigravity account %d: detected signature-related 400, retrying once (%s)", account.ID, stageName)
|
||||
|
||||
retryGeminiBody, txErr := antigravity.TransformClaudeToGeminiWithOptions(&retryClaudeReq, projectID, mappedModel, s.getClaudeTransformOptions(ctx))
|
||||
if txErr != nil {
|
||||
@@ -1522,7 +1531,10 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context,
|
||||
Kind: "signature_retry_request_error",
|
||||
Message: sanitizeUpstreamErrorMessage(retryErr.Error()),
|
||||
})
|
||||
logger.LegacyPrintf("service.antigravity_gateway", "Antigravity account %d: signature retry request failed (%s): %v", account.ID, stage.name, retryErr)
|
||||
logger.LegacyPrintf("service.antigravity_gateway", "Antigravity account %d: signature retry request failed (%s): %v", account.ID, stageName, retryErr)
|
||||
if !proceedAfter {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -1541,11 +1553,11 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context,
|
||||
if retryResp.Request != nil && retryResp.Request.URL != nil {
|
||||
retryBaseURL = retryResp.Request.URL.Scheme + "://" + retryResp.Request.URL.Host
|
||||
}
|
||||
logger.LegacyPrintf("service.antigravity_gateway", "%s status=429 rate_limited base_url=%s retry_stage=%s body=%s", prefix, retryBaseURL, stage.name, truncateForLog(retryBody, 200))
|
||||
logger.LegacyPrintf("service.antigravity_gateway", "%s status=429 rate_limited base_url=%s retry_stage=%s body=%s", prefix, retryBaseURL, stageName, truncateForLog(retryBody, 200))
|
||||
}
|
||||
kind := "signature_retry"
|
||||
if strings.TrimSpace(stage.name) != "" {
|
||||
kind = "signature_retry_" + strings.ReplaceAll(stage.name, "+", "_")
|
||||
if strings.TrimSpace(stageName) != "" {
|
||||
kind = "signature_retry_" + strings.ReplaceAll(stageName, "+", "_")
|
||||
}
|
||||
retryUpstreamMsg := strings.TrimSpace(extractAntigravityErrorMessage(retryBody))
|
||||
retryUpstreamMsg = sanitizeUpstreamErrorMessage(retryUpstreamMsg)
|
||||
@@ -1582,6 +1594,10 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context,
|
||||
Header: retryResp.Header.Clone(),
|
||||
Body: io.NopCloser(bytes.NewReader(retryBody)),
|
||||
}
|
||||
if !proceedAfter {
|
||||
// Rectifier signaled one-shot (e.g. Pool strategy): don't iterate to next stage.
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/usagestats"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service/signature"
|
||||
"github.com/Wei-Shaw/sub2api/internal/util/responseheaders"
|
||||
"github.com/Wei-Shaw/sub2api/internal/util/urlvalidator"
|
||||
"github.com/cespare/xxhash/v2"
|
||||
@@ -570,6 +571,7 @@ type GatewayService struct {
|
||||
debugGatewayBodyFile atomic.Pointer[os.File] // non-nil when SUB2API_DEBUG_GATEWAY_BODY is set
|
||||
tlsFPProfileService *TLSFingerprintProfileService
|
||||
balanceNotifyService *BalanceNotifyService
|
||||
signatureRectifier signature.ClaudeRectifier
|
||||
}
|
||||
|
||||
// NewGatewayService creates a new GatewayService
|
||||
@@ -635,6 +637,10 @@ func NewGatewayService(
|
||||
channelService: channelService,
|
||||
resolver: resolver,
|
||||
balanceNotifyService: balanceNotifyService,
|
||||
signatureRectifier: &signature.StripClaudeRectifier{
|
||||
FilterStage1: FilterThinkingBlocksForRetry,
|
||||
FilterStage2: FilterSignatureSensitiveBlocksForRetry,
|
||||
},
|
||||
}
|
||||
svc.userGroupRateResolver = newUserGroupRateResolver(
|
||||
userGroupRateRepo,
|
||||
@@ -4195,16 +4201,6 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A
|
||||
}(),
|
||||
})
|
||||
|
||||
looksLikeToolSignatureError := func(msg string) bool {
|
||||
m := strings.ToLower(msg)
|
||||
return strings.Contains(m, "tool_use") ||
|
||||
strings.Contains(m, "tool_result") ||
|
||||
strings.Contains(m, "functioncall") ||
|
||||
strings.Contains(m, "function_call") ||
|
||||
strings.Contains(m, "functionresponse") ||
|
||||
strings.Contains(m, "function_response")
|
||||
}
|
||||
|
||||
// 避免在重试预算已耗尽时再发起额外请求
|
||||
if time.Since(retryStart) >= maxRetryElapsed {
|
||||
resp.Body = io.NopCloser(bytes.NewReader(respBody))
|
||||
@@ -4217,7 +4213,17 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A
|
||||
// 2) Only if upstream still errors AND error message points to tool/function signature issues:
|
||||
// also downgrade tool_use/tool_result blocks to text.
|
||||
|
||||
filteredBody := FilterThinkingBlocksForRetry(body)
|
||||
sigIn := signature.ClaudeInput{
|
||||
AccountType: account.Type,
|
||||
AccountID: account.ID,
|
||||
Body: body,
|
||||
}
|
||||
filteredBody, proceedStage1 := s.signatureRectifier.Apply(ctx, sigIn, signature.StageThinkingOnly)
|
||||
if !proceedStage1 {
|
||||
// Rectifier declined (e.g. signature pool is empty under rule A)
|
||||
resp.Body = io.NopCloser(bytes.NewReader(respBody))
|
||||
break
|
||||
}
|
||||
retryCtx, releaseRetryCtx := detachStreamUpstreamContext(ctx, reqStream)
|
||||
retryReq, buildErr := s.buildUpstreamRequest(retryCtx, c, account, filteredBody, token, tokenType, reqModel, reqStream, shouldMimicClaudeCode)
|
||||
releaseRetryCtx()
|
||||
@@ -4250,9 +4256,11 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A
|
||||
}(),
|
||||
})
|
||||
msg2 := extractUpstreamErrorMessage(retryRespBody)
|
||||
if looksLikeToolSignatureError(msg2) && time.Since(retryStart) < maxRetryElapsed {
|
||||
sigIn2 := sigIn
|
||||
sigIn2.LastErrMsg = msg2
|
||||
filteredBody2, proceedStage2 := s.signatureRectifier.Apply(ctx, sigIn2, signature.StageThinkingAndTools)
|
||||
if proceedStage2 && time.Since(retryStart) < maxRetryElapsed {
|
||||
logger.LegacyPrintf("service.gateway", "Account %d: signature retry still failing and looks tool-related, retrying with tool blocks downgraded", account.ID)
|
||||
filteredBody2 := FilterSignatureSensitiveBlocksForRetry(body)
|
||||
retryCtx2, releaseRetryCtx2 := detachStreamUpstreamContext(ctx, reqStream)
|
||||
retryReq2, buildErr2 := s.buildUpstreamRequest(retryCtx2, c, account, filteredBody2, token, tokenType, reqModel, reqStream, shouldMimicClaudeCode)
|
||||
releaseRetryCtx2()
|
||||
@@ -8357,21 +8365,27 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context,
|
||||
|
||||
// 检测 thinking block 签名错误(400)并重试一次(过滤 thinking blocks)
|
||||
if resp.StatusCode == 400 && s.shouldRectifySignatureError(ctx, account, respBody) {
|
||||
logger.LegacyPrintf("service.gateway", "Account %d: detected thinking block signature error on count_tokens, retrying with filtered thinking blocks", account.ID)
|
||||
|
||||
filteredBody := FilterThinkingBlocksForRetry(body)
|
||||
retryReq, buildErr := s.buildCountTokensRequest(ctx, c, account, filteredBody, token, tokenType, reqModel, shouldMimicClaudeCode)
|
||||
if buildErr == nil {
|
||||
retryResp, retryErr := s.httpUpstream.DoWithTLS(retryReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account))
|
||||
if retryErr == nil {
|
||||
resp = retryResp
|
||||
respBody, err = ReadUpstreamResponseBody(resp.Body, s.cfg, c, countTokensTooLarge)
|
||||
_ = resp.Body.Close()
|
||||
if err != nil {
|
||||
if !errors.Is(err, ErrUpstreamResponseBodyTooLarge) {
|
||||
s.countTokensError(c, http.StatusBadGateway, "upstream_error", "Failed to read response")
|
||||
sigIn := signature.ClaudeInput{
|
||||
AccountType: account.Type,
|
||||
AccountID: account.ID,
|
||||
Body: body,
|
||||
}
|
||||
filteredBody, proceedStage1 := s.signatureRectifier.Apply(ctx, sigIn, signature.StageThinkingOnly)
|
||||
if proceedStage1 {
|
||||
logger.LegacyPrintf("service.gateway", "Account %d: detected thinking block signature error on count_tokens, retrying with filtered thinking blocks", account.ID)
|
||||
retryReq, buildErr := s.buildCountTokensRequest(ctx, c, account, filteredBody, token, tokenType, reqModel, shouldMimicClaudeCode)
|
||||
if buildErr == nil {
|
||||
retryResp, retryErr := s.httpUpstream.DoWithTLS(retryReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account))
|
||||
if retryErr == nil {
|
||||
resp = retryResp
|
||||
respBody, err = ReadUpstreamResponseBody(resp.Body, s.cfg, c, countTokensTooLarge)
|
||||
_ = resp.Body.Close()
|
||||
if err != nil {
|
||||
if !errors.Is(err, ErrUpstreamResponseBodyTooLarge) {
|
||||
s.countTokensError(c, http.StatusBadGateway, "upstream_error", "Failed to read response")
|
||||
}
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// Package signature defines the thinking-signature rectifier strategies used
|
||||
// by the gateway retry loops when upstream rejects a request with a
|
||||
// signature-related 400 error.
|
||||
//
|
||||
// Strategies:
|
||||
// - StripClaudeRectifier / StripAntigravityRectifier: the classic two-stage
|
||||
// behavior (drop thinking blocks, optionally drop tool blocks).
|
||||
// - (Phase 3) PoolClaudeRectifier / PoolAntigravityRectifier: replace the
|
||||
// invalid signatures with valid ones fetched from a Redis-backed pool.
|
||||
//
|
||||
// The interfaces are deliberately narrow so that a future factory can swap
|
||||
// strategies at runtime based on RectifierSettings without touching the
|
||||
// retry-loop scaffolding.
|
||||
package signature
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
|
||||
)
|
||||
|
||||
// Stage enumerates the retry stages the gateway loops iterate over.
|
||||
// Strip strategy uses StageThinkingOnly → StageThinkingAndTools.
|
||||
// Pool strategy uses StageThinkingOnly only (one-shot).
|
||||
type Stage int
|
||||
|
||||
const (
|
||||
StageThinkingOnly Stage = 0 // drop thinking blocks / replace their signatures
|
||||
StageThinkingAndTools Stage = 1 // additionally drop tool blocks
|
||||
)
|
||||
|
||||
// Name returns the stage label used in ops-event Kind and logs.
|
||||
func (s Stage) Name() string {
|
||||
switch s {
|
||||
case StageThinkingOnly:
|
||||
return "thinking-only"
|
||||
case StageThinkingAndTools:
|
||||
return "thinking+tools"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// ClaudeInput is the input to the Claude-native body rectifier.
|
||||
// AccountType / AccountID are passed as primitives so the signature package
|
||||
// does not import the service package (avoids an import cycle).
|
||||
type ClaudeInput struct {
|
||||
AccountType string
|
||||
AccountID int64
|
||||
Body []byte
|
||||
LastErrMsg string // error message from the previous stage's 400 response; empty on first stage
|
||||
}
|
||||
|
||||
// ClaudeRectifier transforms a Claude-format request body before a retry.
|
||||
type ClaudeRectifier interface {
|
||||
// Apply returns the body to use for this retry stage.
|
||||
// proceed=false signals "skip this stage and abort the retry loop"
|
||||
// - for Strip stage-2 this means the error did not look tool-related
|
||||
// - for Pool this means the pool is empty or replacement produced no changes
|
||||
Apply(ctx context.Context, in ClaudeInput, stage Stage) (body []byte, proceed bool)
|
||||
}
|
||||
|
||||
// AntigravityInput is the input to the Antigravity rectifier (mutates the
|
||||
// intermediate Claude-format struct before it is re-transformed to Gemini).
|
||||
type AntigravityInput struct {
|
||||
AccountType string
|
||||
AccountID int64
|
||||
Request *antigravity.ClaudeRequest
|
||||
LastErrMsg string
|
||||
}
|
||||
|
||||
// AntigravityRectifier mutates a Claude request in-place for the next
|
||||
// Antigravity retry.
|
||||
type AntigravityRectifier interface {
|
||||
// Apply mutates the request for the given stage.
|
||||
// applied=false means the strip/replace found nothing to do — outer loop
|
||||
// should skip this stage and try the next one (matches legacy behavior).
|
||||
// proceed=false means abort further stages entirely (e.g. Pool exhausted).
|
||||
Apply(ctx context.Context, in AntigravityInput, stage Stage) (applied bool, proceed bool, err error)
|
||||
|
||||
// Stages returns the ordered list of stages this strategy wants the loop
|
||||
// to iterate. Strip returns [ThinkingOnly, ThinkingAndTools]; Pool
|
||||
// returns [ThinkingOnly] only.
|
||||
Stages() []Stage
|
||||
}
|
||||
|
||||
// LooksLikeToolSignatureError is the predicate that gates Strip stage-2.
|
||||
// Extracted from the anonymous closure previously inlined in gateway_service.go.
|
||||
func LooksLikeToolSignatureError(msg string) bool {
|
||||
m := strings.ToLower(msg)
|
||||
return strings.Contains(m, "tool_use") ||
|
||||
strings.Contains(m, "tool_result") ||
|
||||
strings.Contains(m, "functioncall") ||
|
||||
strings.Contains(m, "function_call") ||
|
||||
strings.Contains(m, "functionresponse") ||
|
||||
strings.Contains(m, "function_response")
|
||||
}
|
||||
|
||||
// StripClaudeRectifier wraps the legacy FilterThinkingBlocksForRetry /
|
||||
// FilterSignatureSensitiveBlocksForRetry functions as a ClaudeRectifier.
|
||||
// The filter functions are injected to avoid an import cycle with the
|
||||
// service package where they live.
|
||||
type StripClaudeRectifier struct {
|
||||
FilterStage1 func([]byte) []byte // FilterThinkingBlocksForRetry
|
||||
FilterStage2 func([]byte) []byte // FilterSignatureSensitiveBlocksForRetry
|
||||
}
|
||||
|
||||
// Apply implements ClaudeRectifier.
|
||||
func (r *StripClaudeRectifier) Apply(_ context.Context, in ClaudeInput, stage Stage) ([]byte, bool) {
|
||||
switch stage {
|
||||
case StageThinkingOnly:
|
||||
return r.FilterStage1(in.Body), true
|
||||
case StageThinkingAndTools:
|
||||
if !LooksLikeToolSignatureError(in.LastErrMsg) {
|
||||
return nil, false
|
||||
}
|
||||
return r.FilterStage2(in.Body), true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// StripAntigravityRectifier wraps the legacy stripThinkingFromClaudeRequest /
|
||||
// stripSignatureSensitiveBlocksFromClaudeRequest functions as an
|
||||
// AntigravityRectifier.
|
||||
type StripAntigravityRectifier struct {
|
||||
StripStage1 func(*antigravity.ClaudeRequest) (bool, error) // stripThinkingFromClaudeRequest
|
||||
StripStage2 func(*antigravity.ClaudeRequest) (bool, error) // stripSignatureSensitiveBlocksFromClaudeRequest
|
||||
}
|
||||
|
||||
// Apply implements AntigravityRectifier.
|
||||
func (r *StripAntigravityRectifier) Apply(_ context.Context, in AntigravityInput, stage Stage) (bool, bool, error) {
|
||||
switch stage {
|
||||
case StageThinkingOnly:
|
||||
applied, err := r.StripStage1(in.Request)
|
||||
return applied, true, err
|
||||
case StageThinkingAndTools:
|
||||
applied, err := r.StripStage2(in.Request)
|
||||
return applied, true, err
|
||||
}
|
||||
return false, false, nil
|
||||
}
|
||||
|
||||
// Stages returns the two-stage order used by the legacy retry loop.
|
||||
func (r *StripAntigravityRectifier) Stages() []Stage {
|
||||
return []Stage{StageThinkingOnly, StageThinkingAndTools}
|
||||
}
|
||||
Reference in new issue
Block a user