Repository navigation
Go CLI: refactor commands - #16213
Conversation
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds ChangesAdmin ShowRole and Models endpoints + CLI command rename refactor
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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. Comment |
Signed-off-by: Jin Hai <[email protected]>
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 (2)
internal/cli/admin_command.go (1)
587-587:⚠️ Potential issue | 🟠 Major | ⚡ Quick winValidate
numberbefore using it.
cmd.Params["number"].(int)panics if the parser or another caller omits the key or passes a non-intvalue.🐛 Proposed fix
- serviceIndex := cmd.Params["number"].(int) + serviceIndex, ok := cmd.Params["number"].(int) + if !ok { + return nil, fmt.Errorf("number not provided") + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/admin_command.go` at line 587, The type assertion for cmd.Params["number"].(int) will panic if the key is missing or the value is not an int. Replace this unsafe assertion with the two-return-value form of type assertion (value, ok := cmd.Params["number"].(int)) and add validation to check if ok is true and the key exists in cmd.Params. If validation fails, return an appropriate error or handle it gracefully instead of allowing a panic.internal/cli/common_command.go (1)
616-626:⚠️ Potential issue | 🟠 Major | ⚡ Quick winInitialize
result.Dataeven whenresultalready exists.If
GetAdminServerInfo/GetAPIServerInforeturns aCommonDataResponsewithData == nil, Line 623 panics when writing to the nil map.🐛 Proposed fix
if result == nil { result = &CommonDataResponse{} - if result.Data == nil { - result.Data = make(map[string]interface{}) - } + } + if result.Data == nil { + result.Data = make(map[string]interface{}) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/common_command.go` around lines 616 - 626, The current code only initializes result.Data when result itself is nil, but if GetAdminServerInfo or GetAPIServerInfo returns a CommonDataResponse with a non-nil result but nil Data field, the subsequent assignments to result.Data on lines 623-626 will panic. Move the nil check for result.Data outside of the if result == nil block so that result.Data is always initialized before use, regardless of whether result was originally nil.
🧹 Nitpick comments (2)
internal/cli/admin_command.go (1)
589-600: ⚡ Quick winRemove the leftover benchmark branch.
This command still accepts
iterationsand returnsRequestWithIterations, while the refactor scope says admin show commands now use a single request path.♻️ Proposed cleanup
- // Check for benchmark iterations - iterations := 1 - if val, ok := cmd.Params["iterations"].(int); ok && val > 1 { - iterations = val - } - endPoint := fmt.Sprintf("/admin/services/%d", serviceIndex) - - if iterations > 1 { - // Benchmark mode - return raw result for benchmark stats - return c.AdminServerClient.RequestWithIterations("GET", endPoint, "admin", nil, nil, iterations) - } resp, err := c.AdminServerClient.Request("GET", endPoint, "admin", nil, nil)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/admin_command.go` around lines 589 - 600, Remove the benchmark mode support from the admin command handler. Delete the iterations variable declaration and the entire conditional block that checks if iterations > 1 and calls RequestWithIterations. Replace this entire section with a single direct request call using the standard request method instead, passing the same endPoint, method, and other parameters but without the iterations parameter. The code should make one straightforward GET request to the admin service endpoint rather than supporting multiple benchmark iterations.internal/admin/enterprise_handler.go (1)
225-229: ⚡ Quick winUse the errorResponse helper for consistency.
This error response uses
c.JSON(http.StatusBadRequest, gin.H{...})directly, while the rest of the file uses theerrorResponse(c, message, code)helper function. Maintaining a consistent error response pattern improves code maintainability.♻️ Proposed fix
var req ListModelsOrShowModelRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, gin.H{ - "code": 400, - "message": "Invalid request body", - }) + errorResponse(c, "Invalid request body", 400) return }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/admin/enterprise_handler.go` around lines 225 - 229, The error response in this section uses direct c.JSON(http.StatusBadRequest, gin.H{...}) instead of the errorResponse helper function used consistently throughout the rest of the file. Replace this inline JSON response with a call to the errorResponse(c, message, code) helper function, passing the context object, the message "Invalid request body", and the code 400. This will standardize the error response format and improve code maintainability.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/admin/enterprise_handler.go`:
- Around line 222-252: The ListModelsOrShowModel handler function uses
c.ShouldBindJSON to bind a JSON request body on a GET endpoint, which violates
HTTP best practices since GET requests should use query parameters instead. To
fix this, change the request struct's field tags from json tags to form tags for
query parameter binding, replace c.ShouldBindJSON(&req) with
c.ShouldBindQuery(&req), and update the validation error handling to use the
errorResponse() helper function (currently it calls c.JSON() directly on lines
225-228) to maintain consistency with other handlers in the file, passing
appropriate parameters like c, "Invalid request parameters", and 400 to
errorResponse.
In `@internal/cli/admin_command.go`:
- Around line 1776-1778: In the admin_command.go file where role_name is
extracted and the endpoint is constructed, add validation for the role_name
parameter extraction to prevent panics from missing or incorrectly typed
parameters, and remove the trailing slash from the endpoint path construction in
the fmt.Sprintf call so that the generated path matches the registered route
`/admin/roles/:role_name` without the trailing slash.
In `@internal/cli/admin_parser.go`:
- Around line 356-360: In the parseAdminListModels function, add optional
semicolon handling after consuming the MODELS token and before returning the
command, similar to how parseAdminListProvider handles it. Check if the current
token is a semicolon using the parser's token checking method, and if present,
consume it by calling p.nextToken(). This will ensure the parser doesn't get
left in an inconsistent state when users include a trailing semicolon after LIST
MODELS.
---
Outside diff comments:
In `@internal/cli/admin_command.go`:
- Line 587: The type assertion for cmd.Params["number"].(int) will panic if the
key is missing or the value is not an int. Replace this unsafe assertion with
the two-return-value form of type assertion (value, ok :=
cmd.Params["number"].(int)) and add validation to check if ok is true and the
key exists in cmd.Params. If validation fails, return an appropriate error or
handle it gracefully instead of allowing a panic.
In `@internal/cli/common_command.go`:
- Around line 616-626: The current code only initializes result.Data when result
itself is nil, but if GetAdminServerInfo or GetAPIServerInfo returns a
CommonDataResponse with a non-nil result but nil Data field, the subsequent
assignments to result.Data on lines 623-626 will panic. Move the nil check for
result.Data outside of the if result == nil block so that result.Data is always
initialized before use, regardless of whether result was originally nil.
---
Nitpick comments:
In `@internal/admin/enterprise_handler.go`:
- Around line 225-229: The error response in this section uses direct
c.JSON(http.StatusBadRequest, gin.H{...}) instead of the errorResponse helper
function used consistently throughout the rest of the file. Replace this inline
JSON response with a call to the errorResponse(c, message, code) helper
function, passing the context object, the message "Invalid request body", and
the code 400. This will standardize the error response format and improve code
maintainability.
In `@internal/cli/admin_command.go`:
- Around line 589-600: Remove the benchmark mode support from the admin command
handler. Delete the iterations variable declaration and the entire conditional
block that checks if iterations > 1 and calls RequestWithIterations. Replace
this entire section with a single direct request call using the standard request
method instead, passing the same endPoint, method, and other parameters but
without the iterations parameter. The code should make one straightforward GET
request to the admin service endpoint rather than supporting multiple benchmark
iterations.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 6e3b5b0c-a788-4fdc-956a-0cb4af594f88
📒 Files selected for processing (10)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/router.gointernal/admin/service.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/common_command.gointernal/cli/parser.gointernal/cli/user_parser.go
💤 Files with no reviewable changes (2)
- internal/admin/service.go
- internal/cli/parser.go
| func (h *Handler) ListModelsOrShowModel(c *gin.Context) { | ||
| var req ListModelsOrShowModelRequest | ||
| if err := c.ShouldBindJSON(&req); err != nil { | ||
| c.JSON(http.StatusBadRequest, gin.H{ | ||
| "code": 400, | ||
| "message": "Invalid request body", | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| if req.ModelName == "" { | ||
| // List models | ||
| models, err := h.service.ListAllModels() | ||
| if err != nil { | ||
| errorResponse(c, err.Error(), 500) | ||
| return | ||
| } | ||
|
|
||
| success(c, models, "") | ||
| } else { | ||
| // Get model | ||
| model, err := h.service.GetModelByModelName(req.ModelName) | ||
| if err != nil { | ||
| errorResponse(c, err.Error(), 500) | ||
| return | ||
| } | ||
|
|
||
| success(c, model, "") | ||
| } | ||
| } | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check httpClient.Request implementation to confirm GET body handling
# Find the Request method definition
ast-grep --pattern 'func ($_ *HTTPClient) Request($$$) ($$$) {
$$$
}'
# Also search for how payload is processed in GET requests
rg -n -A 10 'func.*Request.*method.*string' internal/cli/http_client.goRepository: infiniflow/ragflow
Length of output: 5236
🏁 Script executed:
#!/bin/bash
# Check the client code that calls the handler
# Find ListAllModels and CommonShowModel in common_command.go
rg -n -B 5 -A 15 "func.*ListAllModels|func.*CommonShowModel" internal/cli/common_command.go
# Check router.go line 176 to confirm the endpoint configuration
sed -n '170,185p' internal/admin/router.go
# Also check if there are multiple routers or if GET is definitely used
rg -n "all-models" internal/admin/router.goRepository: infiniflow/ragflow
Length of output: 1799
🏁 Script executed:
#!/bin/bash
# Check what HTTP method is passed in the Request call for both functions
# Check ListAllModels method call
sed -n '920,945p' internal/cli/common_command.go
# Check CommonShowModel method call
sed -n '968,990p' internal/cli/common_command.goRepository: infiniflow/ragflow
Length of output: 1513
🏁 Script executed:
#!/bin/bash
# Check the error response pattern in the handler file
# Look at the ListModelsOrShowModel handler lines 222-252
sed -n '222,252p' internal/admin/enterprise_handler.go
# Check how errorResponse is used elsewhere in the file
rg -n "errorResponse" internal/admin/enterprise_handler.go | head -20
# Check if c.JSON with StatusBadRequest is used elsewhere
rg -n 'c\.JSON.*StatusBadRequest' internal/admin/enterprise_handler.go | head -10Repository: infiniflow/ragflow
Length of output: 1685
GET requests should not use JSON body binding.
The handler binds a JSON request body using c.ShouldBindJSON on a GET endpoint. This violates HTTP best practices:
- GET requests should use query parameters, not request bodies
- Many HTTP proxies and caches ignore or strip GET request bodies
- This pattern is non-standard and may fail with standard HTTP clients or infrastructure
The client code in internal/cli/common_command.go confirms both ListAllModels (line 929) and CommonShowModel (line 977) send GET requests with JSON payloads to this endpoint.
Additionally, lines 225-228 use c.JSON() directly for error handling, while all other handlers in this file use the errorResponse() helper function. For consistency, use errorResponse(c, "Invalid request parameters", 400).
Recommended fixes:
- Change the request struct to use query parameter binding with
formtags - Use
c.ShouldBindQuery(&req)instead ofc.ShouldBindJSON(&req) - Use the
errorResponse()helper for the validation error - Alternatively, change the HTTP method to POST if a body is required
Proposed fix to use query parameters
type ListModelsOrShowModelRequest struct {
- ModelName string `json:"model_name"`
+ ModelName string `form:"model_name"`
}
func (h *Handler) ListModelsOrShowModel(c *gin.Context) {
var req ListModelsOrShowModelRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "code": 400,
- "message": "Invalid request body",
- })
+ if err := c.ShouldBindQuery(&req); err != nil {
+ errorResponse(c, "Invalid request parameters", 400)
return
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/admin/enterprise_handler.go` around lines 222 - 252, The
ListModelsOrShowModel handler function uses c.ShouldBindJSON to bind a JSON
request body on a GET endpoint, which violates HTTP best practices since GET
requests should use query parameters instead. To fix this, change the request
struct's field tags from json tags to form tags for query parameter binding,
replace c.ShouldBindJSON(&req) with c.ShouldBindQuery(&req), and update the
validation error handling to use the errorResponse() helper function (currently
it calls c.JSON() directly on lines 225-228) to maintain consistency with other
handlers in the file, passing appropriate parameters like c, "Invalid request
parameters", and 400 to errorResponse.
| roleName := cmd.Params["role_name"].(string) | ||
|
|
||
| endPoint := fmt.Sprintf("/admin/roles/%s/", roleName) |
There was a problem hiding this comment.
Validate role_name and match the registered route.
The unchecked assertion can panic on a missing/mis-typed param, and the built path adds a trailing slash while the admin router registers /roles/:role_name.
🐛 Proposed fix
- roleName := cmd.Params["role_name"].(string)
+ roleName, ok := cmd.Params["role_name"].(string)
+ if !ok {
+ return nil, fmt.Errorf("role_name not provided")
+ }
- endPoint := fmt.Sprintf("/admin/roles/%s/", roleName)
+ endPoint := fmt.Sprintf("/admin/roles/%s", roleName)📝 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.
| roleName := cmd.Params["role_name"].(string) | |
| endPoint := fmt.Sprintf("/admin/roles/%s/", roleName) | |
| roleName, ok := cmd.Params["role_name"].(string) | |
| if !ok { | |
| return nil, fmt.Errorf("role_name not provided") | |
| } | |
| endPoint := fmt.Sprintf("/admin/roles/%s", roleName) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/cli/admin_command.go` around lines 1776 - 1778, In the
admin_command.go file where role_name is extracted and the endpoint is
constructed, add validation for the role_name parameter extraction to prevent
panics from missing or incorrectly typed parameters, and remove the trailing
slash from the endpoint path construction in the fmt.Sprintf call so that the
generated path matches the registered route `/admin/roles/:role_name` without
the trailing slash.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16213 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
As title.
Type of change