Repository navigation
task_relay_info - #1656
task_relay_info#1656
Conversation
WalkthroughRefactors the relay flow to use a single RelayInfo object end-to-end. Updates controller handler, task initialization, relay submission pipeline, channel adaptor interfaces, and task adaptors to accept RelayInfo. Adjusts RelayInfo/TaskRelayInfo relationship, removes GenTaskRelayInfo, and aligns API request handling to pass RelayInfo directly. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Client
participant C as Controller (RelayTask)
participant RC as relaycommon
participant R as RelayTaskSubmit
participant A as Channel Adaptor
participant AR as API Request
participant S as Upstream Service
participant DB as Task/Quota Store
Client->>C: HTTP request
C->>RC: GenRelayInfo(c)
RC-->>C: RelayInfo or error
alt error
C-->>Client: Error response
else RelayMode = Fetch
C->>R: RelayTaskFetch(..., relayInfo.RelayMode)
R-->>Client: Fetch response
else RelayMode = Submit
C->>R: RelayTaskSubmit(c, RelayInfo)
R->>R: info.InitChannelMeta(c)
R->>A: Init(info)
A->>A: ValidateRequestAndSetAction(c, info)
A-->>R: ok or task error
R->>A: BuildRequestBody(c, info)
R->>AR: DoTaskApiRequest(A, c, info, body)
AR->>A: BuildRequestURL(info)
AR->>A: BuildRequestHeader(c, req, info)
AR->>A: DoRequest(c, info, body)
A->>S: HTTP request
S-->>A: HTTP response
A-->>R: DoResponse(..., info) → taskID, data
R->>DB: Create task, consume quota, record logs
DB-->>R: ack
R-->>Client: Submit response (task info)
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (9)
model/task.go (1)
80-90: Prevent nil-pointer deref when ChannelMeta is not initialized
relayInfo.ChannelIdis accessed via an embedded pointer*ChannelMeta. IfrelayInfo.ChannelMetais nil, this will panic. Make it nil-safe.Apply this diff:
func InitTask(platform constant.TaskPlatform, relayInfo *commonRelay.RelayInfo) *Task { - t := &Task{ - UserId: relayInfo.UserId, - SubmitTime: time.Now().Unix(), - Status: TaskStatusNotStart, - Progress: "0%", - ChannelId: relayInfo.ChannelId, - Platform: platform, - } + channelID := 0 + if relayInfo.ChannelMeta != nil { + channelID = relayInfo.ChannelId + } + t := &Task{ + UserId: relayInfo.UserId, + SubmitTime: time.Now().Unix(), + Status: TaskStatusNotStart, + Progress: "0%", + ChannelId: channelID, + Platform: platform, + } return t }relay/channel/api_request.go (1)
280-303: Ensure replayable request bodies and apply channelHeadersOverridein DoTaskApiRequestDoTaskApiRequest currently:
- Unconditionally sets
req.GetBodyto return the sameio.Reader, causing retries and redirects to immediately hit EOF (all TaskAdaptors returnbytes.Reader, which does implementio.ReadSeeker).- Omits
info.HeadersOverrideentirely, unlike DoApiRequest/DoFormRequest, so caller-specified header overrides have no effect.Please apply the following mandatory changes in
relay/channel/api_request.gowithinfunc DoTaskApiRequest(around lines 280–303):- // existing unconditional GetBody - req.GetBody = func() (io.ReadCloser, error) { - return io.NopCloser(requestBody), nil - } + // Only make the body replayable when it supports seeking + if rs, ok := requestBody.(io.ReadSeeker); ok { + req.GetBody = func() (io.ReadCloser, error) { + _, _ = rs.Seek(0, io.SeekStart) + return io.NopCloser(rs), nil + } + } + // Apply channel HeadersOverride before building remaining headers + for key, val := range info.HeadersOverride { + strVal, ok := val.(string) + if !ok { + return nil, types.NewError(nil, types.ErrorCodeChannelHeaderOverrideInvalid) + } + req.Header.Set(key, strVal) + }These changes guarantee that request bodies from your TaskAdaptors (e.g.
bytes.NewReader) can be replayed on redirects/retries and that anyinfo.HeadersOverrideentries are consistently honored.relay/relay_task.go (1)
77-103: Ensure channel meta (ApiKey, Type, Overrides) is reinitialized when switching origin task channelThe current code in
relay/relay_task.go(around lines 77–103) updates only plain context keys and the request header whenoriginTask.ChannelId != info.ChannelId, but leavesinfo.ApiKey(and other channel metadata) pointing to the old channel. All task adaptors reconstruct their Authorization header frominfo.ApiKey(not fromc.Request.Header), so this can cause downstream requests to use stale credentials.Evidence from adaptors under
relay/channel/task:
- Many adaptors do
req.Header.Set("Authorization", "..."+info.ApiKey)(vidu, suno) or useinfo.ApiKeyfor token generation (jimeng, kling).- No adaptors read
c.Request.Headerdirectly for credentials.Pinpoint:
- File:
relay/relay_task.go, lines ~77–103Please apply the following mandatory refactor inside the channel-switch block to populate standard context keys and rebuild
info.ChannelMeta:- c.Set("base_url", channel.GetBaseURL()) - c.Set("channel_id", originTask.ChannelId) - c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", channel.Key)) - - info.ChannelBaseUrl = channel.GetBaseURL() - info.ChannelId = originTask.ChannelId + // Populate standard context keys consumed by InitChannelMeta + c.Set(constant.ContextKeyChannelBaseUrl, channel.GetBaseURL()) + c.Set(constant.ContextKeyChannelId, originTask.ChannelId) + c.Set(constant.ContextKeyChannelType, channel.Type) + c.Set(constant.ContextKeyChannelKey, channel.Key) + // Reinitialize ChannelMeta (ApiKey, ApiType, overrides) from context + info.InitChannelMeta(c) + // Keep request header in sync for any code paths forwarding c.Request + c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", channel.Key))This change is critical to prevent authorization failures when the origin task’s channel differs from the initial one.
relay/channel/task/jimeng/adaptor.go (2)
178-186: req_key mismatch between submit and fetch will cause retrieval failuresSubmission defaults to ReqKey "jimeng_vgfm_i2v_l20" (image-to-video) while FetchTask hardcodes "jimeng_vgfm_t2v_l20" (text-to-video). If upstream requires a matching req_key, fetches will fail intermittently. Align fetch with the actual submit req_key and allow overriding via body.
Apply the following focused changes:
--- a/relay/channel/task/jimeng/adaptor.go +++ b/relay/channel/task/jimeng/adaptor.go @@ func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any) (*http.Response, error) { taskID, ok := body["task_id"].(string) if !ok { return nil, fmt.Errorf("invalid task_id") } - uri := fmt.Sprintf("%s/?Action=CVSync2AsyncGetResult&Version=2022-08-31", baseUrl) - payload := map[string]string{ - "req_key": "jimeng_vgfm_t2v_l20", // This is fixed value from doc: https://www.volcengine.com/docs/85621/1544774 - "task_id": taskID, - } + uri := fmt.Sprintf("%s/?Action=CVSync2AsyncGetResult&Version=2022-08-31", baseUrl) + // Prefer explicitly provided req_key, otherwise default to the submission default. + reqKey, _ := body["req_key"].(string) + if strings.TrimSpace(reqKey) == "" { + reqKey = "jimeng_vgfm_i2v_l20" + } + payload := map[string]string{ + "req_key": reqKey, + "task_id": taskID, + } @@ -func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*requestPayload, error) { - r := requestPayload{ - ReqKey: "jimeng_vgfm_i2v_l20", +func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq) (*requestPayload, error) { + // Default req_key based on presence of image: i2v when image is provided, else t2v. + reqKey := "jimeng_vgfm_t2v_l20" + if strings.TrimSpace(req.Image) != "" { + reqKey = "jimeng_vgfm_i2v_l20" + } + r := requestPayload{ + ReqKey: reqKey, Prompt: req.Prompt, AspectRatio: "16:9", // Default aspect ratio Seed: -1, // Default to random }Optionally, persist the req_key along with task submission so the fetch path can reuse the exact value: include it in the taskData or response body.
Also applies to: 329-334
356-377: Failure status is overridden by downstream status mappingWhen Code != 10000, you set failure, then unconditionally overwrite Status based on resTask.Data.Status. This can flip a failure into "queued/success" incorrectly.
Fix by returning early on non-success, or guard the status switch:
func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) { resTask := responseTask{} if err := json.Unmarshal(respBody, &resTask); err != nil { return nil, errors.Wrap(err, "unmarshal task result failed") } taskResult := relaycommon.TaskInfo{} - if resTask.Code == 10000 { - taskResult.Code = 0 - } else { - taskResult.Code = resTask.Code // todo uni code - taskResult.Reason = resTask.Message - taskResult.Status = model.TaskStatusFailure - taskResult.Progress = "100%" - } + if resTask.Code != 10000 { + taskResult.Code = resTask.Code // todo uni code + taskResult.Reason = resTask.Message + taskResult.Status = model.TaskStatusFailure + taskResult.Progress = "100%" + return &taskResult, nil + } + taskResult.Code = 0 switch resTask.Data.Status { case "in_queue": taskResult.Status = model.TaskStatusQueued taskResult.Progress = "10%" case "done": taskResult.Status = model.TaskStatusSuccess taskResult.Progress = "100%" }relay/channel/task/vidu/adaptor.go (1)
160-169: Close upstream response body to avoid connection leaksresp.Body is not closed, which can exhaust HTTP connections under load.
func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, _ *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) { - responseBody, err := io.ReadAll(resp.Body) + defer resp.Body.Close() + responseBody, err := io.ReadAll(resp.Body) if err != nil { taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError) return }relay/channel/task/suno/adaptor.go (1)
95-103: Close upstream response body to avoid connection leaksAdd a close to ensure connections are returned to the pool.
func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) { - responseBody, err := io.ReadAll(resp.Body) + defer resp.Body.Close() + responseBody, err := io.ReadAll(resp.Body) if err != nil { taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError) return }relay/channel/task/kling/adaptor.go (2)
97-107: Action detection ignores text-only requests; always routes to image2videoValidateRequestAndSetAction hardcodes generate, and BuildRequestURL picks image2video when Action == generate. For text-only requests, this will hit the wrong endpoint.
Adjust action based on presence of req.Image (mirroring Vidu):
func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) { // Accept only POST /v1/video/generations as "generate" action. - action := constant.TaskActionGenerate - info.Action = action + action := constant.TaskActionGenerate @@ var req SubmitReq if err := common.UnmarshalBodyReusable(c, &req); err != nil { @@ if strings.TrimSpace(req.Prompt) == "" { @@ } - // Store into context for later usage + // Choose action based on presence of image + if strings.TrimSpace(req.Image) == "" { + info.Action = constant.TaskActionTextGenerate + } else { + info.Action = constant.TaskActionGenerate + } + // Store into context for later usage c.Set("task_request", req) return nil }Also applies to: 112-116
159-179: Close upstream response body to avoid connection leaksAdd a close before reading to ensure the transport can reuse the connection.
func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) { - responseBody, err := io.ReadAll(resp.Body) + defer resp.Body.Close() + responseBody, err := io.ReadAll(resp.Body) if err != nil { taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError) return }
🧹 Nitpick comments (10)
relay/common/relay_info.go (1)
404-406: Fallback RelayMode from context is OKUsing
c.GetInt("relay_mode")whenPath2RelayModeyields unknown is a reasonable fallback. Optional: guard against redundant 0 to make intent explicit.Apply this minimal tweak if desired:
- if info.RelayMode == relayconstant.RelayModeUnknown { - info.RelayMode = c.GetInt("relay_mode") - } + if info.RelayMode == relayconstant.RelayModeUnknown { + if v := c.GetInt("relay_mode"); v != relayconstant.RelayModeUnknown { + info.RelayMode = v + } + }controller/relay.go (1)
390-394: Handle GenRelayInfo error instead of returning silentlyFor
RelayFormatTask,GenRelayInfocurrently won’t error, but if this changes you’ll return without a response. Respond with a clear error to the client.Apply this diff:
- relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatTask, nil, nil) - if err != nil { - return - } + relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatTask, nil, nil) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{ + "description": fmt.Sprintf("failed to generate relay info: %s", err.Error()), + "type": "upstream_error", + "code": 4, + }) + return + }relay/relay_task.go (1)
58-66: Quota ratio computation is fine; minor clarity suggestionLogic prefers user-group-specific ratio when present; otherwise falls back to group ratio. Consider including the chosen ratio in a local
effectiveRatiofor readability.- var ratio float64 - userGroupRatio, hasUserGroupRatio := ratio_setting.GetGroupGroupRatio(info.UserGroup, info.UsingGroup) - if hasUserGroupRatio { - ratio = modelPrice * userGroupRatio - } else { - ratio = modelPrice * groupRatio - } + userGroupRatio, hasUserGroupRatio := ratio_setting.GetGroupGroupRatio(info.UserGroup, info.UsingGroup) + effectiveRatio := userGroupRatio + if !hasUserGroupRatio { + effectiveRatio = groupRatio + } + ratio := modelPrice * effectiveRatiorelay/channel/adapter.go (2)
37-41: Header construction API is inconsistent across Adaptor and TaskAdaptorAdaptor.SetupRequestHeader takes *http.Header while TaskAdaptor.BuildRequestHeader takes *http.Request. Consider unifying to one shape (prefer *http.Request) to eliminate duplicated logic and edge cases around Host/header casing.
33-41: Decouple from gin.Context at the interface boundarySince gin.Context implements context.Context, consider accepting context.Context in TaskAdaptor methods and using gin-specific types only at the HTTP layer. This improves testability and reuse for non-HTTP flows.
relay/channel/task/jimeng/adaptor.go (2)
245-260: Canonical query encoding should be RFC 3986, not url.QueryEscapeFor HMAC-SHA256 style signing, spaces must be %20 (not +), and a few runes need normalization. url.QueryEscape produces + for spaces, which can lead to signature mismatches.
- for _, k := range sortedKeys { + for _, k := range sortedKeys { values := queryParams[k] sort.Strings(values) for _, v := range values { - queryParts = append(queryParts, fmt.Sprintf("%s=%s", url.QueryEscape(k), url.QueryEscape(v))) + queryParts = append(queryParts, fmt.Sprintf("%s=%s", rfc3986Escape(k), rfc3986Escape(v))) } }Add helper (outside the selected range):
// rfc3986Escape encodes per RFC 3986 (space -> %20, ~ preserved) func rfc3986Escape(s string) string { e := url.QueryEscape(s) e = strings.ReplaceAll(e, "+", "%20") e = strings.ReplaceAll(e, "*", "%2A") e = strings.ReplaceAll(e, "%7E", "~") return e }
345-352: Typo and clearer error messages in metadata handlingRename medaBytes to metaBytes and make errors actionable.
- medaBytes, err := json.Marshal(metadata) + metaBytes, err := json.Marshal(metadata) if err != nil { - return nil, errors.Wrap(err, "metadata marshal metadata failed") + return nil, errors.Wrap(err, "marshal metadata failed") } - err = json.Unmarshal(medaBytes, &r) + err = json.Unmarshal(metaBytes, &r) if err != nil { - return nil, errors.Wrap(err, "unmarshal metadata failed") + return nil, errors.Wrap(err, "apply metadata overrides failed") }relay/channel/task/suno/adaptor.go (2)
146-160: Unnecessary defer on request body; prefer closing the response bodyThe current FetchTask defers req.Body.Close() (usually a NopCloser over a buffer) and never closes resp.Body. Remove the defer on req.Body and close resp.Body instead.
- req, err := http.NewRequest("POST", requestUrl, bytes.NewBuffer(byteBody)) + req, err := http.NewRequest("POST", requestUrl, bytes.NewBuffer(byteBody)) if err != nil { common.SysLog(fmt.Sprintf("Get Task error: %v", err)) return nil, err } - defer req.Body.Close() @@ - resp, err := service.GetHttpClient().Do(req) + resp, err := service.GetHttpClient().Do(req) if err != nil { return nil, err } + // Caller should close resp.Body; if you consume it here, add: defer resp.Body.Close() return resp, nil
26-29: ParseTaskResult is unimplementedIf this path is ever used, it will error. If intentional, add a comment pointing to the alternative flow; otherwise, I can wire this up consistent with Kling/Vidu adapters.
relay/channel/task/kling/adaptor.go (1)
293-310: Gracefully handle empty/invalid API keys for JWTWhen apiKey is empty, accessKey becomes "", and you return a blank bearer token. Consider validating non-empty keys and surfacing a clear error earlier (Init or BuildRequestHeader).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (10)
controller/relay.go(4 hunks)model/task.go(1 hunks)relay/channel/adapter.go(1 hunks)relay/channel/api_request.go(2 hunks)relay/channel/task/jimeng/adaptor.go(4 hunks)relay/channel/task/kling/adaptor.go(6 hunks)relay/channel/task/suno/adaptor.go(4 hunks)relay/channel/task/vidu/adaptor.go(4 hunks)relay/common/relay_info.go(2 hunks)relay/relay_task.go(7 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-06-15T12:38:11.806Z
Learnt from: feitianbubu
PR: QuantumNous/new-api#1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().
Applied to files:
relay/channel/task/suno/adaptor.go
🧬 Code graph analysis (6)
relay/channel/task/vidu/adaptor.go (4)
relay/channel/task/jimeng/adaptor.go (1)
TaskAdaptor(70-75)relay/channel/task/kling/adaptor.go (1)
TaskAdaptor(77-81)relay/channel/task/suno/adaptor.go (1)
TaskAdaptor(22-24)relay/common/relay_info.go (1)
RelayInfo(74-120)
relay/common/relay_info.go (1)
relay/constant/relay_mode.go (1)
RelayModeUnknown(9-9)
relay/relay_task.go (6)
relay/common/relay_info.go (1)
RelayInfo(74-120)relay/relay_adaptor.go (2)
GetTaskPlatform(108-114)GetTaskAdaptor(116-134)model/user.go (2)
GetUserQuota(570-595)UpdateUserUsedQuotaAndRequestCount(737-744)service/quota.go (1)
PostConsumeQuota(490-519)model/log.go (2)
RecordConsumeLog(153-200)RecordConsumeLogParams(138-151)model/channel.go (1)
UpdateChannelUsedQuota(729-735)
relay/channel/task/kling/adaptor.go (2)
relay/common/relay_info.go (1)
RelayInfo(74-120)constant/task.go (1)
TaskActionGenerate(14-14)
relay/channel/task/jimeng/adaptor.go (1)
relay/common/relay_info.go (1)
RelayInfo(74-120)
relay/channel/task/suno/adaptor.go (1)
relay/common/relay_info.go (1)
RelayInfo(74-120)
🔇 Additional comments (7)
controller/relay.go (2)
24-25: Import reorder is fineNothing to change here.
429-436: Switching to RelayInfo-centric handler looks goodUsing
relayInfo.RelayModeand passingrelayInfodownstream aligns with the new single-object flow.relay/relay_task.go (4)
25-39: Good: initialize channel meta up front and adaptors receive unified RelayInfo
info.InitChannelMeta(c)before adaptor work de-risks laterChannelMetaaccess. Interface migration toRelayInfois consistent.
43-47: Model resolution fallback is sensibleUsing
OriginModelNamewith fallback toCoverTaskActionToModelName(platform, info.Action)is appropriate and backward-compatible.
124-159: Post-consume and logging flow LGTMQuota deduction and logging use
infoconsistently. Good inclusion of group ratio details inOther.
161-178: ConsumeQuota flag and task persistence look correctSetting
info.ConsumeQuota = trueonly after successful response handling, then persistingTaskwithInitTask(platform, info)andActionfrominfo.Actionis consistent with the new flow.relay/channel/adapter.go (1)
33-43: Interface break checked – TaskAdaptor signatures updatedI’ve confirmed the following:
- No remaining references to the old
TaskRelayInfostruct orGenTaskRelayInfohelper anywhere in the repo (rg \bTaskRelayInfo\b|GenTaskRelayInforeturned only the type definition inrelay/common/relay_info.go).- All
TaskAdaptorimplementations underrelay/channel/task/*/adaptor.gonow define the seven methods (Init,ValidateRequestAndSetAction,BuildRequestURL,BuildRequestHeader,BuildRequestBody,DoRequest,DoResponse) with*relaycommon.RelayInfoparameters.Next steps:
- Please manually verify that your controller /
relay_taskflows construct and pass a fully–populatedrelaycommon.RelayInfoinstance into these adapters, as this cannot be enforced via signature checks alone.
| func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error { | ||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Accept", "application/json") | ||
| return a.signRequest(req, a.accessKey, a.secretKey) | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Fail fast on invalid API key format
signRequest will happily sign with an empty secret, leading to opaque upstream 401/403. Validate the "ak|sk" parts and return a descriptive error.
func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
- return a.signRequest(req, a.accessKey, a.secretKey)
+ if a.accessKey == "" || a.secretKey == "" {
+ return fmt.Errorf("invalid api key for jimeng: expected 'access_key|secret_key'")
+ }
+ return a.signRequest(req, a.accessKey, a.secretKey)
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error { | |
| req.Header.Set("Content-Type", "application/json") | |
| req.Header.Set("Accept", "application/json") | |
| return a.signRequest(req, a.accessKey, a.secretKey) | |
| } | |
| func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error { | |
| req.Header.Set("Content-Type", "application/json") | |
| req.Header.Set("Accept", "application/json") | |
| if a.accessKey == "" || a.secretKey == "" { | |
| return fmt.Errorf("invalid api key for jimeng: expected 'access_key|secret_key'") | |
| } | |
| return a.signRequest(req, a.accessKey, a.secretKey) | |
| } |
🤖 Prompt for AI Agents
In relay/channel/task/jimeng/adaptor.go around lines 116 to 120, the
BuildRequestHeader currently attempts to sign requests even when API credentials
are invalid; add a fast-fail validation before calling signRequest: verify that
a.accessKey and a.secretKey are non-empty (and trim whitespace) and that they
match expected patterns (e.g., accessKey contains the required 'ak' part and
secretKey contains the 'sk' part or otherwise meet your credential format
rules), and if validation fails return a descriptive error (for example
fmt.Errorf("invalid API credentials: missing or malformed accessKey/secretKey"))
instead of calling signRequest. Ensure you return the error up the call chain
and do not modify the request headers or attempt signing when credentials are
invalid.
| func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) { | ||
| baseURL := info.ChannelBaseUrl | ||
| fullRequestURL := fmt.Sprintf("%s%s", baseURL, "/suno/submit/"+info.Action) | ||
| return fullRequestURL, nil | ||
| } |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Action path uses uppercased segment; verify server expects this
ValidateRequestAndSetAction uppercases the action and BuildRequestURL uses it in the URL path. Many REST routes are lowercase; if the upstream expects lowercase, this will 404.
Run:
If the upstream expects lowercase, change to strings.ToLower for path construction while keeping any business logic case-insensitive.
Also applies to: 34-60
🏁 Script executed:
#!/bin/bash
# Inspect routes or reverse-proxy rules expecting /suno/submit/<action>
rg -nP --type=go -C2 'suno/submit/([A-Za-z]+)'Length of output: 48
🏁 Script executed:
#!/bin/bash
# Search for ValidateRequestAndSetAction in the codebase
rg -n 'ValidateRequestAndSetAction' -C3 --no-heading
# Search for ToLower occurrences in suno adaptor
rg -n 'ToLower' -C3 --no-heading relay/channel/task/suno/adaptor.go
# Search for suno/submit usage across the repo
rg -n 'suno/submit' -C3 --no-heading
# Search for Action assignment and mutations in adaptor.go
rg -n 'Action' -C3 --no-heading relay/channel/task/suno/adaptor.goLength of output: 5287
Convert action to lowercase in Suno request URL
The Suno API documentation specifies lowercase paths for submit endpoints (e.g. /suno/submit/music, /suno/submit/lyrics), but BuildRequestURL currently appends the uppercased info.Action, which will result in URLs like /suno/submit/MUSIC and cause 404s.
• Location to update:
– relay/channel/task/suno/adaptor.go, line 64
• Proposed diff:
- fullRequestURL := fmt.Sprintf("%s%s", baseURL, "/suno/submit/"+info.Action)
+ fullRequestURL := fmt.Sprintf("%s/suno/submit/%s", baseURL, strings.ToLower(info.Action))This change preserves the uppercase info.Action used for business logic while ensuring the URL path matches the lowercase convention expected by the server.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) { | |
| baseURL := info.ChannelBaseUrl | |
| fullRequestURL := fmt.Sprintf("%s%s", baseURL, "/suno/submit/"+info.Action) | |
| return fullRequestURL, nil | |
| } | |
| func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) { | |
| baseURL := info.ChannelBaseUrl | |
| fullRequestURL := fmt.Sprintf("%s/suno/submit/%s", baseURL, strings.ToLower(info.Action)) | |
| return fullRequestURL, nil | |
| } |
🤖 Prompt for AI Agents
In relay/channel/task/suno/adaptor.go around lines 62 to 66, the URL builder
appends info.Action as-is which can be uppercase and causes 404s; change the URL
assembly to use a lowercase version of the action (e.g.
strings.ToLower(info.Action)) when constructing the path "/suno/submit/<action>"
while leaving info.Action unchanged elsewhere for business logic, and add the
strings import if it’s not already present.
| *TaskRelayInfo | ||
| } |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Embedding TaskRelayInfo: ensure it’s always non-nil
With *TaskRelayInfo embedded, any access like info.Action or info.OriginTaskID will deref the pointer. Several call sites (e.g., RelayTaskSubmit) assume it’s non-nil post Init. To avoid hard-to-track panics, defensively initialize it in genBaseRelayInfo.
Apply this diff near the end of genBaseRelayInfo (after fallback RelayMode assignment):
if info.RelayMode == relayconstant.RelayModeUnknown {
info.RelayMode = c.GetInt("relay_mode")
}
+
+ // Ensure TaskRelayInfo is always non-nil to prevent nil deref at call sites.
+ if info.TaskRelayInfo == nil {
+ info.TaskRelayInfo = &TaskRelayInfo{}
+ }Run to verify adaptors aren’t relying on nil TaskRelayInfo:
🏁 Script executed:
#!/bin/bash
# Check that TaskAdaptor.Init initializes TaskRelayInfo or that call sites guard nil.
rg -nP --type=go 'TaskAdaptor\)\s+Init\s*\('
rg -nP --type=go 'info\.TaskRelayInfo\s*='
rg -nP --type=go 'info\.(Action|OriginTaskID|ConsumeQuota)\b' -C2Length of output: 6047
🏁 Script executed:
#!/bin/bash
# Print first 200 lines of relay/common/relay_info.go to inspect TaskRelayInfo and genBaseRelayInfo
sed -n '1,200p' relay/common/relay_info.goLength of output: 6138
🏁 Script executed:
#!/bin/bash
# Locate the genBaseRelayInfo function definition
rg -n 'func\s\+genBaseRelayInfo' -n relay/common/relay_info.go
# Print the implementation of genBaseRelayInfo (lines 200–350)
sed -n '200,350p' relay/common/relay_info.goLength of output: 5182
🏁 Script executed:
#!/bin/bash
# Locate the definition of genBaseRelayInfo
line=$(rg -n 'genBaseRelayInfo' relay/common/relay_info.go | head -1 | cut -d: -f1)
echo "genBaseRelayInfo defined at line: $line"
# Print 10 lines before and after the definition for context
start=$((line - 10))
end=$((line + 10))
sed -n "${start},${end}p" relay/common/relay_info.goLength of output: 915
🏁 Script executed:
#!/bin/bash
# Locate genBaseRelayInfo start line
start=$(rg -n '^func\s\+genBaseRelayInfo' -n relay/common/relay_info.go | head -1 | cut -d: -f1)
echo "genBaseRelayInfo starts at line: $start"
# Print function body (start to start+200)
sed -n "$start,$((start+200))p" relay/common/relay_info.goLength of output: 272
🏁 Script executed:
#!/bin/bash
# Print last 200 lines of relay/common/relay_info.go to locate genBaseRelayInfo definition
tail -n 200 relay/common/relay_info.goLength of output: 6455
🏁 Script executed:
#!/bin/bash
# Search for any references to TaskRelayInfo in task adaptors
rg -n 'TaskRelayInfo' -n relay/channel/taskLength of output: 43
Critical: Initialize TaskRelayInfo in genBaseRelayInfo to prevent nil pointer derefs
The embedded *TaskRelayInfo is never set in genBaseRelayInfo, so any access like info.Action, info.OriginTaskID or info.ConsumeQuota panics at runtime when TaskRelayInfo == nil. Call sites in both the channel adaptors and in relay/relay_task.go assume these fields exist. Please add the following just before returning info in genBaseRelayInfo:
func genBaseRelayInfo(c *gin.Context, request dto.Request) *RelayInfo {
… existing initialization …
if userSetting, ok := common.GetContextKeyType[dto.UserSetting](c, constant.ContextKeyUserSetting); ok {
info.UserSetting = userSetting
}
+ // Ensure the embedded TaskRelayInfo pointer is non-nil
+ if info.TaskRelayInfo == nil {
+ info.TaskRelayInfo = &TaskRelayInfo{}
+ }
return info
}- File:
relay/common/relay_info.go - Function:
genBaseRelayInfo— insert before itsreturn info
This guarantees all downstream fields on info are safe to read or write.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| *TaskRelayInfo | |
| } | |
| func genBaseRelayInfo(c *gin.Context, request dto.Request) *RelayInfo { | |
| … existing initialization … | |
| if userSetting, ok := common.GetContextKeyType[dto.UserSetting](c, constant.ContextKeyUserSetting); ok { | |
| info.UserSetting = userSetting | |
| } | |
| // Ensure the embedded TaskRelayInfo pointer is non-nil | |
| if info.TaskRelayInfo == nil { | |
| info.TaskRelayInfo = &TaskRelayInfo{} | |
| } | |
| return info | |
| } |
🤖 Prompt for AI Agents
In relay/common/relay_info.go around lines 119-120, the embedded *TaskRelayInfo
field on the returned info is never initialized in genBaseRelayInfo which causes
nil-pointer panics when callers access info.Action, info.OriginTaskID,
info.ConsumeQuota, etc.; before the function's return info, ensure the embedded
pointer is non-nil by setting info.TaskRelayInfo = &TaskRelayInfo{} if it is nil
(or otherwise populate required fields) so downstream reads/writes are safe,
taking care not to overwrite an existing TaskRelayInfo if one was intentionally
set earlier.
Summary by CodeRabbit
New Features
Bug Fixes
Refactor