Repository navigation
Go CLI: admin list configs - #16221
Conversation
Signed-off-by: Jin Hai <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe PR refactors admin service and handler methods from Get* to List* patterns with unified error handling, modularizes the CLI parser into reusable helpers for LIST CONFIGS, LIST ENVIRONMENTS, and AVAILABLE PROVIDERS commands, implements AdminListConfigsCommand and AdminListEnvironmentsCommand, renames the shared provider listing command to CommonAvailableProvidersCommand, and adds enterprise user provider/ingestion task listing endpoints with matching service methods, handlers, CLI commands, and parser support. ChangesAdmin API List refactoring and CLI command consolidation*
Enterprise user provider and ingestion task listing
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~30 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ 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]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/admin/handler.go (1)
754-770:⚠️ Potential issue | 🟠 Major
ContentLength == -1is misclassified as "no body" inListVariables.Line 754 treats
ContentLength == -1(unknown-size body per Go semantics) as empty, routing requests with unknown-size bodies toListAllVariables()instead of attempting to parsevar_name. This skips single-variable parsing and returns the wrong result set.Suggested fix
func (h *Handler) ListVariables(c *gin.Context) { - // Check if request has body content - if c.Request.ContentLength == 0 || c.Request.ContentLength == -1 { - // List all variables - variables, err := h.service.ListAllVariables() - if err != nil { - errorResponse(c, err.Error(), 500) - return - } - success(c, variables, "") - return - } - // Get single variable by var_name from request body var req struct { VarName string `json:"var_name"` } if err := c.ShouldBindJSON(&req); err != nil { + // Empty body => list all variables + if c.Request.ContentLength == 0 { + variables, listErr := h.service.ListAllVariables() + if listErr != nil { + errorResponse(c, listErr.Error(), 500) + return + } + success(c, variables, "") + return + } 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/handler.go` around lines 754 - 770, The condition checking ContentLength in the ListVariables handler is incorrectly treating ContentLength == -1 (which indicates unknown body size per Go semantics) as a signal for no body, causing requests with unknown-size bodies to be routed to ListAllVariables() instead of parsing the var_name parameter. Remove the `|| c.Request.ContentLength == -1` portion of the condition on line 754 so that only requests with ContentLength == 0 (truly empty body) skip the single-variable var_name parsing, allowing requests with unknown-size bodies to proceed to the ShouldBindJSON parsing logic.
🤖 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/cli/admin_command.go`:
- Around line 687-698: The error messages in the function handling environment
operations are incorrectly labeled as "configs" instead of "environment". In the
error handling blocks after the nil check, HTTP status code check, and JSON
unmarshaling check, replace "list configs" and "configs" references with the
correct operation name "environment" to accurately reflect what operation
failed. This applies to all three error return statements in the shown section.
In `@internal/cli/admin_parser.go`:
- Around line 233-240: The `parseCommonAvailableProviders()` function hardcodes
the return value to "admin_list_available_providers", but since this helper is
now reused for both admin and user command parsing, it returns the wrong command
type for user commands (which expect "list_available_providers"). Modify the
function signature to accept a parameter (such as a string for the command type
or a boolean flag indicating admin vs user context) and use that parameter to
determine which command type to return in the NewCommand call, ensuring that
admin parsing receives "admin_list_available_providers" and user parsing
receives "list_available_providers".
---
Outside diff comments:
In `@internal/admin/handler.go`:
- Around line 754-770: The condition checking ContentLength in the ListVariables
handler is incorrectly treating ContentLength == -1 (which indicates unknown
body size per Go semantics) as a signal for no body, causing requests with
unknown-size bodies to be routed to ListAllVariables() instead of parsing the
var_name parameter. Remove the `|| c.Request.ContentLength == -1` portion of the
condition on line 754 so that only requests with ContentLength == 0 (truly empty
body) skip the single-variable var_name parsing, allowing requests with
unknown-size bodies to proceed to the ShouldBindJSON parsing logic.
🪄 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: dc94bc81-ddb9-4d1d-9789-2d8865707089
📒 Files selected for processing (8)
internal/admin/handler.gointernal/admin/router.gointernal/admin/service.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/common_command.gointernal/cli/user_parser.go
| if err != nil { | ||
| return nil, fmt.Errorf("failed to list configs: %w", err) | ||
| } | ||
|
|
||
| if resp.StatusCode != 200 { | ||
| return nil, fmt.Errorf("failed to list configs: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) | ||
| } | ||
|
|
||
| var result CommonResponse | ||
| if err = json.Unmarshal(resp.Body, &result); err != nil { | ||
| return nil, fmt.Errorf("list configs failed: invalid JSON (%w)", err) | ||
| } |
There was a problem hiding this comment.
Fix copied error labels in environment error paths.
Line 688, Line 692, and Line 697 still report “configs”, so environment failures return misleading errors.
🔧 Proposed fix
resp, err := c.AdminServerClient.Request("GET", "/admin/environments", "admin", nil, nil)
if err != nil {
- return nil, fmt.Errorf("failed to list configs: %w", err)
+ return nil, fmt.Errorf("failed to list environments: %w", err)
}
if resp.StatusCode != 200 {
- return nil, fmt.Errorf("failed to list configs: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+ return nil, fmt.Errorf("failed to list environments: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
}
var result CommonResponse
if err = json.Unmarshal(resp.Body, &result); err != nil {
- return nil, fmt.Errorf("list configs failed: invalid JSON (%w)", err)
+ return nil, fmt.Errorf("list environments failed: invalid JSON (%w)", err)
}📝 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.
| if err != nil { | |
| return nil, fmt.Errorf("failed to list configs: %w", err) | |
| } | |
| if resp.StatusCode != 200 { | |
| return nil, fmt.Errorf("failed to list configs: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) | |
| } | |
| var result CommonResponse | |
| if err = json.Unmarshal(resp.Body, &result); err != nil { | |
| return nil, fmt.Errorf("list configs failed: invalid JSON (%w)", err) | |
| } | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to list environments: %w", err) | |
| } | |
| if resp.StatusCode != 200 { | |
| return nil, fmt.Errorf("failed to list environments: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) | |
| } | |
| var result CommonResponse | |
| if err = json.Unmarshal(resp.Body, &result); err != nil { | |
| return nil, fmt.Errorf("list environments failed: invalid JSON (%w)", err) | |
| } |
🤖 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 687 - 698, The error messages in
the function handling environment operations are incorrectly labeled as
"configs" instead of "environment". In the error handling blocks after the nil
check, HTTP status code check, and JSON unmarshaling check, replace "list
configs" and "configs" references with the correct operation name "environment"
to accurately reflect what operation failed. This applies to all three error
return statements in the shown section.
| func (p *Parser) parseCommonAvailableProviders() (*Command, error) { | ||
| p.nextToken() // consume AVAILABLE | ||
|
|
||
| if p.curToken.Type != TokenProviders { | ||
| return nil, fmt.Errorf("expected PROVIDERS") | ||
| } | ||
|
|
||
| return NewCommand("list_available_providers"), nil | ||
| return NewCommand("admin_list_available_providers"), nil |
There was a problem hiding this comment.
Shared available-providers parser hardcodes admin command type and breaks user dispatch.
parseCommonAvailableProviders() always returns admin_list_available_providers. Since user parsing now reuses this helper, user LIST AVAILABLE PROVIDERS can emit an admin command type that ExecuteUserCommand does not route (list_available_providers is expected there), causing command execution failure.
💡 Proposed fix
--- a/internal/cli/admin_parser.go
+++ b/internal/cli/admin_parser.go
@@
-func (p *Parser) parseCommonAvailableProviders() (*Command, error) {
+func (p *Parser) parseCommonAvailableProviders(cmdType string) (*Command, error) {
p.nextToken() // consume AVAILABLE
if p.curToken.Type != TokenProviders {
return nil, fmt.Errorf("expected PROVIDERS")
}
- return NewCommand("admin_list_available_providers"), nil
+ return NewCommand(cmdType), nil
}--- a/internal/cli/admin_parser.go
+++ b/internal/cli/admin_parser.go
@@
case TokenAvailable:
- return p.parseCommonAvailableProviders()
+ return p.parseCommonAvailableProviders("admin_list_available_providers")--- a/internal/cli/user_parser.go
+++ b/internal/cli/user_parser.go
@@
case TokenAvailable:
- return p.parseCommonAvailableProviders()
+ return p.parseCommonAvailableProviders("list_available_providers")🤖 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_parser.go` around lines 233 - 240, The
`parseCommonAvailableProviders()` function hardcodes the return value to
"admin_list_available_providers", but since this helper is now reused for both
admin and user command parsing, it returns the wrong command type for user
commands (which expect "list_available_providers"). Modify the function
signature to accept a parameter (such as a string for the command type or a
boolean flag indicating admin vs user context) and use that parameter to
determine which command type to return in the NewCommand call, ensuring that
admin parsing receives "admin_list_available_providers" and user parsing
receives "list_available_providers".
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 705-707: The error handling at lines 705, 733, and 767 in
enterprise_handler.go currently returns HTTP 500 for all errors from the service
layer. Instead of treating all errors the same, check if the returned error is
specifically common.ErrUserNotFound and map it to an HTTP 404 status code using
errorResponse, while mapping other errors to HTTP 500. This ensures that
client-side errors (user not found) are properly distinguished from server
errors in the HTTP response status.
In `@internal/admin/enterprise_service.go`:
- Around line 476-479: The user lookup error handling in the three database
query blocks (around lines 476-479, 497-500, and 519-522) currently treats all
query errors the same by returning common.ErrUserNotFound, which masks actual
database or runtime failures. For each of these three error handling blocks,
check if the error is specifically a "record not found" error (typically
gorm.ErrRecordNotFound) and only return common.ErrUserNotFound in that case; for
all other errors, return the actual error to preserve error semantics and aid
debugging.
In `@internal/cli/admin_parser.go`:
- Around line 2706-2727: The parseAdminListUserIngestionTasks function receives
userName as a parameter but fails to store it in the command params and does not
consume the optional semicolon terminator. Add cmd.Params["user_name"] =
userName assignment after creating the NewCommand object to propagate the user
name to downstream command execution. Additionally, after the optional status
parameter handling, add a check for TokenSemicolon and consume it with
p.nextToken() if present, matching the pattern used in sibling LIST USER helper
functions.
🪄 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: 74aaabc1-8f97-4ee8-bb21-80ec491478ea
📒 Files selected for processing (7)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/router.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/user_parser.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/cli/user_parser.go
| if err != nil { | ||
| errorResponse(c, err.Error(), 500) | ||
| return |
There was a problem hiding this comment.
Map user-not-found errors to client status instead of 500.
At Line 705, Line 733, and Line 767, all service errors return HTTP 500. For common.ErrUserNotFound, this should be a not-found/client response (typically 404), otherwise clients get false server-failure signals.
Suggested fix
+import "errors"
...
- if err != nil {
- errorResponse(c, err.Error(), 500)
- return
- }
+ if err != nil {
+ if errors.Is(err, common.ErrUserNotFound) {
+ errorResponse(c, err.Error(), 404)
+ return
+ }
+ errorResponse(c, err.Error(), 500)
+ return
+ }As per coding guidelines, “cross-file ... contract breaks” should be validated end-to-end, including error-path behavior across layers.
Also applies to: 733-735, 767-769
🤖 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 705 - 707, The error
handling at lines 705, 733, and 767 in enterprise_handler.go currently returns
HTTP 500 for all errors from the service layer. Instead of treating all errors
the same, check if the returned error is specifically common.ErrUserNotFound and
map it to an HTTP 404 status code using errorResponse, while mapping other
errors to HTTP 500. This ensures that client-side errors (user not found) are
properly distinguished from server errors in the HTTP response status.
| err := dao.DB.Where("email = ?", email).First(&user).Error | ||
| if err != nil { | ||
| return nil, common.ErrUserNotFound | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, let's read the file around the specified lines
cat -n internal/admin/enterprise_service.go | sed -n '470,530p'Repository: infiniflow/ragflow
Length of output: 2338
🏁 Script executed:
# Check the imports at the top of the file
head -30 internal/admin/enterprise_service.goRepository: infiniflow/ragflow
Length of output: 944
🏁 Script executed:
# Search for other similar patterns in the file
rg "Where.*First.*Error" internal/admin/enterprise_service.go -B 2 -A 2Repository: infiniflow/ragflow
Length of output: 2993
🏁 Script executed:
# Check how gorm.ErrRecordNotFound is used elsewhere in the codebase
rg "gorm\.ErrRecordNotFound\|errors\.Is" --type go -B 1 -A 1Repository: infiniflow/ragflow
Length of output: 44
Differentiate not-found from datastore failures in user lookup.
Lines 476–479, 497–500, and 519–522 collapse all lookup failures into common.ErrUserNotFound, masking real DB/runtime errors and breaking error semantics for callers.
Suggested fix
+import "gorm.io/gorm"
...
- err := dao.DB.Where("email = ?", email).First(&user).Error
- if err != nil {
- return nil, common.ErrUserNotFound
- }
+ err := dao.DB.Where("email = ?", email).First(&user).Error
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, common.ErrUserNotFound
+ }
+ return nil, err
+ }Apply the same fix to all three methods.
🤖 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_service.go` around lines 476 - 479, The user lookup
error handling in the three database query blocks (around lines 476-479,
497-500, and 519-522) currently treats all query errors the same by returning
common.ErrUserNotFound, which masks actual database or runtime failures. For
each of these three error handling blocks, check if the error is specifically a
"record not found" error (typically gorm.ErrRecordNotFound) and only return
common.ErrUserNotFound in that case; for all other errors, return the actual
error to preserve error semantics and aid debugging.
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/cli/admin_command.go`:
- Around line 2990-2997: The code type-checks user_name but does not validate
that it is non-empty, allowing an empty string to pass through and create an
invalid API URL like /admin/users//default-models. After the existing type check
for userName using the ok variable, add an additional validation check to ensure
userName is not an empty string, and return a fmt.Errorf with an appropriate
message if it is empty. This validation should occur before calling
common.EncodeEmail(userName) and constructing the apiURL.
🪄 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: 8df2472a-f861-4954-b829-5e27f84aea15
📒 Files selected for processing (6)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/router.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/cli_http.go
🚧 Files skipped from review as they are similar to previous changes (4)
- internal/admin/enterprise_handler.go
- internal/admin/router.go
- internal/cli/cli_http.go
- internal/cli/admin_parser.go
| userName, ok := cmd.Params["user_name"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("user_name not provided") | ||
| } | ||
|
|
||
| encodedUserName := common.EncodeEmail(userName) | ||
| apiURL := fmt.Sprintf("/admin/users/%s/default-models", encodedUserName) | ||
|
|
There was a problem hiding this comment.
Reject empty user_name before constructing the API path.
user_name is only type-checked, so an empty string can produce /admin/users//default-models and a misleading downstream failure.
Suggested patch
userName, ok := cmd.Params["user_name"].(string)
-if !ok {
+if !ok || strings.TrimSpace(userName) == "" {
return nil, fmt.Errorf("user_name 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` around lines 2990 - 2997, The code type-checks
user_name but does not validate that it is non-empty, allowing an empty string
to pass through and create an invalid API URL like /admin/users//default-models.
After the existing type check for userName using the ok variable, add an
additional validation check to ensure userName is not an empty string, and
return a fmt.Errorf with an appropriate message if it is empty. This validation
should occur before calling common.EncodeEmail(userName) and constructing the
apiURL.
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 #16221 +/- ##
==========================================
- 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:
|
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]>
What problem does this PR solve?
Type of change