Skip to content

Commit d10eafb

Browse files
committed
fix(relay): report the real cause when a request body cannot be read
POST /v1/responses, /v1/videos and /v1/images/* pass through the task plugin endpoint check before any model is matched. A body that failed to read or parse there got 400 "Invalid task protocol request" even when no plugin claims the model, and the log carried only that sentence, so the real cause, such as a body over MAX_REQUEST_BODY_MB or a connection cut mid-upload, was lost. These requests now get the cause in the response and in the log, and a body over the size limit gets 413 with the limit in the message. Other endpoints such as /v1/chat/completions no longer repeat the prefix, as in "Invalid request: Invalid request: invalid JSON request body".
1 parent 63cecab commit d10eafb

3 files changed

Lines changed: 66 additions & 7 deletions

File tree

‎middleware/distributor.go‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -236,17 +236,13 @@ func getModelFromRequest(c *gin.Context) (*ModelRequest, error) {
236236
}
237237
}
238238
if strings.HasPrefix(c.Request.Header.Get("Content-Type"), "application/json") {
239-
modelRequest, err := getModelFromJSONBody(c)
240-
if err != nil {
241-
return nil, errors.New(i18n.T(c, i18n.MsgDistributorInvalidRequest, map[string]any{"Error": err.Error()}))
242-
}
243-
return modelRequest, nil
239+
return getModelFromJSONBody(c)
244240
}
245241

246242
var modelRequest ModelRequest
247243
err := common.UnmarshalBodyReusable(c, &modelRequest)
248244
if err != nil {
249-
return nil, errors.New(i18n.T(c, i18n.MsgDistributorInvalidRequest, map[string]any{"Error": err.Error()}))
245+
return nil, err
250246
}
251247
return &modelRequest, nil
252248
}

‎middleware/task_plugin.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"github.com/QuantumNous/new-api/common"
2121
"github.com/QuantumNous/new-api/constant"
2222
"github.com/QuantumNous/new-api/dto"
23+
"github.com/QuantumNous/new-api/i18n"
2324
"github.com/QuantumNous/new-api/logger"
2425
"github.com/QuantumNous/new-api/model"
2526
pluginruntime "github.com/QuantumNous/new-api/pkg/jsplugin"
@@ -333,7 +334,11 @@ func PinTaskPluginEndpoint() gin.HandlerFunc {
333334
modelRequest, err := getModelFromRequest(c)
334335
if err != nil {
335336
if _, _, protocolPath := pluginruntime.LookupHostProtocolOperation(c.Request.Method, c.Request.URL.Path); protocolPath {
336-
abortWithOpenAiMessage(c, http.StatusBadRequest, "Invalid task protocol request")
337+
statusCode := http.StatusBadRequest
338+
if common.IsRequestBodyTooLargeError(err) {
339+
statusCode = http.StatusRequestEntityTooLarge
340+
}
341+
abortWithOpenAiMessage(c, statusCode, i18n.T(c, i18n.MsgDistributorInvalidRequest, map[string]any{"Error": err.Error()}))
337342
return
338343
}
339344
c.Next()

‎middleware/task_plugin_test.go‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"net/textproto"
1313
"strings"
1414
"testing"
15+
"testing/iotest"
1516

1617
"github.com/QuantumNous/new-api/common"
1718
"github.com/QuantumNous/new-api/constant"
@@ -784,6 +785,63 @@ func TestTaskPluginEndpointUsesOneCanonicalModelForDuplicateJSONKeys(t *testing.
784785
}
785786
}
786787

788+
func TestRequestBodyFailuresReportTheirCause(t *testing.T) {
789+
require.NoError(t, appI18n.Init())
790+
require.NotNil(t, jsplugin.DefaultRegistry.Generation(), "the built-in plugins keep a routing generation, as in production")
791+
previous := constant.MaxRequestBodyMB
792+
constant.MaxRequestBodyMB = 1
793+
t.Cleanup(func() { constant.MaxRequestBodyMB = previous })
794+
795+
router := gin.New()
796+
router.POST("/v1/responses", PinTaskPluginEndpoint(), PrepareTaskPluginEndpoint(), Distribute(), func(c *gin.Context) {
797+
c.Status(http.StatusNoContent)
798+
})
799+
router.POST("/v1/chat/completions", Distribute(), func(c *gin.Context) {
800+
c.Status(http.StatusNoContent)
801+
})
802+
tests := []struct {
803+
name string
804+
path string
805+
body io.Reader
806+
status int
807+
message string
808+
}{
809+
{
810+
name: "oversized body on a plugin protocol path",
811+
path: "/v1/responses",
812+
body: strings.NewReader(`{"model":"gpt-x","input":"` + strings.Repeat("a", 1<<20) + `"}`),
813+
status: http.StatusRequestEntityTooLarge,
814+
message: "Invalid request: request body exceeds 1 MB: request body too large",
815+
},
816+
{
817+
name: "body cut off on a plugin protocol path",
818+
path: "/v1/responses",
819+
body: io.MultiReader(strings.NewReader(`{"model":"gpt-x","input":"`), iotest.ErrReader(io.ErrUnexpectedEOF)),
820+
status: http.StatusBadRequest,
821+
message: "Invalid request: unexpected EOF",
822+
},
823+
{
824+
name: "invalid JSON on an ordinary path",
825+
path: "/v1/chat/completions",
826+
body: strings.NewReader(`{"model":"gpt-x",`),
827+
status: http.StatusBadRequest,
828+
message: "Invalid request: invalid JSON request body",
829+
},
830+
}
831+
for _, testCase := range tests {
832+
t.Run(testCase.name, func(t *testing.T) {
833+
request := httptest.NewRequest(http.MethodPost, testCase.path, testCase.body)
834+
request.Header.Set("Content-Type", "application/json")
835+
recorder := httptest.NewRecorder()
836+
837+
router.ServeHTTP(recorder, request)
838+
839+
assert.Equal(t, testCase.status, recorder.Code)
840+
assert.Contains(t, recorder.Body.String(), `"message":"`+testCase.message+` (request id:`)
841+
})
842+
}
843+
}
844+
787845
func TestTaskPluginEndpointOnlyPreservesConditionalMiddlewareSemantics(t *testing.T) {
788846
tests := []struct {
789847
name string

0 commit comments

Comments
 (0)