fix(gemini): 引用缓存不存在的 403 不再停用账号并换号

上游对不存在、已过期、已删除或不属于当前项目的 cachedContent 一律返回
403 "CachedContent not found (or permission denied)"。原生转发路径在错误
策略之前识别该响应,原样返回客户端,不标记账号错误、不临时停调度、
不重试、不换号;其余 403 处理不变。
This commit is contained in:
feeeei committed 2026-10-10 23:36:17 +08:00
1 parent 3a6fd1c9db
commit 3bfd40f5af
2 files changed
+165

No files matched your search

@@ -0,0 +1,129 @@
//go:build unit
package service
import (
"context"
"errors"
"io"
"net/http"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
// 上游对不存在、已过期、已删除或不属于当前项目的显式缓存一律返回这个 403。
const geminiCachedContentNotFoundBody = `{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}`
func newGeminiCachedContentTestService(status int, body string) (*GeminiMessagesCompatService, *geminiCompatHTTPUpstreamStub, *errorPolicyRepoStub) {
repo := &errorPolicyRepoStub{}
httpStub := &geminiCompatHTTPUpstreamStub{
response: &http.Response{
StatusCode: status,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(body)),
},
}
svc := &GeminiMessagesCompatService{
httpUpstream: httpStub,
cfg: &config.Config{},
rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil),
}
return svc, httpStub, repo
}
func geminiDefaultPolicyAPIKeyAccount() *Account {
return &Account{
ID: 710,
Platform: PlatformGemini,
Type: AccountTypeAPIKey,
Credentials: map[string]any{
"api_key": "test-key",
},
}
}
const geminiCachedContentRequestBody = `{"cachedContent":"cachedContents/doesnotexist","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`
func TestGeminiForwardNative_CachedContentNotFoundPassthroughWithoutAccountPenalty(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
name string
action string
stream bool
}{
{name: "generateContent", action: "generateContent"},
{name: "streamGenerateContent", action: "streamGenerateContent", stream: true},
{name: "countTokens", action: "countTokens"},
} {
t.Run(tc.name, func(t *testing.T) {
svc, httpStub, repo := newGeminiCachedContentTestService(http.StatusForbidden, geminiCachedContentNotFoundBody)
c, rec := newGeminiNativeTestContext(t)
result, err := svc.ForwardNative(context.Background(), c, geminiDefaultPolicyAPIKeyAccount(),
"gemini-3.8-flash", tc.action, tc.stream, []byte(geminiCachedContentRequestBody))
require.Nil(t, result)
require.Error(t, err)
var failoverErr *UpstreamFailoverError
require.False(t, errors.As(err, &failoverErr), "缓存不存在是请求问题,不应换号")
require.Equal(t, 0, repo.setErrCalls, "不应把账号标记为错误")
require.Equal(t, 0, repo.tempCalls, "不应临时停调度")
require.Equal(t, 1, httpStub.calls, "不应重试")
require.Equal(t, http.StatusForbidden, rec.Code)
require.Equal(t, geminiCachedContentNotFoundBody, rec.Body.String(), "响应体应原样透传")
})
}
}
func TestGeminiForwardNative_CachedContentNotFoundBypassesTempUnschedulableRules(t *testing.T) {
gin.SetMode(gin.TestMode)
svc, _, repo := newGeminiCachedContentTestService(http.StatusForbidden, geminiCachedContentNotFoundBody)
c, rec := newGeminiNativeTestContext(t)
account := geminiDefaultPolicyAPIKeyAccount()
account.Credentials["temp_unschedulable_enabled"] = true
account.Credentials["temp_unschedulable_rules"] = []any{
map[string]any{
"error_code": float64(403),
"keywords": []any{"permission denied"},
"duration_minutes": float64(10),
"description": "403 permission denied",
},
}
_, err := svc.ForwardNative(context.Background(), c, account,
"gemini-3.8-flash", "generateContent", false, []byte(geminiCachedContentRequestBody))
require.Error(t, err)
var failoverErr *UpstreamFailoverError
require.False(t, errors.As(err, &failoverErr))
require.Equal(t, 0, repo.tempCalls, "临时不可调度规则不应命中")
require.Equal(t, 0, repo.setErrCalls)
require.Equal(t, http.StatusForbidden, rec.Code)
}
func TestGeminiForwardNative_OtherForbiddenStillPenalizesAccount(t *testing.T) {
gin.SetMode(gin.TestMode)
body := `{"error":{"code":403,"message":"Your project has been denied access. Please contact support.","status":"PERMISSION_DENIED"}}`
svc, _, repo := newGeminiCachedContentTestService(http.StatusForbidden, body)
c, _ := newGeminiNativeTestContext(t)
_, err := svc.ForwardNative(context.Background(), c, geminiDefaultPolicyAPIKeyAccount(),
"gemini-3.8-flash", "generateContent", false, []byte(geminiCachedContentRequestBody))
var failoverErr *UpstreamFailoverError
require.True(t, errors.As(err, &failoverErr), "其他 403 仍按账号问题换号")
require.Equal(t, 1, repo.setErrCalls, "其他 403 仍标记账号错误")
}
func TestIsGeminiCachedContentNotFound(t *testing.T) {
require.True(t, isGeminiCachedContentNotFound(http.StatusForbidden, []byte(geminiCachedContentNotFoundBody)))
require.True(t, isGeminiCachedContentNotFound(http.StatusForbidden,
[]byte(`[{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}]`)))
require.False(t, isGeminiCachedContentNotFound(http.StatusBadRequest, []byte(geminiCachedContentNotFoundBody)))
require.False(t, isGeminiCachedContentNotFound(http.StatusForbidden,
[]byte(`{"error":{"code":403,"message":"Permission denied: Consumer has been suspended.","status":"PERMISSION_DENIED"}}`)))
}
@@ -1374,6 +1374,14 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
return nil, transportErr
}
// 引用缓存不存在先于错误策略识别:错误策略会写临时不可调度,重试与换号也无法恢复。
if notFound, rebuilt := s.cachedContentNotFoundInLoop(resp); notFound {
resp = rebuilt
break
} else {
resp = rebuilt
}
// 错误策略优先:匹配则跳过重试直接处理。
if matched, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel); matched {
resp = rebuilt
@@ -1467,6 +1475,10 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
if resp.StatusCode >= 400 {
respBody := s.readUpstreamErrorBody(resp)
// 引用缓存不存在是请求问题:原样返回客户端,不改账号状态、不换号。
if isGeminiCachedContentNotFound(resp.StatusCode, respBody) {
return nil, s.writeGeminiNativeUpstreamError(c, account, resp, respBody, requestID, isOAuth)
}
// Best-effort fallback for OAuth tokens missing AI Studio scopes when calling countTokens.
// This avoids Gemini SDKs failing hard during preflight token counting.
// Checked before error policy so it always works regardless of custom error codes.
@@ -1676,6 +1688,21 @@ func (s *GeminiMessagesCompatService) checkErrorPolicyInLoop(
return policy != ErrorPolicyNone, rebuilt
}
// cachedContentNotFoundInLoop 判断上游响应是否为引用缓存不存在的 403;读取过的响应体以内存副本重建。
func (s *GeminiMessagesCompatService) cachedContentNotFoundInLoop(resp *http.Response) (notFound bool, rebuilt *http.Response) {
if resp.StatusCode != http.StatusForbidden {
return false, resp
}
body := s.readUpstreamErrorBody(resp)
_ = resp.Body.Close()
rebuilt = &http.Response{
StatusCode: resp.StatusCode,
Header: resp.Header.Clone(),
Body: io.NopCloser(bytes.NewReader(body)),
}
return isGeminiCachedContentNotFound(resp.StatusCode, body), rebuilt
}
func (s *GeminiMessagesCompatService) shouldRetryGeminiUpstreamError(account *Account, statusCode int) bool {
switch statusCode {
case 429, 500, 502, 503, 504, 529:
@@ -2635,6 +2662,15 @@ func isGeminiInsufficientScope(headers http.Header, body []byte) bool {
return strings.Contains(lower, "insufficient authentication scopes") || strings.Contains(lower, "access_token_scope_insufficient")
}
// isGeminiCachedContentNotFound 识别请求引用的显式缓存不存在、已过期、已删除或不属于当前项目时
// 上游返回的 403。四种情况上游响应完全相同,均由请求的 cachedContent 决定,与账号凭据状态无关。
func isGeminiCachedContentNotFound(statusCode int, body []byte) bool {
if statusCode != http.StatusForbidden {
return false
}
return strings.Contains(strings.ToLower(string(body)), "cachedcontent not found")
}
func estimateGeminiCountTokens(reqBody []byte) int {
total := 0