diff --git a/controller/relay_task_plugin_test.go b/controller/relay_task_plugin_test.go index 28ca4adc1808..15adb3688046 100644 --- a/controller/relay_task_plugin_test.go +++ b/controller/relay_task_plugin_test.go @@ -652,6 +652,22 @@ export function buildQueryRequest(){throw new Error("completed submissions must } } +func TestPassthroughSubmitKeepsAuthErrorRetry(t *testing.T) { + c := taskSubmissionTestContext() + unauthorized := &dto.TaskError{StatusCode: http.StatusUnauthorized} + forbidden := &dto.TaskError{StatusCode: http.StatusForbidden} + assert.Equal(t, "retry", decideTaskRetry(c, unauthorized, 1).Action) + assert.Equal(t, "retry", decideTaskRetry(c, forbidden, 1).Action) + c.Set(pluginruntime.ContextKeyPinnedRoute, pluginruntime.PinnedRoute{ + Route: pluginruntime.Route{UpstreamError: pluginruntime.RouteUpstreamErrorPassthrough}, + }) + assert.Equal(t, "retry", decideTaskRetry(c, unauthorized, 1).Action) + assert.Equal(t, "retry", decideTaskRetry(c, forbidden, 1).Action) + assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "status_not_retryable", Source: "system"}, decideTaskRetry(c, &dto.TaskError{StatusCode: http.StatusBadRequest}, 1)) + assert.Equal(t, "retry", decideTaskRetry(c, &dto.TaskError{StatusCode: http.StatusTooManyRequests}, 1).Action) + assert.Equal(t, "retry", decideTaskRetry(c, &dto.TaskError{StatusCode: http.StatusInternalServerError}, 1).Action) +} + func TestAcceptedSubmitStreamNeverRetries(t *testing.T) { c := taskSubmissionTestContext() assert.Equal(t, service.PolicyDecision{Action: "stop", Reason: "task_accepted", Source: "system"}, decideTaskRetry(c, &dto.TaskError{StatusCode: 502, LocalError: true, NoRetry: true}, 3)) diff --git a/docs/plugin-api/v1.d.ts b/docs/plugin-api/v1.d.ts index 9db3c7385496..6c827db46a86 100644 --- a/docs/plugin-api/v1.d.ts +++ b/docs/plugin-api/v1.d.ts @@ -67,7 +67,7 @@ export interface ProtocolDecodeContext extends NativeDecodeContext {protocol: Pr export type SubmitIntent = {kind: "submit"; model: string; action?: string; requestBody?: unknown; originTaskIds?: readonly string[]}; export type QueryIntent = {kind: "query"; taskIds: readonly string[]}; export type TaskIntent = SubmitIntent | QueryIntent; -export interface NativeRoute {method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; /** The vendor's own path; the host also serves it under /{key} unless its first segment is the key or a proper prefix of it. */ path: string; type: "submit" | "query" | "dynamic"; action?: string; /** Query routes: the path parameter carrying the gateway task id or, when the path has none, the query-string parameter of that name. Default "task_id". */ taskIdParam?: string; decode?: string; render: string; models?: readonly string[]; retainResult?: boolean} +export interface NativeRoute {method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; /** The vendor's own path; the host also serves it under /{key} unless its first segment is the key or a proper prefix of it. */ path: string; type: "submit" | "query" | "dynamic"; action?: string; /** Query routes: the path parameter carrying the gateway task id or, when the path has none, the query-string parameter of that name. Default "task_id". */ taskIdParam?: string; decode?: string; render: string; models?: readonly string[]; retainResult?: boolean; /** Dynamic routes only. "collect" renders found tasks and reports the rest on ctx.missedTaskIds. On a shared path, a batch split across plugins is not found. */ missing?: "collect"; /** Submit routes only. "passthrough" gives the error presenter the vendor's non-2xx status, body, and Retry-After. */ upstreamError?: "passthrough"} export type ProtocolName = "openai_responses" | "openai_video" | "openai_image"; export type ResponsesMode = "stream" | "sync" | "background"; export type ProtocolClaim = @@ -124,11 +124,11 @@ export interface UpstreamResponse {statusCode: number; headers: Readonly>} +/** A query presenter's context: artifacts holds the gateway download addresses of one task in SUCCESS (from listArtifacts) and is empty otherwise. Throwing "artifact_not_found" answers 404. missedTaskIds is set only for a dynamic route that declares missing: "collect". */ +export interface NativeQueryContext extends NativeDecodeContext {artifacts: Readonly>; missedTaskIds?: readonly string[]} /** A native presenter's reply with the vendor's own HTTP status (200–599); only Location and Retry-After may be set, and a reply without __body has no body. Any other value is the JSON body of a 200 reply, or of the host's status for the error presenter. */ export type NativeReply = {__status: number; __headers?: {Location?: string; "Retry-After"?: string}; __body?: unknown}; -export declare const native: Record TaskIntent) | ((ctx: NativeQueryContext, task: TaskView | readonly TaskView[]) => unknown | NativeReply)> & {error?: (ctx: NativeDecodeContext, error: {code: string; message: string; httpStatus: number; retryable: boolean; requestId: string}) => unknown | NativeReply}; +export declare const native: Record TaskIntent) | ((ctx: NativeQueryContext, task: TaskView | readonly TaskView[]) => unknown | NativeReply)> & {error?: (ctx: NativeDecodeContext, error: {code: string; message: string; httpStatus: number; retryable: boolean; requestId: string; upstream?: {status: number; body: unknown; retryAfter?: string}}) => unknown | NativeReply}; export declare const protocols: { openai_responses?: {decodeRequest(ctx: ProtocolDecodeContext): SubmitIntent; renderEvents?(ctx: unknown, task: TaskView, previousState: unknown): unknown; renderFinal?(ctx: unknown, task: TaskView): unknown}; openai_video?: {decodeRequest(ctx: ProtocolDecodeContext): SubmitIntent; render(ctx: unknown, task: TaskView): unknown}; diff --git a/docs/plugin-api/v1.md b/docs/plugin-api/v1.md index 110c0bba1d64..3f364121aef5 100644 --- a/docs/plugin-api/v1.md +++ b/docs/plugin-api/v1.md @@ -32,12 +32,16 @@ export const meta = { A plugin declares its vendor's own paths. The gateway serves each route at that path and again under `/{key}`: doubao's `POST /api/v3/contents/generations/tasks` is also `POST /doubao/api/v3/contents/generations/tasks`, which reaches doubao alone. A route whose first segment is the key, or a proper prefix of it, is already the plugin's own address and gets no copy: alibaba's `/ali/...`, sunoapi's `/suno/...`, `/hailuo/...` for hailuo. The own prefixes of the built-in plugins are protected: another plugin may not take one as its key, and its top-level routes under one are not served. -Several plugins may declare the same method and path shape, for the same model as well. Every plugin declaring a `submit` path decodes the request, in ascending key order; the first that accepts it names the model, the others that accept the same model stay candidates, and the selected channel decides which plugin executes, as on a shared host protocol, billing the task at that plugin's `::` expression. A decoder's `model` is matched as on the host protocols: a case variant stands for the declared model and the task takes the declared spelling; an alias that an enabled channel lists and maps through `model_mapping` stays the task's model, and the driver reads the mapped name from `ctx.upstreamModel`. A single candidate's rejection reaches the client as it is; when all of several reject, the client gets each message prefixed with the plugin keys that gave it. A `query` path answers through the task's own plugin, the first in key order owning it; a task none of them owns is not found, like a missing one. A `dynamic` path answers a query through the first plugin owning the tasks and otherwise continues as a submit. Each plugin reads the path parameters under the names it declares, so `/v1/videos/:request_id` and `/v1/videos/:task_id` share a path. A catch-all (`*name`) beside another plugin's literal segment at the same position cannot be served together; the gateway then excludes one plugin with a routing error. +Several plugins may declare the same method and path shape, for the same model as well. Every plugin declaring a `submit` path decodes the request, in ascending key order; the first that accepts it names the model, the others that accept the same model stay candidates, and the selected channel decides which plugin executes, as on a shared host protocol, billing the task at that plugin's `::` expression. A decoder's `model` is matched as on the host protocols: a case variant stands for the declared model and the task takes the declared spelling; an alias that an enabled channel lists and maps through `model_mapping` stays the task's model, and the driver reads the mapped name from `ctx.upstreamModel`. A single candidate's rejection reaches the client as it is; when all of several reject, the client gets each message prefixed with the plugin keys that gave it. A `query` path answers through the task's own plugin, the first in key order owning it; a task none of them owns is not found, like a missing one. A `dynamic` path answers a query through the first plugin owning the tasks and otherwise continues as a submit. `missing: "collect"` still requires that plugin to own every id any candidate can retrieve. Each plugin reads the path parameters under the names it declares, so `/v1/videos/:request_id` and `/v1/videos/:task_id` share a path. A catch-all (`*name`) beside another plugin's literal segment at the same position cannot be served together; the gateway then excludes one plugin with a routing error. Routes stay out of the reserved namespaces `/v1/tasks`, `/assets` and the console pages, and a key may not be `api` or the first segment of one of them: such a plugin fails to compile. Every plugin, built-in or uploaded, is served at its top-level paths, such as `POST /v1/systemone`, except where a host route of the same method, or the trailing-slash redirect it causes, answers first, or where the first segment is another plugin's key or a built-in plugin's own prefix. Such a route is still served under `/{key}`, and the plugin list (`GET /api/plugin/task`) and detail name it in `skipped_routes` (`"GET /v1/models"`). A plugin whose key is `api`, the first segment of a host route (`v1`, `v1beta`, `mj`, `pg`, `dashboard`) or a built-in plugin's own prefix is excluded with a routing error. A `query` route's task-id parameter only receives gateway task ids, so it never meets a literal host segment: `GET /v1/videos/text2video/:task_id` is free beside the host's `GET /v1/videos/:task_id/content`. Two host routes offer matching requests to plugin routes first, so plugin routes may overlap them. `GET /v1/videos/:task_id` answers through the task's own plugin when the task was submitted on one of that plugin's native routes (at the vendor path, under `/{key}` or under its own prefix) and the plugin serves a `query` route matching the request; every other task gets the OpenAI video object. `POST /v1beta/models/{model}:predictLongRunning` goes to the matching plugin route before the Gemini relay's authentication, rate limit and channel selection; other Gemini actions, and requests no plugin route matches, stay with the relay. `routes[].retainResult` is an optional boolean on `submit` and `dynamic` routes, default `true`. Declare `retainResult: false` only on routes where every successful submission completes immediately (`parseSubmitResponse` returns a terminal `immediate`), typically a vendor's synchronous image API that has no task to re-query. For such a result the host does not persist `task.data`, and the task is thereafter not found on every retrieval surface: the plugin's own `query` routes, `GET /v1/responses/:response_id`, `GET /v1/videos/:task_id` and its content, and artifact listing and content. The task row remains for billing and the task log. The submit presenter still receives the complete in-memory `task.data`, and `extractUsageOnComplete` runs before persistence, so settlement is unchanged. Because nothing is persisted, the submit reply of such a route, each of its SSE events and its in-memory `task.data` may be as large as `MAX_FILE_DOWNLOAD_MB` (default 64 MB) instead of 1 MiB, which lets a vendor answer with Base64 images; plugin state keeps its 1 MiB limit. An asynchronous result on a declaring route is retained and retrievable as usual and logs a warning. `query` routes reject the field. `openai_responses` and `openai_video` always retain their results because their deliverables are served through host artifact URLs; a plugin that wants previews with less storage should instead return a compact `taskData` from `parseSubmitResponse`. `openai_image` delivers its images inline in the create response, so an immediate terminal result on that protocol is discarded exactly as with `retainResult: false`, while a result completed by in-request polling keeps the snapshot the poller wrote. This is an additive apiVersion 1 extension: older hosts reject the unknown field. +`routes[].missing` is the optional string `"collect"` on a `dynamic` route. A query intent on that route renders the tasks this caller can retrieve and passes the other public ids, in request order and without duplicates, as `ctx.missedTaskIds` (an empty array when every id was found). A task owned by someone else, or one whose result was discarded, is missed the same way as an unknown id. On a path several plugins declare, the first plugin that can retrieve every id any of them can retrieve answers and reports the rest as missed. A batch split across those plugins, and a batch none of them can retrieve, are not found. Each plugin's own `/{key}` address still collects either batch. Without the field, any missing id fails the whole request with 404, which remains the behavior of every route that does not declare it. `submit` and `query` routes reject the field. + +`routes[].upstreamError` is the optional string `"passthrough"` on a `submit` route. A non-2xx upstream response is still a failed submission: the reservation is refunded and `parseSubmitResponse` does not run. The error presenter additionally receives `error.upstream` as `{status, body, retryAfter?}`, where `body` is the parsed JSON value when the response is JSON and the raw text otherwise, and `retryAfter` is the vendor's `Retry-After` header when it sent one. The presenter can answer with a reply wrapper using that status, body, and header. The field does not change which statuses the gateway retries: `400` and `408` still stop, while `401`, `403`, `429`, and `5xx` keep the usual retry budget so another channel can be tried. The response the client finally sees is whatever the presenter returns for the last attempt. Routes that omit the field keep the sanitized gateway error and do not receive `error.upstream`. `query` and `dynamic` routes reject the field. Both fields are additive apiVersion 1 extensions: older hosts reject the unknown field. + `routes[].models` optionally restricts a `submit` or `dynamic` route to a subset of `meta.models`. The host matches the canonical top-level `model` body field before any JS hook runs, counting a case variant or a channel alias of a listed model as listed; a missing, non-string, or unlisted model is rejected with 400 (plugin routes are exclusive paths, so there is no relay fallback). Declare it only when the model lives at the body top level — vendor formats that nest the model elsewhere should omit `models` and filter inside `decode`. `query` routes have no body and reject the field. Each `protocols` entry claims a host protocol. A protocol that defines modes must be claimed in object form with an explicit `supports`; the bare-string form is valid only for protocols without modes (`openai_video`, `openai_image`). `supports` declares which client request forms the plugin accepts on `openai_responses`: `"stream"` (`stream: true`), `"sync"` (neither flag; the call blocks until the terminal Response), `"background"` (`background: true`; the create returns a pending Response immediately). An unsupported request form is rejected with a 400 at channel selection, before any plugin hook runs and before billing. Retrieval (`GET /v1/responses/:response_id`) is not a mode: every created response is always retrievable. diff --git a/docs/plugin-api/v1.schema.json b/docs/plugin-api/v1.schema.json index e75936c5b3ec..e2e5d0f634dc 100644 --- a/docs/plugin-api/v1.schema.json +++ b/docs/plugin-api/v1.schema.json @@ -164,7 +164,7 @@ "maxBytes": {"type": "integer", "exclusiveMinimum": 0} } }, - "route": {"type": "object", "additionalProperties": false, "required": ["method", "path", "type", "render"], "properties": {"method": {"enum": ["GET", "POST", "PUT", "PATCH", "DELETE"]}, "path": {"type": "string", "pattern": "^/"}, "type": {"enum": ["submit", "query", "dynamic"]}, "action": {"type": "string"}, "taskIdParam": {"type": "string"}, "retainResult": {"type": "boolean"}, "decode": {"type": "string"}, "render": {"type": "string"}, "models": {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"type": "string", "minLength": 1}}}, "allOf": [{"if": {"properties": {"type": {"const": "query"}}}, "then": {"allOf": [{"not": {"required": ["decode"]}}, {"not": {"required": ["models"]}}, {"not": {"required": ["retainResult"]}}]}}, {"if": {"properties": {"type": {"enum": ["submit", "dynamic"]}}}, "then": {"required": ["decode"]}}]}, + "route": {"type": "object", "additionalProperties": false, "required": ["method", "path", "type", "render"], "properties": {"method": {"enum": ["GET", "POST", "PUT", "PATCH", "DELETE"]}, "path": {"type": "string", "pattern": "^/"}, "type": {"enum": ["submit", "query", "dynamic"]}, "action": {"type": "string"}, "taskIdParam": {"type": "string"}, "retainResult": {"type": "boolean"}, "missing": {"const": "collect"}, "upstreamError": {"const": "passthrough"}, "decode": {"type": "string"}, "render": {"type": "string"}, "models": {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"type": "string", "minLength": 1}}}, "allOf": [{"if": {"properties": {"type": {"const": "query"}}}, "then": {"allOf": [{"not": {"required": ["decode"]}}, {"not": {"required": ["models"]}}, {"not": {"required": ["retainResult"]}}, {"not": {"required": ["missing"]}}, {"not": {"required": ["upstreamError"]}}]}}, {"if": {"properties": {"type": {"const": "submit"}}}, "then": {"not": {"required": ["missing"]}}}, {"if": {"properties": {"type": {"const": "dynamic"}}}, "then": {"not": {"required": ["upstreamError"]}}}, {"if": {"properties": {"type": {"enum": ["submit", "dynamic"]}}}, "then": {"required": ["decode"]}}]}, "relayRoute": { "type": "object", "additionalProperties": false, diff --git a/dto/task.go b/dto/task.go index 6e9a6d4f2df5..8c46113f52b3 100644 --- a/dto/task.go +++ b/dto/task.go @@ -4,15 +4,25 @@ import ( "encoding/json" ) +// TaskUpstreamReply is a vendor's non-2xx submit response kept for a route +// that declares upstreamError passthrough. It is not part of the JSON body +// the gateway writes for every other task error. +type TaskUpstreamReply struct { + StatusCode int + Body []byte + RetryAfter string +} + type TaskError struct { // NoRetry prevents duplicate upstream work after a response has been accepted. - NoRetry bool `json:"-"` - Code string `json:"code"` - Message string `json:"message"` - Data any `json:"data"` - StatusCode int `json:"-"` - LocalError bool `json:"-"` - Error error `json:"-"` + NoRetry bool `json:"-"` + Code string `json:"code"` + Message string `json:"message"` + Data any `json:"data"` + StatusCode int `json:"-"` + LocalError bool `json:"-"` + Error error `json:"-"` + UpstreamReply *TaskUpstreamReply `json:"-"` } type TaskData interface { diff --git a/middleware/task_plugin.go b/middleware/task_plugin.go index ebecf44886c3..9ec9671b8137 100644 --- a/middleware/task_plugin.go +++ b/middleware/task_plugin.go @@ -213,7 +213,7 @@ func PrepareTaskPluginRoute() gin.HandlerFunc { failures []string ) rejectedPlugins := make(map[string][]string) - for _, candidate := range eligible { + for candidateIndex, candidate := range eligible { candidateContext := requestContext candidateContext.Params = pluginruntime.RouteParams(c.Params, candidate.Route) var ( @@ -258,12 +258,31 @@ func PrepareTaskPluginRoute() gin.HandlerFunc { renderTaskPluginQuery(c, pinned, candidateContext, intent.taskIDs, candidate.Route.Render, true) return } - owned, lookupErr := taskPluginOwnsTasks(c, candidate.Plugin.Meta, intent.taskIDs) + retrievable, lookupErr := taskPluginRetrievableIDs(c, candidate.Plugin.Meta, intent.taskIDs) if lookupErr != nil { abortTaskPluginRouteError(c, http.StatusInternalServerError) return } - if owned { + ownsQuery := true + for _, taskID := range intent.taskIDs { + if _, found := retrievable[taskID]; !found { + ownsQuery = false + break + } + } + // A collect route may answer when it can retrieve at least one + // id and no other candidate can retrieve the rest. An unknown + // id does not block it. A candidate that can retrieve nothing + // does not answer a shared path. + if !ownsQuery && candidate.Route.Missing == pluginruntime.RouteMissingCollect && len(retrievable) > 0 { + elsewhere, elsewhereErr := taskPluginSharedQueryOwnedElsewhere(c, eligible, candidateIndex, intent.taskIDs, retrievable) + if elsewhereErr != nil { + abortTaskPluginRouteError(c, http.StatusInternalServerError) + return + } + ownsQuery = !elsewhere + } + if ownsQuery { pinned.Plugin, pinned.Route = candidate.Plugin, candidate.Route c.Set(pluginruntime.ContextKeyPinnedRoute, pinned) c.Set(pluginruntime.ContextKeyPinnedPlugin, pluginruntime.PinnedPlugin{Generation: pinned.Generation, Plugin: candidate.Plugin}) @@ -499,19 +518,55 @@ func renderTaskPluginRouteQuery(c *gin.Context, pinned pluginruntime.PinnedRoute renderTaskPluginQuery(c, pinned, requestContext, []string{taskIDs[ownerIndex]}, owner.Route.Render, false) } -// taskPluginOwnsTasks reports whether every task id names a retrievable task -// of the caller on one of the plugin's platforms. -func taskPluginOwnsTasks(c *gin.Context, meta pluginruntime.Meta, taskIDs []string) (bool, error) { +// taskPluginRetrievableIDs returns the requested ids that name a retrievable +// task of the caller on one of the plugin's platforms. +func taskPluginRetrievableIDs(c *gin.Context, meta pluginruntime.Meta, taskIDs []string) (map[string]struct{}, error) { tasks, err := model.GetByTaskIdsForPlatforms(common.GetContextKeyInt(c, constant.ContextKeyUserId), taskPluginLegacyPlatforms(meta), taskIDs) if err != nil { - return false, err + return nil, err } + retrievable := make(map[string]struct{}, len(tasks)) + for _, task := range tasks { + if task.ResultRetrievable() { + retrievable[task.TaskID] = struct{}{} + } + } + return retrievable, nil +} + +// taskPluginSharedQueryOwnedElsewhere reports whether another candidate on the +// same path can retrieve a requested id that this plugin cannot. Those ids +// still decide which plugin owns the batch; missing:collect must not report +// them as missed. +func taskPluginSharedQueryOwnedElsewhere(c *gin.Context, candidates []pluginruntime.RouteBinding, self int, taskIDs []string, retrievable map[string]struct{}) (bool, error) { + missing := make([]string, 0, len(taskIDs)) + seen := make(map[string]struct{}, len(taskIDs)) for _, taskID := range taskIDs { - if !slices.ContainsFunc(tasks, func(task *model.Task) bool { return task.TaskID == taskID && task.ResultRetrievable() }) { - return false, nil + if _, found := retrievable[taskID]; found { + continue + } + if _, found := seen[taskID]; found { + continue + } + seen[taskID] = struct{}{} + missing = append(missing, taskID) + } + if len(missing) == 0 { + return false, nil + } + for index, other := range candidates { + if index == self { + continue + } + found, err := taskPluginRetrievableIDs(c, other.Plugin.Meta, missing) + if err != nil { + return false, err + } + if len(found) > 0 { + return true, nil } } - return true, nil + return false, nil } // RouteTaskPluginEndpoint selects between ordinary relay and plugin channels @@ -1478,20 +1533,30 @@ func renderTaskPluginQuery( for _, task := range tasks { tasksByID[task.TaskID] = task } + collectMissing := multiple && pinned.Route.Missing == pluginruntime.RouteMissingCollect views := make([]dto.TaskView, 0, len(taskIDs)) + var missed []string + seenMissed := map[string]struct{}{} for _, taskID := range taskIDs { task := tasksByID[taskID] if task == nil || !task.ResultRetrievable() { - logger.LogDebug( - c, - "task_plugin subsystem=query event=lookup_failed generation=%d plugin=%q reason=task_not_found requested=%d found=%d", - generation, - pinned.Plugin.Meta.Key, - len(taskIDs), - len(tasks), - ) - abortTaskPluginRouteError(c, http.StatusNotFound) - return + if !collectMissing { + logger.LogDebug( + c, + "task_plugin subsystem=query event=lookup_failed generation=%d plugin=%q reason=task_not_found requested=%d found=%d", + generation, + pinned.Plugin.Meta.Key, + len(taskIDs), + len(tasks), + ) + abortTaskPluginRouteError(c, http.StatusNotFound) + return + } + if _, seen := seenMissed[taskID]; !seen { + seenMissed[taskID] = struct{}{} + missed = append(missed, taskID) + } + continue } view, viewErr := service.BuildTaskPluginView(task) if viewErr != nil { @@ -1523,6 +1588,12 @@ func renderTaskPluginQuery( } } presenterContext["artifacts"] = artifacts + if collectMissing { + if missed == nil { + missed = []string{} + } + presenterContext["missedTaskIds"] = missed + } renderStarted := time.Now() result, err := pinned.Plugin.Engine.CallPath(c.Request.Context(), "native", []string{renderer}, presenterContext, pluginruntime.RawJSON(encoded)) if err != nil { @@ -1629,6 +1700,23 @@ func WriteNativeReply(c *gin.Context, status int, value any) error { return nil } +// taskUpstreamErrorValue is the vendor response a passthrough submit route's +// error presenter reads. A JSON body stays a value; anything else stays text. +func taskUpstreamErrorValue(reply *dto.TaskUpstreamReply) map[string]any { + // JSON, including null, is the parsed value. Anything else, including an + // empty or whitespace-only body, stays the original text. + body := any(string(reply.Body)) + var decoded any + if common.Unmarshal(reply.Body, &decoded) == nil { + body = decoded + } + value := map[string]any{"status": reply.StatusCode, "body": body} + if reply.RetryAfter != "" { + value["retryAfter"] = reply.RetryAfter + } + return value +} + // RespondTaskPluginError gives a pinned plugin a sanitized error DTO and writes // its native error body with the host's status, unless the body is a reply // wrapper that answers with the vendor's own status. @@ -1652,13 +1740,17 @@ func RespondTaskPluginError(c *gin.Context, taskErr *dto.TaskError) bool { requestValue, exists := c.Get(pluginruntime.ContextKeyRouteRequest) requestContext, ok := requestValue.(pluginruntime.RouteRequestContext) if err == nil && hasRenderer && exists && ok { - body, callErr := pinned.Plugin.Engine.CallMember(c.Request.Context(), "native", "error", requestContext.JSValue(), map[string]any{ + errorValue := map[string]any{ "code": sanitized.Code, "message": sanitized.Message, "httpStatus": sanitized.HTTPStatus, "retryable": sanitized.Retryable, "requestId": requestID, - }) + } + if pinned.Route.UpstreamError == pluginruntime.RouteUpstreamErrorPassthrough && taskErr.UpstreamReply != nil { + errorValue["upstream"] = taskUpstreamErrorValue(taskErr.UpstreamReply) + } + body, callErr := pinned.Plugin.Engine.CallMember(c.Request.Context(), "native", "error", requestContext.JSValue(), errorValue) if callErr == nil { callErr = WriteNativeReply(c, sanitized.HTTPStatus, body) } diff --git a/middleware/task_plugin_test.go b/middleware/task_plugin_test.go index a6b3f39d738e..3b04ac228b36 100644 --- a/middleware/task_plugin_test.go +++ b/middleware/task_plugin_test.go @@ -1336,6 +1336,165 @@ export function parseTaskResult() { return {status: "SUCCESS"}; } assert.NotContains(t, recorder.Body.String(), "secret") } +func TestPrepareTaskPluginDynamicQueryCollectsMissingIDs(t *testing.T) { + setupTaskPluginRouteDB(t) + source := func(missing string) string { + return ` +export const meta = { + apiVersion: 1, key: "route-query-miss-test", name: "Query", version: "1.0.0", + author: {name: "Test"}, + models: ["query-model"], fetchMode: "per_task", + routes: [{method: "POST", path: "/vendor/query", type: "dynamic", decode: "decodeQuery", render: "renderQuery"` + missing + `}], +}; +export const native = { + decodeQuery: function() { return {kind: "query", taskIds: ["task-b", "missing-task", "missing-task", "foreign-task", "discarded-task"]}; }, + renderQuery: function(ctx, tasks) { + return {ids: tasks.map(function(task) { return task.task_id; }), missed: ctx.missedTaskIds || null}; + }, +}; +export function buildSubmitRequest() { return {url: "https://example.com"}; } +export function parseSubmitResponse() { return {taskId: "one"}; } +export function buildQueryRequest() { return {url: "https://example.com"}; } +export function parseTaskResult() { return {status: "SUCCESS"}; } +` + } + insertTaskPluginRouteTask(t, &model.Task{ + TaskID: "task-b", UserId: 7, Platform: constant.TaskPlatform("route-query-miss-test"), + Status: model.TaskStatusSuccess, + }) + insertTaskPluginRouteTask(t, &model.Task{ + TaskID: "foreign-task", UserId: 8, Platform: constant.TaskPlatform("route-query-miss-test"), + }) + insertTaskPluginRouteTask(t, &model.Task{ + TaskID: "discarded-task", UserId: 7, Platform: constant.TaskPlatform("route-query-miss-test"), + Status: model.TaskStatusSuccess, PrivateData: model.TaskPrivateData{ResultDiscarded: true}, + }) + + serve := func(plugin *jsplugin.LoadedPlugin) *httptest.ResponseRecorder { + router := gin.New() + router.POST("/vendor/query", + pinTaskPluginRoute(plugin, 0), + func(c *gin.Context) { + c.Set("id", 7) + c.Next() + }, + PrepareTaskPluginRoute(), + ) + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/vendor/query", strings.NewReader(`{}`)) + request.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, request) + return recorder + } + + plain := compileTaskRoutePlugin(t, source("")) + missingAll := serve(plain) + assert.Equal(t, http.StatusNotFound, missingAll.Code) + + collected := serve(compileTaskRoutePlugin(t, source(`, missing: "collect"`))) + assert.Equal(t, http.StatusOK, collected.Code) + assert.JSONEq(t, `{"ids":["task-b"],"missed":["missing-task","foreign-task","discarded-task"]}`, collected.Body.String()) +} + +func TestRespondTaskPluginErrorPassesUpstreamReply(t *testing.T) { + plugin := compileTaskRoutePlugin(t, ` +export const meta = {apiVersion:1,key:"upstream-error",name:"Upstream",version:"1.0.0",author:{name:"Test"},models:["model"],fetchMode:"per_task",routes:[{method:"POST",path:"/vendor/submit",type:"submit",decode:"decode",render:"created",upstreamError:"passthrough"}]}; +export const native = { + decode: function() { return {kind:"submit", model:"model", requestBody:{}}; }, + created: function() { return {}; }, + error: function(ctx, error) { + if (error.upstream) { + const reply = {__status: error.upstream.status, __body: error.upstream.body}; + if (error.upstream.retryAfter) reply.__headers = {"Retry-After": error.upstream.retryAfter}; + return reply; + } + return {leaked: false, code: error.httpStatus, message: error.message}; + } +}; +export function buildSubmitRequest(){return {}} export function parseSubmitResponse(){return {taskId:"one"}} export function buildQueryRequest(){return {}} export function parseTaskResult(){return {status:"SUCCESS"}} +`) + taskErr := &dto.TaskError{ + Code: "fail_to_fetch_task", + Message: `{"code":2000,"status":"error","message":"slow down"}`, + StatusCode: http.StatusTooManyRequests, + UpstreamReply: &dto.TaskUpstreamReply{ + StatusCode: http.StatusTooManyRequests, + Body: []byte(`{"code":2000,"status":"error","message":"slow down"}`), + RetryAfter: "5", + }, + } + call := func(passthrough bool) *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/vendor/submit", nil) + route := plugin.Meta.Routes[0] + if !passthrough { + route.UpstreamError = "" + } + c.Set(jsplugin.ContextKeyPinnedRoute, jsplugin.PinnedRoute{Plugin: plugin, Route: route}) + c.Set(jsplugin.ContextKeyRouteRequest, jsplugin.RouteRequestContext{Method: http.MethodPost, Path: "/vendor/submit"}) + require.True(t, RespondTaskPluginError(c, taskErr)) + return recorder + } + + passed := call(true) + assert.Equal(t, http.StatusTooManyRequests, passed.Code) + assert.Equal(t, "5", passed.Header().Get("Retry-After")) + assert.JSONEq(t, `{"code":2000,"status":"error","message":"slow down"}`, passed.Body.String()) + + kept := call(false) + assert.Equal(t, http.StatusTooManyRequests, kept.Code) + assert.Empty(t, kept.Header().Get("Retry-After")) + assert.JSONEq(t, `{"leaked":false,"code":429,"message":"{\"code\":2000,\"status\":\"error\",\"message\":\"slow down\"}"}`, kept.Body.String()) +} + +func TestRespondTaskPluginErrorPreservesUpstreamBody(t *testing.T) { + plugin := compileTaskRoutePlugin(t, ` +export const meta = {apiVersion:1,key:"upstream-body",name:"Upstream",version:"1.0.0",author:{name:"Test"},models:["model"],fetchMode:"per_task",routes:[{method:"POST",path:"/vendor/submit",type:"submit",decode:"decode",render:"created",upstreamError:"passthrough"}]}; +export const native = { + decode: function() { return {kind:"submit", model:"model"}; }, + created: function() { return {}; }, + error: function(ctx, error) { return {__status: error.upstream.status, __body: error.upstream.body}; } +}; +export function buildSubmitRequest(){return {}} export function parseSubmitResponse(){return {taskId:"one"}} export function buildQueryRequest(){return {}} export function parseTaskResult(){return {status:"SUCCESS"}} +`) + for _, testCase := range []struct { + name string + body []byte + want string + }{ + {name: "json object", body: []byte(`{"ok":true}`), want: `{"ok":true}`}, + {name: "json null", body: []byte(`null`), want: `null`}, + {name: "json false", body: []byte(`false`), want: `false`}, + {name: "json zero", body: []byte(`0`), want: `0`}, + {name: "json empty string", body: []byte(`""`), want: `""`}, + {name: "json empty array", body: []byte(`[]`), want: `[]`}, + {name: "json with surrounding whitespace", body: []byte(" {\"ok\":true}\n"), want: `{"ok":true}`}, + {name: "empty", body: nil, want: `""`}, + {name: "whitespace", body: []byte(" \n\t"), want: "\" \\n\\t\""}, + {name: "plain text", body: []byte("slow down"), want: `"slow down"`}, + } { + t.Run(testCase.name, func(t *testing.T) { + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + context.Request = httptest.NewRequest(http.MethodPost, "/vendor/submit", nil) + context.Set(jsplugin.ContextKeyPinnedRoute, jsplugin.PinnedRoute{Plugin: plugin, Route: plugin.Meta.Routes[0]}) + context.Set(jsplugin.ContextKeyRouteRequest, jsplugin.RouteRequestContext{Method: http.MethodPost, Path: "/vendor/submit"}) + require.True(t, RespondTaskPluginError(context, &dto.TaskError{ + Code: "invalid_request", + Message: "Invalid request", + StatusCode: http.StatusBadRequest, + UpstreamReply: &dto.TaskUpstreamReply{ + StatusCode: http.StatusBadRequest, + Body: testCase.body, + }, + })) + assert.Equal(t, http.StatusBadRequest, recorder.Code) + assert.JSONEq(t, testCase.want, recorder.Body.String()) + }) + } +} + func TestPrepareTaskPluginDynamicDecoderRejectsRendererField(t *testing.T) { plugin := compileTaskRoutePlugin(t, ` export const meta = {apiVersion:1,key:"dynamic-renderer",name:"Dynamic",version:"1.0.0",author:{name:"Test"},models:["model"],fetchMode:"per_task",routes:[{method:"POST",path:"/vendor/query",type:"dynamic",decode:"decode",render:"show"}]}; @@ -2561,6 +2720,64 @@ func TestPrepareTaskPluginRouteAnswersSharedQueriesByTaskOwner(t *testing.T) { } } +// missing:collect on a shared dynamic path reports ids no candidate can +// retrieve, and still refuses a batch whose tasks belong to different plugins. +func TestPrepareTaskPluginSharedDynamicQueryCollectsUnknownIDs(t *testing.T) { + setupTaskPluginRouteDB(t) + route := func(collect bool) string { + missing := "" + if collect { + missing = `, missing: "collect"` + } + return `[{method: "POST", path: "/probe/v1/fetch", type: "dynamic", decode: "fetchJobs", render: "renderFetch"` + missing + `}]` + } + extra := func(key string) string { + return fmt.Sprintf(`renderFetch(ctx, tasks) { return {by: %q, tasks: tasks.map(function(task) { return task.task_id; }), missed: ctx.missedTaskIds || null}; },`, key) + } + plugin := func(key string, collect bool) *jsplugin.LoadedPlugin { + return compileTaskRoutePlugin(t, sharedRouteTestPluginSource(key, `["probe-model"]`, route(collect), extra(key))) + } + insertTaskPluginRouteTask(t, &model.Task{TaskID: "task_alpha", UserId: 7, Platform: constant.TaskPlatform("share-alpha"), Status: model.TaskStatusSuccess}) + insertTaskPluginRouteTask(t, &model.Task{TaskID: "task_beta", UserId: 7, Platform: constant.TaskPlatform("share-beta"), Status: model.TaskStatusSuccess}) + insertTaskPluginRouteTask(t, &model.Task{TaskID: "task_foreign", UserId: 8, Platform: constant.TaskPlatform("share-alpha"), Status: model.TaskStatusSuccess}) + insertTaskPluginRouteTask(t, &model.Task{ + TaskID: "task_discarded", UserId: 7, Platform: constant.TaskPlatform("share-alpha"), + Status: model.TaskStatusSuccess, PrivateData: model.TaskPrivateData{ResultDiscarded: true}, + }) + both := sharedTaskPluginRouteRouter(t, plugin("share-alpha", true), plugin("share-beta", true)) + alphaOnly := sharedTaskPluginRouteRouter(t, plugin("share-alpha", true), plugin("share-beta", false)) + neither := sharedTaskPluginRouteRouter(t, plugin("share-alpha", false), plugin("share-beta", false)) + notFound := `{"code":"task_not_found","message":"Task not found","data":null}` + + for _, testCase := range []struct { + name, body, want string + router http.Handler + status int + }{ + {name: "unknown id is missed", router: both, status: http.StatusOK, body: `{"ids":["task_alpha","missing-task","missing-task"]}`, + want: `{"by":"share-alpha","tasks":["task_alpha"],"missed":["missing-task"]}`}, + {name: "foreign and discarded ids are missed", router: both, status: http.StatusOK, body: `{"ids":["task_foreign","task_alpha","task_discarded"]}`, + want: `{"by":"share-alpha","tasks":["task_alpha"],"missed":["task_foreign","task_discarded"]}`}, + {name: "later plugin owns the known id", router: both, status: http.StatusOK, body: `{"ids":["missing-task","task_beta"]}`, + want: `{"by":"share-beta","tasks":["task_beta"],"missed":["missing-task"]}`}, + {name: "split batch stays not found", router: both, status: http.StatusNotFound, body: `{"ids":["task_alpha","task_beta"]}`, want: notFound}, + {name: "nothing retrievable stays not found", router: both, status: http.StatusNotFound, body: `{"ids":["missing-a","missing-b"]}`, want: notFound}, + {name: "collect does not take another plugin's task", router: alphaOnly, status: http.StatusNotFound, body: `{"ids":["task_alpha","task_beta"]}`, want: notFound}, + {name: "without collect a missing id is not found", router: neither, status: http.StatusNotFound, body: `{"ids":["task_alpha","missing-task"]}`, want: notFound}, + {name: "without collect the owner still answers", router: neither, status: http.StatusOK, body: `{"ids":["task_beta"]}`, + want: `{"by":"share-beta","tasks":["task_beta"],"missed":null}`}, + } { + t.Run(testCase.name, func(t *testing.T) { + recorder := performSharedRouteRequest(testCase.router, http.MethodPost, "/probe/v1/fetch", testCase.body) + assert.Equal(t, testCase.status, recorder.Code, recorder.Body.String()) + assert.JSONEq(t, testCase.want, recorder.Body.String()) + }) + } + ownedPath := performSharedRouteRequest(both, http.MethodPost, "/share-alpha/probe/v1/fetch", `{"ids":["task_alpha","task_beta","missing-task"]}`) + assert.Equal(t, http.StatusOK, ownedPath.Code, ownedPath.Body.String()) + assert.JSONEq(t, `{"by":"share-alpha","tasks":["task_alpha"],"missed":["task_beta","missing-task"]}`, ownedPath.Body.String()) +} + // A query route whose taskIdParam is not a path parameter reads the task id // from the query string, as MiniMax's v1 query does. func TestPrepareTaskPluginRouteReadsQueryStringTaskID(t *testing.T) { diff --git a/pkg/jsplugin/registry.go b/pkg/jsplugin/registry.go index e8608f7b71e4..75d58ca2f2c4 100644 --- a/pkg/jsplugin/registry.go +++ b/pkg/jsplugin/registry.go @@ -2279,7 +2279,7 @@ func decodeRoutes(value any) ([]Route, error) { } for key := range object { switch key { - case "method", "path", "type", "action", "decode", "render", "taskIdParam", "models", "retainResult": + case "method", "path", "type", "action", "decode", "render", "taskIdParam", "models", "retainResult", "missing", "upstreamError": default: return nil, fmt.Errorf("plugin meta route %d has unknown field %q", index, key) } @@ -2324,6 +2324,20 @@ func decodeRoutes(value any) ([]Route, error) { } route.RetainResult = &retain } + if value, exists := object["missing"]; exists { + text, ok := value.(string) + if !ok || text != RouteMissingCollect { + return nil, fmt.Errorf("plugin meta route %d missing must be %q", index, RouteMissingCollect) + } + route.Missing = text + } + if value, exists := object["upstreamError"]; exists { + text, ok := value.(string) + if !ok || text != RouteUpstreamErrorPassthrough { + return nil, fmt.Errorf("plugin meta route %d upstreamError must be %q", index, RouteUpstreamErrorPassthrough) + } + route.UpstreamError = text + } routes = append(routes, route) } return routes, nil diff --git a/pkg/jsplugin/routing.go b/pkg/jsplugin/routing.go index 1370cb5f1c1c..936e6d7556aa 100644 --- a/pkg/jsplugin/routing.go +++ b/pkg/jsplugin/routing.go @@ -21,6 +21,13 @@ const ( RouteTypeSubmit RouteType = "submit" RouteTypeQuery RouteType = "query" RouteTypeDynamic RouteType = "dynamic" + + // RouteMissingCollect tells a dynamic query to render the tasks it found + // and report the public ids it did not, instead of failing the whole request. + RouteMissingCollect = "collect" + // RouteUpstreamErrorPassthrough tells a submit route to hand the vendor's + // non-2xx status, body, and Retry-After to the error presenter. + RouteUpstreamErrorPassthrough = "passthrough" ) type Route struct { @@ -40,6 +47,15 @@ type Route struct { // canonical top-level "model" body field before any JS hook runs; empty // means unrestricted. Must be a subset of meta.models. Models []string `json:"models,omitempty"` + // Missing is "collect" on a dynamic route whose query renderer should + // receive the public ids this caller cannot retrieve. Empty fails the + // whole request when any id is missing, which is what every existing + // batch query does. + Missing string `json:"missing,omitempty"` + // UpstreamError is "passthrough" on a submit route whose error presenter + // receives the vendor's non-2xx response. Empty keeps the sanitized + // gateway error. + UpstreamError string `json:"upstreamError,omitempty"` } // ProtocolClaim is one entry of meta.protocols. Models narrows the protocol's @@ -914,6 +930,12 @@ func validateRoute(route *Route) error { if route.Decode == "" || route.Render == "" || route.TaskIDParam != "" { return fmt.Errorf("submit route %s %s must declare decode and render and must not declare taskIdParam", route.Method, route.Path) } + if route.Missing != "" { + return fmt.Errorf("submit route %s %s must not declare missing", route.Method, route.Path) + } + if route.UpstreamError != "" && route.UpstreamError != RouteUpstreamErrorPassthrough { + return fmt.Errorf("submit route %s %s has unsupported upstreamError %q", route.Method, route.Path, route.UpstreamError) + } case RouteTypeQuery: if route.Decode != "" || strings.TrimSpace(route.Render) == "" { return fmt.Errorf("query route %s %s must declare render and must not declare decode", route.Method, route.Path) @@ -924,6 +946,9 @@ func validateRoute(route *Route) error { if route.RetainResult != nil { return fmt.Errorf("query route %s %s must not declare retainResult", route.Method, route.Path) } + if route.Missing != "" || route.UpstreamError != "" { + return fmt.Errorf("query route %s %s must not declare missing or upstreamError", route.Method, route.Path) + } if route.TaskIDParam == "" { route.TaskIDParam = "task_id" } @@ -934,6 +959,12 @@ func validateRoute(route *Route) error { if route.Decode == "" || route.Render == "" || route.TaskIDParam != "" { return fmt.Errorf("dynamic route %s %s must declare decode and render and must not declare taskIdParam", route.Method, route.Path) } + if route.UpstreamError != "" { + return fmt.Errorf("dynamic route %s %s must not declare upstreamError", route.Method, route.Path) + } + if route.Missing != "" && route.Missing != RouteMissingCollect { + return fmt.Errorf("dynamic route %s %s has unsupported missing %q", route.Method, route.Path, route.Missing) + } default: return fmt.Errorf("plugin route %s %s has unsupported type %q", route.Method, route.Path, route.Type) } @@ -985,6 +1016,17 @@ func (r Route) TaskIDInQuery() bool { return r.Type == RouteTypeQuery && !pathHasParameter(r.Path, r.TaskIDParam) } +// PinnedRoutePassesUpstreamError reports whether the request's submit route +// asked to hand the vendor's non-2xx response to its error presenter. +func PinnedRoutePassesUpstreamError(c *gin.Context) bool { + if c == nil { + return false + } + value, exists := c.Get(ContextKeyPinnedRoute) + pinned, ok := value.(PinnedRoute) + return exists && ok && pinned.Route.UpstreamError == RouteUpstreamErrorPassthrough +} + // routeHasOwnPrefix reports whether a declared route already lives under the // plugin's own address: its first segment is the key or a proper prefix of it. func routeHasOwnPrefix(key, routePath string) bool { diff --git a/pkg/jsplugin/routing_test.go b/pkg/jsplugin/routing_test.go index 58bed9392a33..f2f1663e225b 100644 --- a/pkg/jsplugin/routing_test.go +++ b/pkg/jsplugin/routing_test.go @@ -468,6 +468,69 @@ func TestRouteRetainResultDecodeAndValidation(t *testing.T) { } } +func TestRouteMissingAndUpstreamError(t *testing.T) { + routeExports := `export const native = { + decodeJob: function(ctx) { return {kind: "submit", model: "gpt-5.5", requestBody: ctx.body.value}; }, + decodeQuery: function() { return {kind: "query", taskIds: ["task_a"]}; }, + jobCreated: function(ctx, task) { return task; }, + jobStatus: function(ctx, task) { return task; } + };` + tests := []struct { + name string + metaFields string + missing string + upstream string + errContains string + }{ + { + name: "dynamic query collects missing ids", + metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "dynamic", decode: "decodeQuery", render: "jobStatus", missing: "collect"}],`, + missing: RouteMissingCollect, + }, + { + name: "submit route passes upstream errors", + metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", decode: "decodeJob", render: "jobCreated", upstreamError: "passthrough"}],`, + upstream: RouteUpstreamErrorPassthrough, + }, + { + name: "submit route rejects missing", + metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "submit", decode: "decodeJob", render: "jobCreated", missing: "collect"}],`, + errContains: "must not declare missing", + }, + { + name: "query route rejects both", + metaFields: `routes: [{method: "GET", path: "/v1/batch/:task_id", type: "query", render: "jobStatus", upstreamError: "passthrough"}],`, + errContains: "must not declare missing or upstreamError", + }, + { + name: "dynamic route rejects upstreamError", + metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "dynamic", decode: "decodeQuery", render: "jobStatus", upstreamError: "passthrough"}],`, + errContains: "must not declare upstreamError", + }, + { + name: "unknown missing value", + metaFields: `routes: [{method: "POST", path: "/v1/batch", type: "dynamic", decode: "decodeQuery", render: "jobStatus", missing: "ignore"}],`, + errContains: `missing must be "collect"`, + }, + } + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + plugin, err := CompilePlugin( + routingTestPluginSource("route-opt-in", 0, `["gpt-5.5"]`, testCase.metaFields, routeExports), + Options{}, + ) + if testCase.errContains != "" { + require.ErrorContains(t, err, testCase.errContains) + return + } + require.NoError(t, err) + require.Len(t, plugin.Meta.Routes, 1) + assert.Equal(t, testCase.missing, plugin.Meta.Routes[0].Missing) + assert.Equal(t, testCase.upstream, plugin.Meta.Routes[0].UpstreamError) + }) + } +} + func TestRouteRequestContextKeepsFormAndMultipartValuesAcrossDecoderWrites(t *testing.T) { plugin, err := CompilePlugin(routingTestPluginSource("route-request-writes", 0, `["gpt-5.5"]`, "", ` export function decodeJob(ctx) { diff --git a/relay/relay_task.go b/relay/relay_task.go index 513a832e6100..36dbf9e3f244 100644 --- a/relay/relay_task.go +++ b/relay/relay_task.go @@ -391,7 +391,17 @@ func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (*TaskSubmitRe // or 202 Accepted, and parseSubmitResponse receives the exact status code. if resp.StatusCode/100 != 2 { responseBody, _ := io.ReadAll(resp.Body) - return nil, service.TaskErrorWrapper(fmt.Errorf("%s", string(responseBody)), "fail_to_fetch_task", resp.StatusCode, common.UpstreamAddresses(c)...) + taskErr := service.TaskErrorWrapper(fmt.Errorf("%s", string(responseBody)), "fail_to_fetch_task", resp.StatusCode, common.UpstreamAddresses(c)...) + // A route that opts in keeps the vendor response for its error + // presenter. Every other submit route still gets the sanitized error. + if jsplugin.PinnedRoutePassesUpstreamError(c) { + taskErr.UpstreamReply = &dto.TaskUpstreamReply{ + StatusCode: resp.StatusCode, + Body: responseBody, + RetryAfter: strings.TrimSpace(resp.Header.Get("Retry-After")), + } + } + return nil, taskErr } // 10. Parse only. The controller presents the response after the durable diff --git a/relay/relay_task_test.go b/relay/relay_task_test.go index 236990f32e82..a7da456bd355 100644 --- a/relay/relay_task_test.go +++ b/relay/relay_task_test.go @@ -777,6 +777,7 @@ export function parseTaskResult() { return {status:"SUCCESS"}; } assert.Equal(t, tc.wantCode, taskErr.Code) assert.Equal(t, tc.status, taskErr.StatusCode) assert.Contains(t, taskErr.Message, "upstream body") + assert.Nil(t, taskErr.UpstreamReply) assert.Nil(t, result) return } @@ -788,6 +789,48 @@ export function parseTaskResult() { return {status:"SUCCESS"}; } } } +func TestRelayTaskSubmitPassthroughKeepsUpstreamReply(t *testing.T) { + service.InitHttpClient() + const source = ` +export const meta = {apiVersion:1,key:"status-echo",name:"Status Echo",version:"1.0.0",author:{name:"Test"},models:["declared-model"],fetchMode:"per_task"}; +export function buildSubmitRequest(ctx) { return {url: ctx.baseUrl+"/submit", method:"POST", body:{model: ctx.model}, action:"text_to_video"}; } +export function parseSubmitResponse(ctx, response) { return {taskId: response.body.id}; } +export function buildQueryRequest(ctx) { return {url: ctx.baseUrl+"/query"}; } +export function parseTaskResult() { return {status:"SUCCESS"}; } +` + saveBillingConfig(t) + require.NoError(t, config.GlobalConfig.LoadFromDB(map[string]string{ + "billing_setting.billing_mode": `{"declared-model":"tiered_expr"}`, + "billing_setting.billing_expr": `{"declared-model":"tier(\"flat\", 3)"}`, + })) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Retry-After", "5") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"code":2000,"status":"error","message":"slow down"}`)) + })) + defer server.Close() + + c, info := newTaskSubmitContext(t, "declared-model", "") + common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, server.URL) + c.Set("group", "default") + info.UserGroup, info.UsingGroup = "default", "default" + info.OriginModelName = "declared-model" + info.Billing = &imageReservation{limit: 1 << 30} + pinMappingOrderPlugin(t, c, source) + c.Set(pluginruntime.ContextKeyPinnedRoute, pluginruntime.PinnedRoute{ + Route: pluginruntime.Route{Type: pluginruntime.RouteTypeSubmit, UpstreamError: pluginruntime.RouteUpstreamErrorPassthrough}, + }) + + result, taskErr := RelayTaskSubmit(c, info) + require.NotNil(t, taskErr) + assert.Nil(t, result) + assert.Equal(t, http.StatusTooManyRequests, taskErr.StatusCode) + require.NotNil(t, taskErr.UpstreamReply) + assert.Equal(t, "5", taskErr.UpstreamReply.RetryAfter) + assert.JSONEq(t, `{"code":2000,"status":"error","message":"slow down"}`, string(taskErr.UpstreamReply.Body)) +} + // A retry prices the plugin it lands on from scratch and holds that price // before the upstream sees the request. Plugin A fails upstream on the first // attempt; the retry runs on plugin B, pinned the way