mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 08:05:12 +00:00
feat(gemini): 同账号重试次数改为可配置 gateway.max_same_account_retries_gemini
Gemini 三条转发路径(原生 v1beta、Claude 兼容、Chat 兼容)对 429/5xx 等可重试 上游错误的同号重试次数读取 gateway.max_same_account_retries_gemini(不含首次请求, 默认 4,范围 0–10),取代写死的每号 5 次请求。默认值下不涉及签名降级的请求仍是 每号最多 5 次。 Claude 兼容路径的签名错误两阶段降级重发不占用同号重试次数:每进入一个降级阶段 循环上限顺延一次,重试次数调小时第二阶段降级照常执行,循环不会带着已关闭的响应体 退出。默认配置下先降级再遇瞬时错误的请求单号最多 7 次请求。
This commit is contained in:
1 parent
dba770d56a
commit
4197fa6202
7 files changed
+150
-15
No files matched your search
@@ -1109,6 +1109,8 @@ type GatewayConfig struct {
|
||||
MaxAccountSwitches int `mapstructure:"max_account_switches"`
|
||||
// Gemini 账户切换最大次数(Gemini 平台单独配置,因 API 限制更严格)
|
||||
MaxAccountSwitchesGemini int `mapstructure:"max_account_switches_gemini"`
|
||||
// Gemini 同账号重试次数(429/5xx 等可重试错误在换号前对同一账号的重发次数,不含首次请求)
|
||||
MaxSameAccountRetriesGemini int `mapstructure:"max_same_account_retries_gemini"`
|
||||
|
||||
// Antigravity 429 fallback 限流时间(分钟),解析重置时间失败时使用
|
||||
AntigravityFallbackCooldownMinutes int `mapstructure:"antigravity_fallback_cooldown_minutes"`
|
||||
@@ -2434,6 +2436,7 @@ func setDefaults() {
|
||||
viper.SetDefault("gateway.failover_on_400", false)
|
||||
viper.SetDefault("gateway.max_account_switches", 10)
|
||||
viper.SetDefault("gateway.max_account_switches_gemini", 3)
|
||||
viper.SetDefault("gateway.max_same_account_retries_gemini", 4)
|
||||
viper.SetDefault("gateway.force_codex_cli", false)
|
||||
viper.SetDefault("gateway.disable_codex_identity_enforcement", false)
|
||||
viper.SetDefault("gateway.disable_codex_originator_normalization", false)
|
||||
@@ -3371,6 +3374,9 @@ func (c *Config) Validate() error {
|
||||
if c.Gateway.GrokResponseHeaderTimeout < 0 || c.Gateway.GrokResponseHeaderTimeout > 1800 {
|
||||
return fmt.Errorf("gateway.grok_response_header_timeout must be between 0-1800 seconds")
|
||||
}
|
||||
if c.Gateway.MaxSameAccountRetriesGemini < 0 || c.Gateway.MaxSameAccountRetriesGemini > 10 {
|
||||
return fmt.Errorf("gateway.max_same_account_retries_gemini must be between 0-10")
|
||||
}
|
||||
if c.Gateway.OpenAIFirstOutputTimeoutSeconds < 0 || c.Gateway.OpenAIFirstOutputTimeoutSeconds > 600 ||
|
||||
(c.Gateway.OpenAIFirstOutputTimeoutSeconds > 0 && c.Gateway.OpenAIFirstOutputTimeoutSeconds < 30) {
|
||||
return fmt.Errorf("gateway.openai_first_output_timeout_seconds must be 0 or between 30-600 seconds")
|
||||
|
||||
@@ -46,6 +46,19 @@ func TestLoadMinOutputTokensFromEnv(t *testing.T) {
|
||||
require.Equal(t, 16, cfg.Gateway.MinOutputTokens)
|
||||
}
|
||||
|
||||
func TestLoadGeminiSameAccountRetries(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
cfg, err := Load()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 4, cfg.Gateway.MaxSameAccountRetriesGemini)
|
||||
|
||||
resetViperWithJWTSecret(t)
|
||||
t.Setenv("GATEWAY_MAX_SAME_ACCOUNT_RETRIES_GEMINI", "0")
|
||||
cfg, err = Load()
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, cfg.Gateway.MaxSameAccountRetriesGemini)
|
||||
}
|
||||
|
||||
func TestValidateMinOutputTokensMinimum(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
cfg, err := Load()
|
||||
@@ -1887,6 +1900,16 @@ func TestValidateConfigErrors(t *testing.T) {
|
||||
mutate: func(c *Config) { c.Gateway.OpenAIResponseHeaderTimeout = -1 },
|
||||
wantErr: "gateway.openai_response_header_timeout",
|
||||
},
|
||||
{
|
||||
name: "gateway gemini same account retries negative",
|
||||
mutate: func(c *Config) { c.Gateway.MaxSameAccountRetriesGemini = -1 },
|
||||
wantErr: "gateway.max_same_account_retries_gemini",
|
||||
},
|
||||
{
|
||||
name: "gateway gemini same account retries too large",
|
||||
mutate: func(c *Config) { c.Gateway.MaxSameAccountRetriesGemini = 11 },
|
||||
wantErr: "gateway.max_same_account_retries_gemini",
|
||||
},
|
||||
{
|
||||
name: "gateway openai first output timeout below minimum",
|
||||
mutate: func(c *Config) { c.Gateway.OpenAIFirstOutputTimeoutSeconds = 29 },
|
||||
|
||||
@@ -127,7 +127,8 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions(
|
||||
var resp *http.Response
|
||||
// checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。
|
||||
var checkedPolicy *ErrorPolicyResult
|
||||
for attempt := 1; attempt <= geminiMaxRetries; attempt++ {
|
||||
maxAttempts := s.geminiMaxAttemptsPerAccount()
|
||||
for attempt := 1; attempt <= maxAttempts; attempt++ {
|
||||
upstreamReq, idHeader, err := buildReq(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
@@ -166,7 +167,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions(
|
||||
if resp.StatusCode == http.StatusTooManyRequests {
|
||||
s.handleGeminiUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody)
|
||||
}
|
||||
if attempt < geminiMaxRetries {
|
||||
if attempt < maxAttempts {
|
||||
upstreamReqID := resp.Header.Get(requestIDHeader)
|
||||
if upstreamReqID == "" {
|
||||
upstreamReqID = resp.Header.Get("x-goog-request-id")
|
||||
@@ -184,7 +185,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions(
|
||||
Kind: "retry",
|
||||
Message: upstreamMsg,
|
||||
})
|
||||
logger.LegacyPrintf("service.gemini_chat_completions", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, geminiMaxRetries)
|
||||
logger.LegacyPrintf("service.gemini_chat_completions", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, maxAttempts)
|
||||
sleepGeminiBackoff(attempt)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -182,6 +182,7 @@ func TestGeminiForward_UncheckedFinalResponseIsCheckedAfterLoop(t *testing.T) {
|
||||
geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: `{"error":{"code":503,"message":"backend busy","status":"UNAVAILABLE"}}`},
|
||||
geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: `{"error":{"code":400,"message":"quota project misconfigured","status":"FAILED_PRECONDITION"}}`},
|
||||
)
|
||||
svc.cfg.Gateway.MaxSameAccountRetriesGemini = 1
|
||||
account := geminiAPIKeyAccountWithTempRule(map[string]any{
|
||||
"error_code": float64(400),
|
||||
"keywords": []any{"misconfigured"},
|
||||
|
||||
@@ -35,9 +35,10 @@ import (
|
||||
const geminiStickySessionTTL = time.Hour
|
||||
|
||||
const (
|
||||
geminiMaxRetries = 5
|
||||
geminiRetryBaseDelay = 1 * time.Second
|
||||
geminiRetryMaxDelay = 16 * time.Second
|
||||
// 未注入配置时的同账号重试次数,与 gateway.max_same_account_retries_gemini 默认值一致
|
||||
geminiDefaultSameAccountRetries = 4
|
||||
geminiRetryBaseDelay = 1 * time.Second
|
||||
geminiRetryMaxDelay = 16 * time.Second
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -717,7 +718,9 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
|
||||
// checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。
|
||||
var checkedPolicy *ErrorPolicyResult
|
||||
signatureRetryStage := 0
|
||||
for attempt := 1; attempt <= geminiMaxRetries; attempt++ {
|
||||
maxAttempts := s.geminiMaxAttemptsPerAccount()
|
||||
// 签名降级重发不占用同号重试次数:每进入一个降级阶段,循环上限随之顺延一次。
|
||||
for attempt := 1; attempt <= maxAttempts+signatureRetryStage; attempt++ {
|
||||
checkedPolicy = nil
|
||||
upstreamReq, idHeader, err := buildReq(ctx)
|
||||
if err != nil {
|
||||
@@ -798,7 +801,6 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
|
||||
logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: detected signature-related 400, retrying with downgraded Claude blocks (%s)", account.ID, stageName)
|
||||
// 降级只改写历史块,思考参数沿用客户端原始请求。
|
||||
geminiReq = applyGeminiCompatThinkingConfig(retryGeminiReq, originalClaudeBody, mappedModel, includeThoughts)
|
||||
// Consume one retry budget attempt and continue with the updated request payload.
|
||||
sleepGeminiBackoff(1)
|
||||
continue
|
||||
}
|
||||
@@ -837,7 +839,8 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
|
||||
// Apply account-scoped 429 handling early so concurrent requests avoid a rate-limited account.
|
||||
s.handleGeminiUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody)
|
||||
}
|
||||
if attempt < geminiMaxRetries {
|
||||
retryAttempt := attempt - signatureRetryStage
|
||||
if retryAttempt < maxAttempts {
|
||||
upstreamReqID := resp.Header.Get(requestIDHeader)
|
||||
if upstreamReqID == "" {
|
||||
upstreamReqID = resp.Header.Get("x-goog-request-id")
|
||||
@@ -865,8 +868,8 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
|
||||
Detail: upstreamDetail,
|
||||
})
|
||||
|
||||
logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, geminiMaxRetries)
|
||||
sleepGeminiBackoff(attempt)
|
||||
logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, retryAttempt, maxAttempts)
|
||||
sleepGeminiBackoff(retryAttempt)
|
||||
continue
|
||||
}
|
||||
// Final attempt: surface the upstream error body (mapped below) instead of a generic retry error.
|
||||
@@ -1268,7 +1271,8 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
|
||||
var resp *http.Response
|
||||
// checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。
|
||||
var checkedPolicy *ErrorPolicyResult
|
||||
for attempt := 1; attempt <= geminiMaxRetries; attempt++ {
|
||||
maxAttempts := s.geminiMaxAttemptsPerAccount()
|
||||
for attempt := 1; attempt <= maxAttempts; attempt++ {
|
||||
checkedPolicy = nil
|
||||
upstreamReq, idHeader, err := buildReq(ctx)
|
||||
if err != nil {
|
||||
@@ -1339,7 +1343,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
|
||||
if resp.StatusCode == 429 {
|
||||
s.handleGeminiUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody)
|
||||
}
|
||||
if attempt < geminiMaxRetries {
|
||||
if attempt < maxAttempts {
|
||||
upstreamReqID := resp.Header.Get(requestIDHeader)
|
||||
if upstreamReqID == "" {
|
||||
upstreamReqID = resp.Header.Get("x-goog-request-id")
|
||||
@@ -1367,7 +1371,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
|
||||
Detail: upstreamDetail,
|
||||
})
|
||||
|
||||
logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, geminiMaxRetries)
|
||||
logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, maxAttempts)
|
||||
sleepGeminiBackoff(attempt)
|
||||
continue
|
||||
}
|
||||
@@ -1669,6 +1673,14 @@ func (s *GeminiMessagesCompatService) cachedContentPassthroughInLoop(ctx context
|
||||
return isGeminiCachedContentNotFound(resp.StatusCode, body), rebuilt
|
||||
}
|
||||
|
||||
// geminiMaxAttemptsPerAccount 返回可重试上游错误在单个账号上的最大请求次数(首次请求 + 同账号重试)。
|
||||
func (s *GeminiMessagesCompatService) geminiMaxAttemptsPerAccount() int {
|
||||
if s == nil || s.cfg == nil {
|
||||
return geminiDefaultSameAccountRetries + 1
|
||||
}
|
||||
return s.cfg.Gateway.MaxSameAccountRetriesGemini + 1
|
||||
}
|
||||
|
||||
func (s *GeminiMessagesCompatService) shouldRetryGeminiUpstreamError(account *Account, statusCode int) bool {
|
||||
switch statusCode {
|
||||
case 429, 500, 502, 503, 504, 529:
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
geminiRetryTest503Body = `{"error":{"code":503,"message":"The model is overloaded.","status":"UNAVAILABLE"}}`
|
||||
geminiRetryTestSignatureBody = `{"error":{"code":400,"message":"Function call is missing a thought_signature in functionCall parts.","status":"INVALID_ARGUMENT"}}`
|
||||
geminiRetryTestOKBody = `{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1,"totalTokenCount":4}}`
|
||||
)
|
||||
|
||||
func geminiSameAccountRetryTestAccount() *Account {
|
||||
return &Account{
|
||||
ID: 840,
|
||||
Platform: PlatformGemini,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "test-key"},
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiForward_SameAccountRetriesFollowConfig(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, retries := range []int{0, 1} {
|
||||
for _, fw := range geminiSingleCheckForwarders {
|
||||
t.Run(fmt.Sprintf("%s/retries=%d", fw.name, retries), func(t *testing.T) {
|
||||
svc, upstream, _ := newGeminiSingleCheckService(geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: geminiRetryTest503Body})
|
||||
svc.cfg.Gateway.MaxSameAccountRetriesGemini = retries
|
||||
|
||||
err, _ := fw.forward(t, svc, geminiSameAccountRetryTestAccount())
|
||||
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.True(t, errors.As(err, &failoverErr), "同号重试耗尽应换号,got %T: %v", err, err)
|
||||
require.Equal(t, http.StatusServiceUnavailable, failoverErr.StatusCode)
|
||||
require.Equal(t, retries+1, upstream.calls)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiClaudeCompat_SignatureDowngradeDoesNotConsumeSameAccountRetries(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
forward := func(svc *GeminiMessagesCompatService) (*ForwardResult, error) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
body := []byte(`{"model":"gemini-2.5-flash","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body))
|
||||
return svc.Forward(context.Background(), c, geminiSameAccountRetryTestAccount(), body)
|
||||
}
|
||||
|
||||
t.Run("both downgrade stages run without same-account retries", func(t *testing.T) {
|
||||
svc, upstream, _ := newGeminiSingleCheckService(
|
||||
geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody},
|
||||
geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody},
|
||||
geminiSequenceUpstreamResponse{status: http.StatusOK, body: geminiRetryTestOKBody},
|
||||
)
|
||||
svc.cfg.Gateway.MaxSameAccountRetriesGemini = 0
|
||||
|
||||
result, err := forward(svc)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, 3, upstream.calls)
|
||||
})
|
||||
|
||||
t.Run("same-account retries are counted apart from downgrades", func(t *testing.T) {
|
||||
svc, upstream, _ := newGeminiSingleCheckService(
|
||||
geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: geminiRetryTest503Body},
|
||||
geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody},
|
||||
geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody},
|
||||
geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: geminiRetryTest503Body},
|
||||
)
|
||||
svc.cfg.Gateway.MaxSameAccountRetriesGemini = 1
|
||||
|
||||
_, err := forward(svc)
|
||||
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.True(t, errors.As(err, &failoverErr), "同号重试耗尽应换号,got %T: %v", err, err)
|
||||
require.Equal(t, http.StatusServiceUnavailable, failoverErr.StatusCode)
|
||||
require.Equal(t, 4, upstream.calls)
|
||||
})
|
||||
}
|
||||
@@ -144,7 +144,7 @@ func TestGeminiForwardNative_VertexSharedCapacity429RetriesSameAccountWithoutCoo
|
||||
repo := &geminiBoundCacheRateLimitRepo{}
|
||||
svc := &GeminiMessagesCompatService{
|
||||
httpUpstream: upstream,
|
||||
cfg: &config.Config{},
|
||||
cfg: &config.Config{Gateway: config.GatewayConfig{MaxSameAccountRetriesGemini: 1}},
|
||||
accountRepo: repo,
|
||||
rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil),
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user