mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
fix(grok): preserve upstream media error messages and codes
This commit is contained in:
1 parent
530c5e3a4f
commit
c8f4264f8f
5 files changed
+304
-22
No files matched your search
@@ -0,0 +1,87 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestGrokImagesPreservesUpstreamErrorOnSyncAndAsyncRoutes(t *testing.T) {
|
||||
for _, oauth := range []bool{false, true} {
|
||||
accountType := "api-key"
|
||||
if oauth {
|
||||
accountType = "oauth"
|
||||
}
|
||||
for _, async := range []bool{false, true} {
|
||||
route := "sync"
|
||||
if async {
|
||||
route = "async"
|
||||
}
|
||||
t.Run(accountType+"/"+route, func(t *testing.T) {
|
||||
h, slots, _, upstream := newGrokMediaSlotHandler(t, oauth, false)
|
||||
h.grokMediaEligibilityProber = grokMediaSlotProber(func(context.Context, int64) (bool, string, error) {
|
||||
return true, "test account is eligible", nil
|
||||
})
|
||||
upstream.call = func(req *http.Request, _ int64) (*http.Response, error) {
|
||||
assert.Equal(t, "/v1/images/edits", req.URL.Path)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusBadRequest,
|
||||
Header: http.Header{"Content-Type": {"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"code":"invalid_image","error":"Image could not be decoded: https://example.test/image?access_token=secret&size=1","debug":"private upstream diagnostic"}`)),
|
||||
}, nil
|
||||
}
|
||||
c, recorder := grokMediaSlotContext(context.Background(), true)
|
||||
path := "/v1/images/edits"
|
||||
if async {
|
||||
path += "/async"
|
||||
}
|
||||
c.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"grok-imagine-image","prompt":"test","image":{"url":"https://example.test/input.png"}}`))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
var responseBody []byte
|
||||
if async {
|
||||
store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)}
|
||||
tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute)
|
||||
asyncHandler := NewAsyncImageHandler(tasks, h)
|
||||
asyncHandler.Submit(c)
|
||||
require.Equal(t, http.StatusAccepted, recorder.Code, recorder.Body.String())
|
||||
taskID := gjson.GetBytes(recorder.Body.Bytes(), "task_id").String()
|
||||
owner := service.ImageTaskOwner{UserID: 10, APIKeyID: 20}
|
||||
require.Eventually(t, func() bool {
|
||||
task, err := tasks.Get(context.Background(), owner, taskID)
|
||||
return err == nil && task.Status != service.ImageTaskStatusProcessing
|
||||
}, time.Second, 10*time.Millisecond)
|
||||
poll, pollRecorder := grokMediaSlotContext(context.Background(), false)
|
||||
poll.Params[0].Key, poll.Params[0].Value = "task_id", taskID
|
||||
asyncHandler.Get(poll)
|
||||
require.Equal(t, http.StatusOK, pollRecorder.Code)
|
||||
responseBody = pollRecorder.Body.Bytes()
|
||||
require.Equal(t, service.ImageTaskStatusFailed, gjson.GetBytes(responseBody, "status").String())
|
||||
require.Equal(t, int64(http.StatusBadRequest), gjson.GetBytes(responseBody, "http_status").Int())
|
||||
} else {
|
||||
h.GrokImages(c)
|
||||
require.Equal(t, http.StatusBadRequest, recorder.Code, recorder.Body.String())
|
||||
responseBody = recorder.Body.Bytes()
|
||||
}
|
||||
require.Equal(t, "Image could not be decoded: https://example.test/image?access_token=***&size=1", gjson.GetBytes(responseBody, "error.message").String())
|
||||
require.Equal(t, "invalid_image", gjson.GetBytes(responseBody, "error.code").String())
|
||||
require.Equal(t, "invalid_request_error", gjson.GetBytes(responseBody, "error.type").String())
|
||||
require.NotContains(t, string(responseBody), "secret")
|
||||
require.NotContains(t, string(responseBody), "private upstream diagnostic")
|
||||
require.Equal(t, 1, upstream.calls, "deterministic image errors must not retry another account")
|
||||
slots.assertReleased(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -310,7 +310,15 @@ func extractUpstreamErrorMessage(body []byte) string {
|
||||
}
|
||||
|
||||
// 兜底:尝试顶层 message
|
||||
return gjson.GetBytes(body, "message").String()
|
||||
if m := gjson.GetBytes(body, "message").String(); strings.TrimSpace(m) != "" {
|
||||
return m
|
||||
}
|
||||
|
||||
// xAI 风格:{"code":"...","error":"..."}。不要把未知对象当作消息透出。
|
||||
if e := gjson.GetBytes(body, "error"); e.Type == gjson.String {
|
||||
return e.String()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractUpstreamErrorCode(body []byte) string {
|
||||
@@ -319,20 +327,21 @@ func extractUpstreamErrorCode(body []byte) string {
|
||||
}
|
||||
|
||||
inner := strings.TrimSpace(gjson.GetBytes(body, "error.message").String())
|
||||
if !strings.HasPrefix(inner, "{") {
|
||||
return ""
|
||||
}
|
||||
|
||||
if code := strings.TrimSpace(gjson.Get(inner, "error.code").String()); code != "" {
|
||||
return code
|
||||
}
|
||||
|
||||
if lastBrace := strings.LastIndex(inner, "}"); lastBrace >= 0 {
|
||||
if code := strings.TrimSpace(gjson.Get(inner[:lastBrace+1], "error.code").String()); code != "" {
|
||||
if strings.HasPrefix(inner, "{") {
|
||||
if code := strings.TrimSpace(gjson.Get(inner, "error.code").String()); code != "" {
|
||||
return code
|
||||
}
|
||||
|
||||
if lastBrace := strings.LastIndex(inner, "}"); lastBrace >= 0 {
|
||||
if code := strings.TrimSpace(gjson.Get(inner[:lastBrace+1], "error.code").String()); code != "" {
|
||||
return code
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if code := gjson.GetBytes(body, "code"); code.Type == gjson.String || code.Type == gjson.Number {
|
||||
return strings.TrimSpace(code.String())
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestExtractUpstreamErrorMessageFormats(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
body string
|
||||
want string
|
||||
}{
|
||||
{"xai string error", `{"code":"invalid_image","error":"Image could not be decoded."}`, "Image could not be decoded."},
|
||||
{"nested message", `{"error":{"message":"nested"},"detail":"detail","message":"message"}`, "nested"},
|
||||
{"embedded nested message", `{"error":{"message":"{\"error\":{\"message\":\"embedded\"}}"}}`, "embedded"},
|
||||
{"detail retains priority", `{"error":"xai","detail":"detail","message":"message"}`, "detail"},
|
||||
{"message retains priority", `{"error":"xai","message":"message"}`, "message"},
|
||||
{"blank legacy fields", `{"error":"xai","detail":" ","message":" "}`, "xai"},
|
||||
{"unknown error object", `{"error":{"debug":"private diagnostic"}}`, ""},
|
||||
{"error array", `{"error":["private diagnostic"]}`, ""},
|
||||
{"numeric error", `{"error":400}`, ""},
|
||||
{"null error", `{"error":null}`, ""},
|
||||
{"plain text", `upstream internal diagnostic`, ""},
|
||||
{"empty", ``, ""},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, extractUpstreamErrorMessage([]byte(tt.body)))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractUpstreamErrorCodeFormats(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
body string
|
||||
want string
|
||||
}{
|
||||
{"xai string code", `{"code":" invalid_image ","error":"Image could not be decoded."}`, "invalid_image"},
|
||||
{"numeric code", `{"code":400,"error":"Bad input"}`, "400"},
|
||||
{"nested code retains priority", `{"error":{"code":"nested"},"code":"top"}`, "nested"},
|
||||
{"embedded code retains priority", `{"error":{"message":"{\"error\":{\"code\":\"embedded\"}}"},"code":"top"}`, "embedded"},
|
||||
{"embedded code with suffix", `{"error":{"message":"{\"error\":{\"code\":\"embedded\"}} (upstream)"},"code":"top"}`, "embedded"},
|
||||
{"embedded message without code", `{"error":{"message":"{\"error\":{\"message\":\"reason\"}}"},"code":"top"}`, "top"},
|
||||
{"blank nested code", `{"error":{"code":" "},"code":"top"}`, "top"},
|
||||
{"object code", `{"code":{"private":"diagnostic"}}`, ""},
|
||||
{"array code", `{"code":["diagnostic"]}`, ""},
|
||||
{"boolean code", `{"code":true}`, ""},
|
||||
{"null code", `{"code":null}`, ""},
|
||||
{"no code", `{"error":{"message":"reason"}}`, ""},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
require.Equal(t, tt.want, extractUpstreamErrorCode([]byte(tt.body)))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1295,7 +1295,7 @@ func (s *OpenAIGatewayService) handleGrokMediaErrorResponse(
|
||||
Detail: upstreamDetail,
|
||||
})
|
||||
MarkResponseCommitted(c)
|
||||
writeGrokMediaErrorResponse(c, http.StatusForbidden, "invalid_request_error", clientMsg)
|
||||
writeGrokMediaErrorResponse(c, http.StatusForbidden, "invalid_request_error", clientMsg, extractUpstreamErrorCode(body))
|
||||
return nil, fmt.Errorf("grok content policy rejection: %s", clientMsg)
|
||||
}
|
||||
|
||||
@@ -1309,7 +1309,7 @@ func (s *OpenAIGatewayService) handleGrokMediaErrorResponse(
|
||||
"Upstream request failed",
|
||||
); matched {
|
||||
MarkResponseCommitted(c)
|
||||
writeGrokMediaErrorResponse(c, status, errType, errMsg)
|
||||
writeGrokMediaErrorResponse(c, status, errType, errMsg, "")
|
||||
return nil, fmt.Errorf("upstream error: %d (passthrough rule matched) message=%s", resp.StatusCode, upstreamMsg)
|
||||
}
|
||||
|
||||
@@ -1327,7 +1327,7 @@ func (s *OpenAIGatewayService) handleGrokMediaErrorResponse(
|
||||
Detail: upstreamDetail,
|
||||
})
|
||||
MarkResponseCommitted(c)
|
||||
writeGrokMediaErrorResponse(c, http.StatusInternalServerError, "upstream_error", "Upstream gateway error")
|
||||
writeGrokMediaErrorResponse(c, http.StatusInternalServerError, "upstream_error", "Upstream gateway error", "")
|
||||
return nil, fmt.Errorf("upstream error: %d (not in custom error codes) message=%s", resp.StatusCode, upstreamMsg)
|
||||
}
|
||||
|
||||
@@ -1362,7 +1362,7 @@ func (s *OpenAIGatewayService) handleGrokMediaErrorResponse(
|
||||
}
|
||||
|
||||
MarkResponseCommitted(c)
|
||||
writeGrokMediaErrorResponse(c, resp.StatusCode, grokMediaErrorType(resp.StatusCode), upstreamMsg)
|
||||
writeGrokMediaErrorResponse(c, resp.StatusCode, grokMediaErrorType(resp.StatusCode), upstreamMsg, extractUpstreamErrorCode(body))
|
||||
return nil, fmt.Errorf("upstream error: %d %s", resp.StatusCode, upstreamMsg)
|
||||
}
|
||||
|
||||
@@ -1379,16 +1379,18 @@ func grokMediaErrorType(statusCode int) string {
|
||||
}
|
||||
}
|
||||
|
||||
func writeGrokMediaErrorResponse(c *gin.Context, statusCode int, errType, message string) {
|
||||
func writeGrokMediaErrorResponse(c *gin.Context, statusCode int, errType, message, code string) {
|
||||
if c == nil || c.Writer == nil || c.Writer.Written() {
|
||||
return
|
||||
}
|
||||
c.JSON(statusCode, gin.H{
|
||||
"error": gin.H{
|
||||
"type": strings.TrimSpace(errType),
|
||||
"message": strings.TrimSpace(message),
|
||||
},
|
||||
})
|
||||
payload := gin.H{
|
||||
"type": strings.TrimSpace(errType),
|
||||
"message": sanitizeUpstreamErrorMessage(strings.TrimSpace(message)),
|
||||
}
|
||||
if code = sanitizeUpstreamErrorMessage(strings.TrimSpace(code)); code != "" {
|
||||
payload["code"] = code
|
||||
}
|
||||
c.JSON(statusCode, gin.H{"error": payload})
|
||||
}
|
||||
|
||||
func writeGrokMediaResponse(c *gin.Context, resp *http.Response, body []byte, filter *responseheaders.CompiledHeaderFilter) {
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestGrokMediaUpstreamErrorFields(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantMessage string
|
||||
wantCode string
|
||||
}{
|
||||
{"flat error", 400, `{"code":"invalid_image","error":"Image could not be decoded."}`, "Image could not be decoded.", "invalid_image"},
|
||||
{"nested error", 400, `{"code":"outer","error":{"code":"invalid_size","message":"Invalid size."}}`, "Invalid size.", "invalid_size"},
|
||||
{"message without code", 400, `{"error":"Invalid size."}`, "Invalid size.", ""},
|
||||
{"redact code query", 400, `{"error":"Invalid size.","code":"https://example.test?key=secret&n=1"}`, "Invalid size.", "https://example.test?key=***&n=1"},
|
||||
{"unknown object", 400, `{"error":{"debug":"private diagnostic"},"code":{"debug":"private code"}}`, "xAI upstream returned status 400", ""},
|
||||
{"content refusal", 403, `{"code":"permission-denied","error":"Content violates usage guidelines."}`, "Content violates usage guidelines.", "permission-denied"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/edits", nil)
|
||||
repo := &grokQuotaAccountRepo{}
|
||||
svc := &OpenAIGatewayService{accountRepo: repo}
|
||||
account := &Account{ID: 1, Platform: PlatformGrok, Type: AccountTypeOAuth}
|
||||
_, err := svc.handleGrokMediaErrorResponse(context.Background(), &http.Response{
|
||||
StatusCode: tt.status, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(tt.body)),
|
||||
}, c, account, "request-id", "grok-imagine-image")
|
||||
require.Error(t, err)
|
||||
var failover *UpstreamFailoverError
|
||||
require.False(t, errors.As(err, &failover))
|
||||
require.True(t, IsResponseCommitted(c))
|
||||
require.Equal(t, tt.status, recorder.Code)
|
||||
require.Equal(t, tt.wantMessage, gjson.GetBytes(recorder.Body.Bytes(), "error.message").String())
|
||||
require.Equal(t, tt.wantCode, gjson.GetBytes(recorder.Body.Bytes(), "error.code").String())
|
||||
if tt.wantCode == "" {
|
||||
require.False(t, gjson.GetBytes(recorder.Body.Bytes(), "error.code").Exists())
|
||||
}
|
||||
require.NotContains(t, recorder.Body.String(), "secret")
|
||||
require.NotContains(t, recorder.Body.String(), "private")
|
||||
require.Zero(t, repo.tempUnschedCalls)
|
||||
require.Zero(t, repo.rateLimitedCalls)
|
||||
require.Zero(t, repo.updateCalls)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrokMediaErrorRewritesKeepPriority(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
passthroughRule bool
|
||||
passthroughBody bool
|
||||
}{
|
||||
{name: "account error code filter"},
|
||||
{name: "configured response rule", passthroughRule: true},
|
||||
{name: "configured message passthrough", passthroughRule: true, passthroughBody: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/edits", nil)
|
||||
account := &Account{ID: 1, Platform: PlatformGrok, Type: AccountTypeAPIKey, Credentials: map[string]any{
|
||||
"custom_error_codes_enabled": true, "custom_error_codes": []any{float64(http.StatusTooManyRequests)},
|
||||
}}
|
||||
wantStatus, wantMessage := http.StatusInternalServerError, "Upstream gateway error"
|
||||
if tt.passthroughRule {
|
||||
rules := &ErrorPassthroughService{}
|
||||
rule := newNonFailoverPassthroughRule(http.StatusBadRequest, "invalid_image", http.StatusUnprocessableEntity, "Configured error")
|
||||
rule.PassthroughBody = tt.passthroughBody
|
||||
rules.setLocalCache([]*model.ErrorPassthroughRule{rule})
|
||||
BindErrorPassthroughService(c, rules)
|
||||
wantStatus, wantMessage = http.StatusUnprocessableEntity, "Configured error"
|
||||
if tt.passthroughBody {
|
||||
wantMessage = "Original error: https://example.test?access_token=***"
|
||||
}
|
||||
}
|
||||
svc := &OpenAIGatewayService{accountRepo: &grokQuotaAccountRepo{}}
|
||||
_, err := svc.handleGrokMediaErrorResponse(context.Background(), &http.Response{
|
||||
StatusCode: http.StatusBadRequest, Header: http.Header{},
|
||||
Body: io.NopCloser(strings.NewReader(`{"code":"invalid_image","error":"Original error: https://example.test?access_token=secret"}`)),
|
||||
}, c, account, "request-id", "grok-imagine-image")
|
||||
require.Error(t, err)
|
||||
require.Equal(t, wantStatus, recorder.Code)
|
||||
require.Equal(t, wantMessage, gjson.GetBytes(recorder.Body.Bytes(), "error.message").String())
|
||||
require.False(t, gjson.GetBytes(recorder.Body.Bytes(), "error.code").Exists())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrokMediaRetryableErrorKeepsOriginalBody(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/edits", nil)
|
||||
body := `{"code":"temporarily_unavailable","error":"Try again later"}`
|
||||
svc := &OpenAIGatewayService{accountRepo: &grokQuotaAccountRepo{}}
|
||||
_, err := svc.handleGrokMediaErrorResponse(context.Background(), &http.Response{
|
||||
StatusCode: http.StatusServiceUnavailable, Header: http.Header{"X-Request-Id": {"request-id"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}, c, &Account{ID: 1, Platform: PlatformGrok, Type: AccountTypeOAuth}, "request-id", "grok-imagine-image")
|
||||
var failover *UpstreamFailoverError
|
||||
require.ErrorAs(t, err, &failover)
|
||||
require.Equal(t, http.StatusServiceUnavailable, failover.StatusCode)
|
||||
require.Equal(t, body, string(failover.ResponseBody))
|
||||
require.Equal(t, "request-id", failover.ResponseHeaders.Get("X-Request-Id"))
|
||||
require.False(t, IsResponseCommitted(c))
|
||||
require.False(t, c.Writer.Written())
|
||||
require.Empty(t, recorder.Body.String())
|
||||
}
|
||||
Reference in new issue
Block a user