Repository navigation
Go: add statistics command - #16119
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (6)
📝 WalkthroughWalkthroughAdds enterprise-edition admin HTTP handlers and service methods for role management, per-user metrics, aggregate user reporting, and purge operations. Simultaneously migrates role-related code from the base Enterprise Admin HTTP Layer
CLI Enterprise Command Expansion
🎯 4 (Complex) | ⏱️ ~60 minutes
🚥 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]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 14
🤖 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 517-522: When strconv.Atoi(topStr) fails and errorResponse is
called in the top parameter validation block, add a return statement immediately
after the errorResponse call to prevent further execution. This applies to all
four occurrences: the initial one around line 517-522, and three additional
instances at lines 561-566, 605-610, and 664-669 where similar top parameter
parsing occurs. Without the return statement, the function continues executing
after sending the error response, potentially causing a second response write or
unintended service call.
- Around line 462-473: The pagination parameters page, page_size, and top are
being incorrectly read from URL path parameters using c.Param() calls, but the
registered routes do not define these as path parameters (such as :page,
:page_size, :top), causing them to always return empty strings and silently
ignore the caller's pagination inputs. Replace all c.Param("page"),
c.Param("page_size"), and c.Param("top") calls with their c.Query() equivalents
throughout the handler to read these values from query string parameters
instead. This applies to the pageIndexStr assignment, pageSize assignment, and
topStr assignment in all affected locations across the file.
- Around line 211-221: The ShowUserActivity handler is reading the user identity
from the JSON request body via c.ShouldBindJSON(&req) instead of using the route
parameter :username that is defined in the endpoint route at line 75 of
internal/admin/router.go. To fix this, extract the username from the URL path
parameter using c.Param("username") in the ShowUserActivity function instead of
relying on req.Email from the JSON body, ensuring the handler uses the actual
route parameter that was specified in the route definition.
- Around line 241-248: The GET endpoint handler is using ShouldBindJSON to parse
request bodies, but GET requests should use query parameters instead. Replace
the ShouldBindJSON call with ShouldBindQuery, and update the request DTO struct
tags from json tags to form tags to properly bind query parameters. Ensure the
error handling remains in place but now captures query parameter binding errors
instead of JSON body errors.
In `@internal/admin/enterprise_service.go`:
- Around line 28-31: The methods ListRoles, and all other role and permission
management methods in the Service type (create, update, delete, grant, revoke
operations) are currently TODO stub implementations that return success without
performing any actual work. Replace each stub implementation with proper
business logic that actually executes the intended operation such as querying a
database, modifying role/permission state, or validating inputs before returning
appropriate results or errors. Ensure that these methods no longer report
success when no work has been performed.
- Around line 79-82: The issue is that all database errors from user lookups are
being indiscriminately converted to ErrUserNotFound, which masks real database
failures and misclassifies API errors. Instead of returning ErrUserNotFound for
any error from the Where().First() database query, you need to differentiate
between actual not-found conditions and other database errors. Check if the
error is specifically a record-not-found error (typically using errors.Is with
gorm.ErrRecordNotFound), and only return ErrUserNotFound in that case. For all
other database errors, propagate them as backend errors. This applies to all
user lookup functions in the file affected by the comment (the GetUserByEmail
call around line 79 and similar patterns at lines 98-101, 117-120, 135-138,
153-156, 171-174, 189-192, 209-212, and 427-429).
In `@internal/cli/admin_command.go`:
- Around line 1955-1985: The AdminListActiveUsersCommand function is not using
the days parameter from the command parser when making the API request, causing
it to return all users instead of filtering for active users. Extract the days
parameter from the cmd argument and pass it as a query parameter to the
c.AdminServerClient.Request call (likely by appending it to the URL path or as a
query string parameter like /admin/users?days=X). This will ensure the endpoint
filters users based on the activity duration specified in the command.
- Line 1550: The userName variable in the apiURL construction is being directly
inserted into the URL path without escaping, which can cause issues if the
identifier contains reserved URL characters. Use the net/url package's
PathEscape function to escape the userName before formatting it into the URL
path string. Apply this same escaping pattern to all other instances where email
or userName path segments are constructed in the activity, summary, dataset,
storage, quota, index, permission, and purge-user handlers as noted in the
affected line ranges.
- Around line 1987-2079: The functions AdminListInactiveUsersCommand,
AdminListUsersStorageCommand, AdminListUsersDocumentsCommand,
AdminListUsersIndexCommand, and AdminListUsersQuotaCommand are currently stub
implementations that only switch admin mode instead of performing their intended
operations. Replace the mode-switching stub logic in each function with actual
calls to the appropriate admin server client methods to retrieve the requested
data (inactive users, storage, documents, index, and quota information
respectively). Each function should call the corresponding admin list method on
c.AdminServerClient and return the actual results instead of the hardcoded
SimpleResponse.
- Around line 1659-1671: The payload map being constructed in the handler only
includes the dataset field, but it does not forward the tree option that was
parsed by parseAdminShowUserDataSetCommand. After constructing the payload with
the dataset key, check if cmd.Params["tree"] exists and is a boolean, and if it
evaluates to true, add a "tree" key to the payload map with the appropriate
value to ensure the TREE option is properly forwarded to the dataset endpoint.
In `@internal/cli/admin_parser.go`:
- Around line 2384-2401: After parsing numeric values in the TokenTop and
TokenQuota cases, the parser does not advance to the next token, which prevents
subsequent options from being parsed. Add p.nextToken() calls after the
p.parseNumber() statement in both the TokenTop case and TokenQuota case to
advance the token pointer, matching the pattern used in the DAYS branch so that
options following TOP or QUOTA can be correctly parsed in the loop.
- Around line 1951-1968: The default case in the switch statement checking
p.curToken.Type currently accepts any unrecognized token by falling back to
parseAdminShowUserInfoCommand, which silently ignores typos or invalid suffixes
like STORAG. Modify the default case to check if the current token is EOF or a
semicolon before calling parseAdminShowUserInfoCommand; for any other
unrecognized token, return an appropriate parse error instead of silently
accepting the invalid command.
- Around line 2562-2627: The parseAdminPurgeUsersCommand function does not
validate that required parameters are provided before building the command.
After the command parsing loop ends (after the commandLoop label), add
validation checks to ensure that planName is not nil (PLAN was provided), days
is not nil (DAYS was provided), and days is greater than zero (positive value).
Return an appropriate error message for any validation failure before
constructing and returning the Command object. This ensures that destructive
bulk-purge operations cannot proceed without both a plan constraint and a
positive day threshold, matching the documented bulk purge requirements.
- Around line 2205-2227: The parseAdminListUsersCommand function returns an
"invalid command" error when encountering EOF after consuming USERS (i.e., for a
plain LIST USERS command without additional parameters or semicolon), which
breaks the optional-semicolon convention. In the default case of the switch
statement, before returning the error, check if curToken.Type is EOF or another
valid termination token. If so, initialize the cmd variable with the appropriate
Command object for the admin_list_users_command and return nil to allow the
plain LIST USERS command to succeed. Only return the error for truly invalid
token types.
🪄 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: 2e2b09d9-a3fb-4f20-8da7-89c3ed6438a2
📒 Files selected for processing (12)
internal/admin/enterprise_handler.gointernal/admin/enterprise_service.gointernal/admin/handler.gointernal/admin/router.gointernal/admin/service.gointernal/cli/admin_command.gointernal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/lexer.gointernal/cli/parser.gointernal/cli/types.gointernal/cli/user_parser.go
💤 Files with no reviewable changes (3)
- internal/admin/handler.go
- internal/admin/service.go
- internal/cli/user_parser.go
| func (h *Handler) ShowUserActivity(c *gin.Context) { | ||
| var req ShowUserActivityRequest | ||
| if err := c.ShouldBindJSON(&req); err != nil { | ||
| println("JSON bind error: %v (type: %T)", err, err) | ||
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": common.CodeBadRequest, | ||
| "message": err.Error(), | ||
| }) | ||
| return | ||
| } | ||
| userActivity, err := h.service.ShowUserActivity(req.Email, req.Days) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Verify route contract for this handler
rg -n 'GET\("/users/:username/activity"' internal/admin/router.go
# Verify handler input source
rg -n -A15 -B3 'func \(h \*Handler\) ShowUserActivity' internal/admin/enterprise_handler.go
# Verify CLI request style (payload/query) for this endpoint
rg -n -A8 -B3 'ShowUserActivity|/admin/users/%s/activity' internal/cli/admin_command.go internal/cli/cli_http.goRepository: infiniflow/ragflow
Length of output: 3204
ShowUserActivity reads identity from JSON body instead of the route parameter :username.
The route at line 75 of internal/admin/router.go defines the endpoint as /users/:username/activity, but the handler at line 211 of internal/admin/enterprise_handler.go ignores the URL parameter and instead reads req.Email from the JSON body via c.ShouldBindJSON(&req) (line 213). When the request body is omitted or empty, the handler uses an empty email value and incorrectly returns "User not found" even though the route parameter was provided.
Either extract the username from the path parameter using c.Param("username") or remove the path parameter from the route definition to match the current implementation.
🤖 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 211 - 221, The
ShowUserActivity handler is reading the user identity from the JSON request body
via c.ShouldBindJSON(&req) instead of using the route parameter :username that
is defined in the endpoint route at line 75 of internal/admin/router.go. To fix
this, extract the username from the URL path parameter using c.Param("username")
in the ShowUserActivity function instead of relying on req.Email from the JSON
body, ensuring the handler uses the actual route parameter that was specified in
the route definition.
| if err := c.ShouldBindJSON(&req); err != nil { | ||
| println("JSON bind error: %v (type: %T)", err, err) | ||
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": common.CodeBadRequest, | ||
| "message": err.Error(), | ||
| }) | ||
| return | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, let's check the file structure and find route registrations
cd /tmp && find . -name "enterprise_handler.go" -type f 2>/dev/null | head -5Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Look at the full enterprise_handler.go file to understand route setup and handlers
wc -l internal/admin/enterprise_handler.goRepository: infiniflow/ragflow
Length of output: 103
🏁 Script executed:
# Get the context around the mentioned lines to see route registrations and handler signatures
sed -n '1,50p' internal/admin/enterprise_handler.goRepository: infiniflow/ragflow
Length of output: 1310
🏁 Script executed:
# Check lines 235-250 for context around first location
sed -n '235,250p' internal/admin/enterprise_handler.goRepository: infiniflow/ragflow
Length of output: 503
🏁 Script executed:
# Check if there's a router setup or route registration at the start of the file
grep -n "GET\|POST\|PUT\|DELETE\|router\|Route" internal/admin/enterprise_handler.go | head -20Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Get lines 235-250 to see the function signature and route context
sed -n '235,260p' internal/admin/enterprise_handler.goRepository: infiniflow/ragflow
Length of output: 785
🏁 Script executed:
# Check lines around 421-428
sed -n '415,435p' internal/admin/enterprise_handler.goRepository: infiniflow/ragflow
Length of output: 674
🏁 Script executed:
# Check lines around 451-458
sed -n '445,465p' internal/admin/enterprise_handler.goRepository: infiniflow/ragflow
Length of output: 595
🏁 Script executed:
# Check lines around 634-641
sed -n '628,648p' internal/admin/enterprise_handler.goRepository: infiniflow/ragflow
Length of output: 603
🏁 Script executed:
# Search for where these handlers might be registered as routes
find internal -name "*.go" -type f | xargs grep -l "ShowUserDatasetSummary\|ListTenants\|ShowTenant" | head -5Repository: infiniflow/ragflow
Length of output: 161
🏁 Script executed:
# Look for router setup/registration in the admin package
ls -la internal/admin/Repository: infiniflow/ragflow
Length of output: 711
🏁 Script executed:
# Check the router.go file to see how handlers are registered
cat -n internal/admin/router.goRepository: infiniflow/ragflow
Length of output: 8680
🏁 Script executed:
# Look specifically for registrations of the handlers mentioned in the review
grep -n "ShowUserDatasetSummary\|ShowUsersActivity\|ListUsersReports\|ListUsersQuota" internal/admin/router.goRepository: infiniflow/ragflow
Length of output: 340
GET handlers are binding request bodies instead of query parameters.
These endpoints are registered as GET routes (ShowUserDatasetSummary, ShowUsersActivity, ListUsersReports, ListUsersQuota), but they call ShouldBindJSON to parse request bodies. This causes avoidable bad-request responses for normal empty-body GET requests. Use query binding with ShouldBindQuery and form tags for these filter DTOs instead.
🤖 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 241 - 248, The GET
endpoint handler is using ShouldBindJSON to parse request bodies, but GET
requests should use query parameters instead. Replace the ShouldBindJSON call
with ShouldBindQuery, and update the request DTO struct tags from json tags to
form tags to properly bind query parameters. Ensure the error handling remains
in place but now captures query parameter binding errors instead of JSON body
errors.
| pageIndexStr := c.Param("page") | ||
| if pageIndexStr != "" { | ||
| pageIndex, err = strconv.Atoi(pageIndexStr) | ||
| if err != nil { | ||
| errorResponse(c, "Page index must be an integer", 400) | ||
| return | ||
| } | ||
| } | ||
| pageSize := 10 | ||
| pageSizeStr := c.Param("page_size") | ||
| if pageSizeStr != "" { | ||
| pageSize, err = strconv.Atoi(pageSizeStr) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Routes without path pagination params
rg -n 'GET\("/users/(reports|storage|documents|index|quota)"' internal/admin/router.go
# Handler usage of path params for pagination
rg -n 'c\.Param\("page"\)|c\.Param\("page_size"\)|c\.Param\("top"\)' internal/admin/enterprise_handler.goRepository: infiniflow/ragflow
Length of output: 898
Pagination parameters are read from undefined path params; they will always be empty.
These handlers read c.Param("page"), c.Param("page_size"), and c.Param("top") from the URL path, but the registered routes (/users/reports, /users/storage, /users/documents, /users/index, /users/quota) do not include :page, :page_size, or :top path parameters. The c.Param() calls will always return empty strings, causing pagination logic to silently use default values and ignore caller-supplied pagination parameters.
Also applies to: 498-509, 516-517, 542-553, 560-561, 586-597, 604-605, 645-656, 663-664
🤖 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 462 - 473, The pagination
parameters page, page_size, and top are being incorrectly read from URL path
parameters using c.Param() calls, but the registered routes do not define these
as path parameters (such as :page, :page_size, :top), causing them to always
return empty strings and silently ignore the caller's pagination inputs. Replace
all c.Param("page"), c.Param("page_size"), and c.Param("top") calls with their
c.Query() equivalents throughout the handler to read these values from query
string parameters instead. This applies to the pageIndexStr assignment, pageSize
assignment, and topStr assignment in all affected locations across the file.
| if topStr != "" { | ||
| top, err = strconv.Atoi(topStr) | ||
| if err != nil { | ||
| errorResponse(c, "Top must be an integer", 400) | ||
| } | ||
| } |
There was a problem hiding this comment.
Return is missing after top parse failures.
On invalid top, errorResponse(...) is called but execution continues. This can produce a second write path (service call + success response) after an error was already emitted.
Suggested fix (apply to all four handlers)
if topStr != "" {
top, err = strconv.Atoi(topStr)
if err != nil {
errorResponse(c, "Top must be an integer", 400)
+ return
}
}Also applies to: 561-566, 605-610, 664-669
🤖 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 517 - 522, When
strconv.Atoi(topStr) fails and errorResponse is called in the top parameter
validation block, add a return statement immediately after the errorResponse
call to prevent further execution. This applies to all four occurrences: the
initial one around line 517-522, and three additional instances at lines
561-566, 605-610, and 664-669 where similar top parameter parsing occurs.
Without the return statement, the function continues executing after sending the
error response, potentially causing a second response write or unintended
service call.
| func (s *Service) ListRoles() ([]map[string]interface{}, error) { | ||
| // TODO: Implement list roles | ||
| return []map[string]interface{}{}, nil | ||
| } |
There was a problem hiding this comment.
Role and permission endpoints currently succeed without doing any real work.
These methods are TODO stubs that return nil/empty success values. As wired, create/update/delete/grant/revoke can report success while leaving role/permission state unchanged.
Also applies to: 34-37, 40-43, 46-49, 52-55, 58-61, 64-67, 70-73
🤖 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 28 - 31, The methods
ListRoles, and all other role and permission management methods in the Service
type (create, update, delete, grant, revoke operations) are currently TODO stub
implementations that return success without performing any actual work. Replace
each stub implementation with proper business logic that actually executes the
intended operation such as querying a database, modifying role/permission state,
or validating inputs before returning appropriate results or errors. Ensure that
these methods no longer report success when no work has been performed.
| switch p.curToken.Type { | ||
| case TokenActivity: | ||
| return p.parseAdminShowActivityCommand(userName) | ||
| case TokenSummary: | ||
| return p.parseAdminShowUserSummaryCommand(userName) | ||
| case TokenDataset: | ||
| return p.parseAdminShowUserDataSetCommand(userName) | ||
| case TokenStorage: | ||
| return p.parseAdminShowUserStorageCommand(userName) | ||
| case TokenQuota: | ||
| return p.parseAdminShowUserQuotaCommand(userName) | ||
| case TokenIndex: | ||
| return p.parseAdminShowUserIndexCommand(userName) | ||
| case TokenPermission: | ||
| return p.parseAdminShowUserPermissionCommand(userName) | ||
| default: | ||
| return p.parseAdminShowUserInfoCommand(userName) | ||
| } |
There was a problem hiding this comment.
Reject unknown SHOW USER suffixes instead of falling back to user info.
SHOW USER 'a' STORAG currently returns the basic info command because every unrecognized token hits the default branch. Only EOF/semicolon should use the info command.
Suggested fix
switch p.curToken.Type {
case TokenActivity:
return p.parseAdminShowActivityCommand(userName)
case TokenSummary:
return p.parseAdminShowUserSummaryCommand(userName)
case TokenDataset:
return p.parseAdminShowUserDataSetCommand(userName)
case TokenStorage:
return p.parseAdminShowUserStorageCommand(userName)
case TokenQuota:
return p.parseAdminShowUserQuotaCommand(userName)
case TokenIndex:
return p.parseAdminShowUserIndexCommand(userName)
case TokenPermission:
return p.parseAdminShowUserPermissionCommand(userName)
+ case TokenSemicolon, TokenEOF:
+ return p.parseAdminShowUserInfoCommand(userName)
default:
- return p.parseAdminShowUserInfoCommand(userName)
+ return nil, fmt.Errorf("unknown SHOW USER option: %s", p.curToken.Value)
}
}📝 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.
| switch p.curToken.Type { | |
| case TokenActivity: | |
| return p.parseAdminShowActivityCommand(userName) | |
| case TokenSummary: | |
| return p.parseAdminShowUserSummaryCommand(userName) | |
| case TokenDataset: | |
| return p.parseAdminShowUserDataSetCommand(userName) | |
| case TokenStorage: | |
| return p.parseAdminShowUserStorageCommand(userName) | |
| case TokenQuota: | |
| return p.parseAdminShowUserQuotaCommand(userName) | |
| case TokenIndex: | |
| return p.parseAdminShowUserIndexCommand(userName) | |
| case TokenPermission: | |
| return p.parseAdminShowUserPermissionCommand(userName) | |
| default: | |
| return p.parseAdminShowUserInfoCommand(userName) | |
| } | |
| switch p.curToken.Type { | |
| case TokenActivity: | |
| return p.parseAdminShowActivityCommand(userName) | |
| case TokenSummary: | |
| return p.parseAdminShowUserSummaryCommand(userName) | |
| case TokenDataset: | |
| return p.parseAdminShowUserDataSetCommand(userName) | |
| case TokenStorage: | |
| return p.parseAdminShowUserStorageCommand(userName) | |
| case TokenQuota: | |
| return p.parseAdminShowUserQuotaCommand(userName) | |
| case TokenIndex: | |
| return p.parseAdminShowUserIndexCommand(userName) | |
| case TokenPermission: | |
| return p.parseAdminShowUserPermissionCommand(userName) | |
| case TokenSemicolon, TokenEOF: | |
| return p.parseAdminShowUserInfoCommand(userName) | |
| default: | |
| return nil, fmt.Errorf("unknown SHOW USER option: %s", p.curToken.Value) | |
| } |
🤖 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 1951 - 1968, The default case in
the switch statement checking p.curToken.Type currently accepts any unrecognized
token by falling back to parseAdminShowUserInfoCommand, which silently ignores
typos or invalid suffixes like STORAG. Modify the default case to check if the
current token is EOF or a semicolon before calling
parseAdminShowUserInfoCommand; for any other unrecognized token, return an
appropriate parse error instead of silently accepting the invalid command.
| case TokenTop: | ||
| p.nextToken() | ||
| top, err = p.parseNumber() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if top < 0 { | ||
| return nil, fmt.Errorf("invalid number of TOP") | ||
| } | ||
| case TokenQuota: | ||
| p.nextToken() | ||
| quota, err = p.parseNumber() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if quota < 0 { | ||
| return nil, fmt.Errorf("invalid number of QUOTA") | ||
| } |
There was a problem hiding this comment.
Advance after numeric quota options so later filters are parsed.
For LIST USERS QUOTA 100 TOP 10, parseNumber() leaves the current token on the number, so the loop exits before seeing TOP. Add p.nextToken() after parsing TOP and QUOTA, matching the DAYS branch.
Suggested fix
case TokenTop:
p.nextToken()
top, err = p.parseNumber()
if err != nil {
return nil, err
}
if top < 0 {
return nil, fmt.Errorf("invalid number of TOP")
}
+ p.nextToken()
case TokenQuota:
p.nextToken()
quota, err = p.parseNumber()
if err != nil {
return nil, err
}
if quota < 0 {
return nil, fmt.Errorf("invalid number of QUOTA")
}
+ p.nextToken()📝 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.
| case TokenTop: | |
| p.nextToken() | |
| top, err = p.parseNumber() | |
| if err != nil { | |
| return nil, err | |
| } | |
| if top < 0 { | |
| return nil, fmt.Errorf("invalid number of TOP") | |
| } | |
| case TokenQuota: | |
| p.nextToken() | |
| quota, err = p.parseNumber() | |
| if err != nil { | |
| return nil, err | |
| } | |
| if quota < 0 { | |
| return nil, fmt.Errorf("invalid number of QUOTA") | |
| } | |
| case TokenTop: | |
| p.nextToken() | |
| top, err = p.parseNumber() | |
| if err != nil { | |
| return nil, err | |
| } | |
| if top < 0 { | |
| return nil, fmt.Errorf("invalid number of TOP") | |
| } | |
| p.nextToken() | |
| case TokenQuota: | |
| p.nextToken() | |
| quota, err = p.parseNumber() | |
| if err != nil { | |
| return nil, err | |
| } | |
| if quota < 0 { | |
| return nil, fmt.Errorf("invalid number of QUOTA") | |
| } | |
| p.nextToken() |
🤖 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 2384 - 2401, After parsing numeric
values in the TokenTop and TokenQuota cases, the parser does not advance to the
next token, which prevents subsequent options from being parsed. Add
p.nextToken() calls after the p.parseNumber() statement in both the TokenTop
case and TokenQuota case to advance the token pointer, matching the pattern used
in the DAYS branch so that options following TOP or QUOTA can be correctly
parsed in the loop.
| func (p *Parser) parseAdminPurgeUsersCommand(preview bool) (*Command, error) { | ||
| p.nextToken() // consume USERS | ||
|
|
||
| var userStatus *string = nil | ||
| var days *int = nil | ||
| var planName *string = nil | ||
|
|
||
| commandLoop: | ||
| for { | ||
| switch p.curToken.Type { | ||
| case TokenPlan: | ||
| p.nextToken() | ||
| if planName != nil { | ||
| return nil, fmt.Errorf("duplicate PLAN after USERS") | ||
| } | ||
| plan, err := p.parseQuotedString() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| planName = &plan | ||
| p.nextToken() | ||
| case TokenDays: | ||
| p.nextToken() | ||
| if days != nil { | ||
| return nil, fmt.Errorf("duplicate DAYS after USERS") | ||
| } | ||
| dayCount, err := p.parseNumber() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| days = &dayCount | ||
| p.nextToken() | ||
| case TokenInactive: | ||
| p.nextToken() | ||
| if userStatus != nil { | ||
| return nil, fmt.Errorf("duplicate INACTIVE or ACTIVE after USERS") | ||
| } | ||
| inactiveStatus := "inactive" | ||
| userStatus = &inactiveStatus | ||
| case TokenActive: | ||
| p.nextToken() | ||
| if userStatus != nil { | ||
| return nil, fmt.Errorf("duplicate INACTIVE or ACTIVE after USERS") | ||
| } | ||
| activeStatus := "active" | ||
| userStatus = &activeStatus | ||
| case TokenSemicolon: | ||
| p.nextToken() | ||
| break commandLoop // done | ||
| default: | ||
| // No more options to process | ||
| break commandLoop | ||
| } | ||
| } | ||
|
|
||
| cmd := NewCommand("admin_purge_users_command") | ||
| cmd.Params["preview"] = preview | ||
| if planName != nil { | ||
| cmd.Params["plan_name"] = *planName | ||
| } | ||
| if userStatus != nil { | ||
| cmd.Params["user_status"] = *userStatus | ||
| } | ||
| if days != nil { | ||
| cmd.Params["days"] = *days | ||
| } |
There was a problem hiding this comment.
Require bulk-purge safeguards before building the command.
PURGE USERS currently accepts missing PLAN, missing DAYS, and DAYS 0; the handler then either errors late or can send an under-constrained destructive request. Enforce PLAN and positive DAYS in the parser to match the documented bulk purge shape.
Suggested fix
case TokenDays:
p.nextToken()
if days != nil {
return nil, fmt.Errorf("duplicate DAYS after USERS")
}
dayCount, err := p.parseNumber()
if err != nil {
return nil, err
}
+ if dayCount < 1 {
+ return nil, fmt.Errorf("invalid number of DAYS")
+ }
days = &dayCount
p.nextToken()
@@
}
}
+ if planName == nil {
+ return nil, fmt.Errorf("PLAN is required after USERS")
+ }
+ if days == nil {
+ return nil, fmt.Errorf("DAYS is required after USERS")
+ }
+
cmd := NewCommand("admin_purge_users_command")
📝 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 (p *Parser) parseAdminPurgeUsersCommand(preview bool) (*Command, error) { | |
| p.nextToken() // consume USERS | |
| var userStatus *string = nil | |
| var days *int = nil | |
| var planName *string = nil | |
| commandLoop: | |
| for { | |
| switch p.curToken.Type { | |
| case TokenPlan: | |
| p.nextToken() | |
| if planName != nil { | |
| return nil, fmt.Errorf("duplicate PLAN after USERS") | |
| } | |
| plan, err := p.parseQuotedString() | |
| if err != nil { | |
| return nil, err | |
| } | |
| planName = &plan | |
| p.nextToken() | |
| case TokenDays: | |
| p.nextToken() | |
| if days != nil { | |
| return nil, fmt.Errorf("duplicate DAYS after USERS") | |
| } | |
| dayCount, err := p.parseNumber() | |
| if err != nil { | |
| return nil, err | |
| } | |
| days = &dayCount | |
| p.nextToken() | |
| case TokenInactive: | |
| p.nextToken() | |
| if userStatus != nil { | |
| return nil, fmt.Errorf("duplicate INACTIVE or ACTIVE after USERS") | |
| } | |
| inactiveStatus := "inactive" | |
| userStatus = &inactiveStatus | |
| case TokenActive: | |
| p.nextToken() | |
| if userStatus != nil { | |
| return nil, fmt.Errorf("duplicate INACTIVE or ACTIVE after USERS") | |
| } | |
| activeStatus := "active" | |
| userStatus = &activeStatus | |
| case TokenSemicolon: | |
| p.nextToken() | |
| break commandLoop // done | |
| default: | |
| // No more options to process | |
| break commandLoop | |
| } | |
| } | |
| cmd := NewCommand("admin_purge_users_command") | |
| cmd.Params["preview"] = preview | |
| if planName != nil { | |
| cmd.Params["plan_name"] = *planName | |
| } | |
| if userStatus != nil { | |
| cmd.Params["user_status"] = *userStatus | |
| } | |
| if days != nil { | |
| cmd.Params["days"] = *days | |
| } | |
| func (p *Parser) parseAdminPurgeUsersCommand(preview bool) (*Command, error) { | |
| p.nextToken() // consume USERS | |
| var userStatus *string = nil | |
| var days *int = nil | |
| var planName *string = nil | |
| commandLoop: | |
| for { | |
| switch p.curToken.Type { | |
| case TokenPlan: | |
| p.nextToken() | |
| if planName != nil { | |
| return nil, fmt.Errorf("duplicate PLAN after USERS") | |
| } | |
| plan, err := p.parseQuotedString() | |
| if err != nil { | |
| return nil, err | |
| } | |
| planName = &plan | |
| p.nextToken() | |
| case TokenDays: | |
| p.nextToken() | |
| if days != nil { | |
| return nil, fmt.Errorf("duplicate DAYS after USERS") | |
| } | |
| dayCount, err := p.parseNumber() | |
| if err != nil { | |
| return nil, err | |
| } | |
| if dayCount < 1 { | |
| return nil, fmt.Errorf("invalid number of DAYS") | |
| } | |
| days = &dayCount | |
| p.nextToken() | |
| case TokenInactive: | |
| p.nextToken() | |
| if userStatus != nil { | |
| return nil, fmt.Errorf("duplicate INACTIVE or ACTIVE after USERS") | |
| } | |
| inactiveStatus := "inactive" | |
| userStatus = &inactiveStatus | |
| case TokenActive: | |
| p.nextToken() | |
| if userStatus != nil { | |
| return nil, fmt.Errorf("duplicate INACTIVE or ACTIVE after USERS") | |
| } | |
| activeStatus := "active" | |
| userStatus = &activeStatus | |
| case TokenSemicolon: | |
| p.nextToken() | |
| break commandLoop // done | |
| default: | |
| // No more options to process | |
| break commandLoop | |
| } | |
| } | |
| if planName == nil { | |
| return nil, fmt.Errorf("PLAN is required after USERS") | |
| } | |
| if days == nil { | |
| return nil, fmt.Errorf("DAYS is required after USERS") | |
| } | |
| cmd := NewCommand("admin_purge_users_command") | |
| cmd.Params["preview"] = preview | |
| if planName != nil { | |
| cmd.Params["plan_name"] = *planName | |
| } | |
| if userStatus != nil { | |
| cmd.Params["user_status"] = *userStatus | |
| } | |
| if days != nil { | |
| cmd.Params["days"] = *days | |
| } |
🤖 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 2562 - 2627, The
parseAdminPurgeUsersCommand function does not validate that required parameters
are provided before building the command. After the command parsing loop ends
(after the commandLoop label), add validation checks to ensure that planName is
not nil (PLAN was provided), days is not nil (DAYS was provided), and days is
greater than zero (positive value). Return an appropriate error message for any
validation failure before constructing and returning the Command object. This
ensures that destructive bulk-purge operations cannot proceed without both a
plan constraint and a positive day threshold, matching the documented bulk purge
requirements.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16119 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Signed-off-by: Jin Hai <[email protected]>
What problem does this PR solve?
Type of change