mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-12-05 08:03:01 +00:00
fix(task): build text-only multipart requests from JSON (#8198)
* fix(task): build text-only multipart requests from JSON * fix(task): preserve client content type across multipart retries
This commit is contained in:
2 files changed
+73
-11
No files matched your search
@@ -56,6 +56,8 @@ type requestDescriptor struct {
|
||||
// BodyText is the body as JSON.stringify wrote it, for a plugin that
|
||||
// preserves JSON order: the upstream gets the members in that order.
|
||||
BodyText json.RawMessage `json:"-"`
|
||||
|
||||
multipartContentType string
|
||||
}
|
||||
|
||||
// orderedRequestDescriptor is requestDescriptor as a plugin that preserves
|
||||
@@ -363,17 +365,16 @@ func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, erro
|
||||
return requestURL, pluginruntime.ValidateRequestURL(requestURL, info.ChannelBaseUrl, a.plugin.Meta.AllowedHosts)
|
||||
}
|
||||
|
||||
func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, _ *relaycommon.RelayInfo) error {
|
||||
func (a *TaskAdaptor) BuildRequestHeader(_ *gin.Context, req *http.Request, _ *relaycommon.RelayInfo) error {
|
||||
if a.submit == nil {
|
||||
return fmt.Errorf("plugin submit request was not built")
|
||||
}
|
||||
for name, value := range a.submit.Headers {
|
||||
req.Header.Set(name, value)
|
||||
}
|
||||
// BuildRequestBody rebuilt the multipart body with a new boundary and put its
|
||||
// Content-Type on the client request; a plugin's own Content-Type cannot match it.
|
||||
if a.submit.BodyType == "multipart" {
|
||||
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
|
||||
// The upstream Content-Type must carry the boundary used to encode the body.
|
||||
if a.submit.multipartContentType != "" {
|
||||
req.Header.Set("Content-Type", a.submit.multipartContentType)
|
||||
}
|
||||
applyTaskCredential(a.credential, &url.URL{}, req.Header)
|
||||
return nil
|
||||
@@ -385,11 +386,7 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
|
||||
return nil, err
|
||||
}
|
||||
if descriptor.BodyType == "multipart" {
|
||||
form, parseErr := common.ParseMultipartFormReusable(c)
|
||||
if parseErr != nil {
|
||||
return nil, parseErr
|
||||
}
|
||||
defer form.RemoveAll()
|
||||
var form *multipart.Form
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
for _, part := range descriptor.Parts {
|
||||
@@ -409,6 +406,14 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
|
||||
}
|
||||
continue
|
||||
}
|
||||
// Text-only multipart output may originate from a JSON request.
|
||||
if form == nil {
|
||||
form, err = common.ParseMultipartFormReusable(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer form.RemoveAll()
|
||||
}
|
||||
field, index, validRef := pluginruntime.ParseFileReference(part.FileRef)
|
||||
files := form.File[field]
|
||||
if !validRef || index >= len(files) {
|
||||
@@ -442,7 +447,7 @@ func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayIn
|
||||
if err = writer.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Request.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
descriptor.multipartContentType = writer.FormDataContentType()
|
||||
return bytes.NewReader(body.Bytes()), nil
|
||||
}
|
||||
if descriptor.Body == nil {
|
||||
|
||||
@@ -89,6 +89,63 @@ func TestTaskAdaptorRejectsDeprecatedClientResponse(t *testing.T) {
|
||||
assert.Contains(t, taskErr.Error.Error(), "must not return clientResponse")
|
||||
}
|
||||
|
||||
func TestTaskAdaptorBuildsMultipartFromJSON(t *testing.T) {
|
||||
source := `
|
||||
export const meta = {apiVersion:1,key:"json-multipart",name:"JSON Multipart",version:"1.0.0",author:{name:"Test"},models:["m"],fetchMode:"per_task"};
|
||||
export function buildSubmitRequest(ctx) {
|
||||
const parts = [{name:"model",value:"m"},{name:"prompt",value:ctx.requestBody.prompt},{name:"tag",value:"first"},{name:"tag",value:"second"},{name:"empty",value:""}];
|
||||
if (ctx.requestBody.reference) parts.push({name:"input_reference",fileRef:"request_file:input_reference"});
|
||||
return {url:ctx.baseUrl+"/submit",headers:{"Content-Type":ctx.requestHeaders["Content-Type"]},bodyType:"multipart",parts};
|
||||
}
|
||||
export function parseSubmitResponse(){return {taskId:"1"}} export function buildQueryRequest(){return {url:"https://example.com"}} export function parseTaskResult(){return {status:"SUCCESS"}}
|
||||
`
|
||||
plugin, err := pluginruntime.NewRegistry().Register(source, pluginruntime.Options{})
|
||||
require.NoError(t, err)
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
reference bool
|
||||
wantError string
|
||||
}{
|
||||
{name: "text fields"},
|
||||
{name: "file reference requires an upload", reference: true, wantError: "multipart boundary not found"},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
adaptor := New(plugin)
|
||||
info := &relaycommon.RelayInfo{ChannelMeta: &relaycommon.ChannelMeta{ChannelBaseUrl: "https://provider.example"}, TaskRelayInfo: &relaycommon.TaskRelayInfo{}}
|
||||
adaptor.Init(info)
|
||||
request := map[string]any{"model": "m", "prompt": "paper plane", "reference": testCase.reference}
|
||||
encoded, err := common.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/videos", bytes.NewReader(encoded))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Set("task_request", request)
|
||||
|
||||
body, err := adaptor.BuildRequestBody(c, info)
|
||||
if testCase.wantError != "" {
|
||||
require.EqualError(t, err, testCase.wantError)
|
||||
assert.Nil(t, body)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
upstreamRequest := httptest.NewRequest(http.MethodPost, "https://provider.example/submit", body)
|
||||
require.NoError(t, adaptor.BuildRequestHeader(c, upstreamRequest, info))
|
||||
assert.Equal(t, "application/json", c.GetHeader("Content-Type"))
|
||||
mediaType, params, err := mime.ParseMediaType(upstreamRequest.Header.Get("Content-Type"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "multipart/form-data", mediaType)
|
||||
require.NotEmpty(t, params["boundary"])
|
||||
require.NoError(t, upstreamRequest.ParseMultipartForm(1024))
|
||||
t.Cleanup(func() { require.NoError(t, upstreamRequest.MultipartForm.RemoveAll()) })
|
||||
assert.Equal(t, map[string][]string{
|
||||
"model": {"m"}, "prompt": {"paper plane"}, "tag": {"first", "second"}, "empty": {""},
|
||||
}, upstreamRequest.MultipartForm.Value)
|
||||
assert.Empty(t, upstreamRequest.MultipartForm.File)
|
||||
t.Log("JSON input produced a decodable multipart request with repeated and empty text fields")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskAdaptorBuildsMultipartFromOpaqueFileReference(t *testing.T) {
|
||||
// The plugin forwards the client's Content-Type, whose boundary is not the one of the rebuilt body.
|
||||
source := `
|
||||
|
||||
Reference in new issue
Block a user