From 22693fb4feed5c71c8b18883fca1f7e5e6e50639 Mon Sep 17 00:00:00 2001 From: cyh Date: Sat, 7 Nov 2026 02:07:37 +0800 Subject: [PATCH] fix(grok): classify Grok Voice body read failures Stalled uploads to /v1/tts, /v1/stt and /v1/custom-voices reach GrokVoice directly. Its read errors fell through to a 400 carrying err.Error(): with the read timeout now preserved, that reported a timeout as a malformed request and returned the raw socket error. Keep the validation message for a missing body and send every read error through the shared classifier. --- backend/internal/handler/grok_audio.go | 19 +++++-- .../internal/handler/grok_audio_body_test.go | 56 +++++++++++++++++++ 2 files changed, 71 insertions(+), 4 deletions(-) diff --git a/backend/internal/handler/grok_audio.go b/backend/internal/handler/grok_audio.go index d93e6e6742..3b9b7c9dda 100644 --- a/backend/internal/handler/grok_audio.go +++ b/backend/internal/handler/grok_audio.go @@ -203,10 +203,16 @@ func (h *OpenAIGatewayHandler) GrokVoice(c *gin.Context, endpoint string) { body, err := readGrokVoiceGatewayBody(c) if err != nil { - if handleRequestBodyReadError(c, requestLogger(c, "handler.openai_gateway.grok_voice"), err) { + if errors.Is(err, errGrokVoiceBodyRequired) { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return } - h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + bodyLog := requestLogger(c, "handler.openai_gateway.grok_voice", zap.String("endpoint", endpoint)) + if handleRequestBodyReadError(c, bodyLog, err) { + return + } + status, message := requestBodyReadFailure(bodyLog, c.Request, err) + h.errorResponse(c, status, "invalid_request_error", message) return } if endpoint == "tts" { @@ -377,15 +383,20 @@ func (h *OpenAIGatewayHandler) recordGrokVoiceUsage( }) } +var errGrokVoiceBodyRequired = errors.New("request body is required") + +// readGrokVoiceGatewayBody returns errGrokVoiceBodyRequired for a missing body; +// any other error comes from reading the body and goes through the shared +// read-failure classification. func readGrokVoiceGatewayBody(c *gin.Context) ([]byte, error) { if c == nil || c.Request == nil { - return nil, errors.New("request body is required") + return nil, errGrokVoiceBodyRequired } if c.Request.Body == nil { if c.Request.Method == http.MethodGet || c.Request.Method == http.MethodDelete { return nil, nil } - return nil, errors.New("request body is required") + return nil, errGrokVoiceBodyRequired } return pkghttputil.ReadRequestBodyWithPrealloc(c.Request) } diff --git a/backend/internal/handler/grok_audio_body_test.go b/backend/internal/handler/grok_audio_body_test.go index 84621dce9f..80df25a844 100644 --- a/backend/internal/handler/grok_audio_body_test.go +++ b/backend/internal/handler/grok_audio_body_test.go @@ -1,10 +1,14 @@ package handler import ( + "io" + "net" "net/http" "net/http/httptest" + "os" "strings" "testing" + "testing/iotest" "github.com/Wei-Shaw/sub2api/internal/config" pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" @@ -51,3 +55,55 @@ func TestGrokVoiceRequestBodyMemoryOverload(t *testing.T) { }) } } + +// Read failures other than the memory budget go through the shared classifier: +// a timeout is a 408 with a fixed message, never the raw socket error, and a +// missing body keeps its validation message. +func TestGrokVoiceRequestBodyReadFailures(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeSimple} + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + h := &OpenAIGatewayHandler{ + gatewayService: &service.OpenAIGatewayService{}, + billingCacheService: billing, + apiKeyService: &service.APIKeyService{}, + concurrencyHelper: &ConcurrencyHelper{concurrencyService: service.NewConcurrencyService(nil)}, + cfg: cfg, + } + timeoutErr := &net.OpError{Op: "read", Net: "tcp", Source: &net.TCPAddr{IP: net.IPv4(10, 0, 0, 1), Port: 8080}, Err: os.ErrDeadlineExceeded} + for _, tc := range []struct { + name string + body io.Reader + wantStatus int + wantText string + }{ + {"timeout", iotest.ErrReader(timeoutErr), http.StatusRequestTimeout, "Timed out reading request body"}, + {"truncated", iotest.ErrReader(io.ErrUnexpectedEOF), http.StatusBadRequest, "Failed to read request body"}, + {"missing", nil, http.StatusBadRequest, "request body is required"}, + } { + t.Run(tc.name, func(t *testing.T) { + router := gin.New() + router.Use(func(c *gin.Context) { + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{Platform: service.PlatformGrok}, + User: &service.User{ID: 1}, + }) + c.Next() + }) + router.POST("/v1/tts", func(c *gin.Context) { h.GrokVoice(c, "tts") }) + req := httptest.NewRequest(http.MethodPost, "/v1/tts", nil) + if tc.body != nil { + req.Body = io.NopCloser(tc.body) + } else { + req.Body = nil + } + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + require.Equal(t, tc.wantStatus, rec.Code, rec.Body.String()) + require.Contains(t, rec.Body.String(), tc.wantText) + require.NotContains(t, rec.Body.String(), "10.0.0.1") + }) + } +}