Skip to content

Go: add statistics command - #16119

Merged
JinHai-CN merged 6 commits into
infiniflow:mainfrom
JinHai-CN:fix468
Jun 18, 2026
Merged

JinHai-CN merged 6 commits into
infiniflow:mainfrom
JinHai-CN:fix468

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Jun 17, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

RAGFlow(admin)>  show user '[email protected]' activity days 14;
+----------+-----------------------------------------------------------+
| field    | value                                                     |
+----------+-----------------------------------------------------------+
| days     | 14                                                        |
| email    | [email protected]                                               |
| error    | 'show user activity' is implemented in enterprise edition |
| nickname | aaa                                                       |
+----------+-----------------------------------------------------------+

RAGFlow(admin)> show user '[email protected]' dataset 'aaa';
+----------+------------------------------------------------------------------+
| field    | value                                                            |
+----------+------------------------------------------------------------------+
| email    | [email protected]                                                      |
| error    | 'show user dataset summary' is implemented in enterprise edition |
| nickname | aaa                                                              |
| dataset  | aaa                                                              |
+----------+------------------------------------------------------------------+

RAGFlow(admin)> show user '[email protected]' summary;
+----------+----------------------------------------------------------+
| field    | value                                                    |
+----------+----------------------------------------------------------+
| email    | [email protected]                                              |
| error    | 'show user summary' is implemented in enterprise edition |
| nickname | aaa                                                      |
+----------+----------------------------------------------------------+

RAGFlow(admin)> show user '[email protected]';
+-------------+----------------------------------+
| field       | value                            |
+-------------+----------------------------------+
| id          | 2ba4881420fa11f19e9c38a74640adcc |
| is_active   | 1                                |
| nickname    | aaa                              |
| update_time | 1781605542868                    |
| create_time | 1773639427212                    |
| email       | [email protected]                      |
+-------------+----------------------------------+

RAGFlow(admin)> show user '[email protected]' storage;
+----------+----------------------------------------------------------+
| field    | value                                                    |
+----------+----------------------------------------------------------+
| email    | [email protected]                                              |
| error    | 'show user storage' is implemented in enterprise edition |
| nickname | aaa                                                      |
+----------+----------------------------------------------------------

RAGFlow(admin)> show user '[email protected]' quota;
+----------+--------------------------------------------------------+
| field    | value                                                  |
+----------+--------------------------------------------------------+
| error    | 'show user quota' is implemented in enterprise edition |
| nickname | aaa                                                    |
| email    | [email protected]                                            |
+----------+--------------------------------------------------------+

RAGFlow(admin)> show user '[email protected]' index;
+----------+--------------------------------------------------------+
| field    | value                                                  |
+----------+--------------------------------------------------------+
| email    | [email protected]                                            |
| error    | 'show user index' is implemented in enterprise edition |
| nickname | aaa                                                    |
+----------+--------------------------------------------------------+

RAGFlow(admin)> show users summary;
+---------+-----------------------------------------------------------+
| field   | value                                                     |
+---------+-----------------------------------------------------------+
| command | show_users_summary                                        |
| error   | 'show users summary' is implemented in enterprise edition |
+---------+-----------------------------------------------------------+
RAGFlow(admin)> show users activity days 10 window 5;
+---------+------------------------------------------------------------+
| field   | value                                                      |
+---------+------------------------------------------------------------+
| command | show_users_activity                                        |
| days    | 10                                                         |
| error   | 'show users activity' is implemented in enterprise edition |
| windows | 5                                                          |
+---------+------------------------------------------------------------+

RAGFlow(admin)> PURGE PREVIEW ORPHAN;
+---------+----------------------------------------------------------+
| field   | value                                                    |
+---------+----------------------------------------------------------+
| command | purge_orphan_data                                        |
| error   | 'Purge orphan data' is implemented in enterprise edition |
| preview | true                                                     |
+---------+----------------------------------------------------------+
RAGFlow(admin)> purge orphan;
+---------+----------------------------------------------------------+
| field   | value                                                    |
+---------+----------------------------------------------------------+
| command | purge_orphan_data                                        |
| error   | 'Purge orphan data' is implemented in enterprise edition |
| preview | false                                                    |
+---------+----------------------------------------------------------+
RAGFlow(admin)> PURGE PREVIEW USER '[email protected]';
+----------+--------------------------------------------------------+
| field    | value                                                  |
+----------+--------------------------------------------------------+
| error    | 'Purge user data' is implemented in enterprise edition |
| nickname | aaa                                                    |
| preview  | true                                                   |
| email    | [email protected]                                            |
+----------+--------------------------------------------------------+
RAGFlow(admin)> PURGE USER '[email protected]';
+----------+--------------------------------------------------------+
| field    | value                                                  |
+----------+--------------------------------------------------------+
| email    | [email protected]                                            |
| error    | 'Purge user data' is implemented in enterprise edition |
| nickname | aaa                                                    |
| preview  | false                                                  |
+----------+--------------------------------------------------------+
RAGFlow(admin)> PURGE PREVIEW USERS PLAN 'plan_name' DAYS 30;
+----------+---------------------------------------------------------+
| field    | value                                                   |
+----------+---------------------------------------------------------+
| plan     | plan_name                                               |
| preview  | true                                                    |
| activity | all                                                     |
| command  | purge_users_data                                        |
| days     | 30                                                      |
| error    | 'Purge users data' is implemented in enterprise edition |
+----------+---------------------------------------------------------+
RAGFlow(admin)> PURGE USERS PLAN 'plan_name' DAYS 30;
+----------+---------------------------------------------------------+
| field    | value                                                   |
+----------+---------------------------------------------------------+
| activity | all                                                     |
| command  | purge_users_data                                        |
| days     | 30                                                      |
| error    | 'Purge users data' is implemented in enterprise edition |
| plan     | plan_name                                               |
| preview  | false                                                   |
+----------+---------------------------------------------------------+
RAGFlow(admin)> PURGE PREVIEW USERS INACTIVE PLAN 'plan_name' DAYS 30;
+----------+---------------------------------------------------------+
| field    | value                                                   |
+----------+---------------------------------------------------------+
| days     | 30                                                      |
| error    | 'Purge users data' is implemented in enterprise edition |
| plan     | plan_name                                               |
| preview  | true                                                    |
| activity | inactive                                                |
| command  | purge_users_data                                        |
+----------+---------------------------------------------------------+
RAGFlow(admin)> PURGE USERS INACTIVE PLAN 'plan_name' DAYS 30;
+----------+---------------------------------------------------------+
| field    | value                                                   |
+----------+---------------------------------------------------------+
| activity | inactive                                                |
| command  | purge_users_data                                        |
| days     | 30                                                      |
| error    | 'Purge users data' is implemented in enterprise edition |
| plan     | plan_name                                               |
| preview  | false                                                   |
+----------+---------------------------------------------------------+
RAGFlow(admin)> list users inactive top 10 days 5 quota 30 plan 'trial';
+------+-------+-------+----------+-----+
| days | plan  | quota | status   | top |
+------+-------+-------+----------+-----+
| 5    | trial | 30    | inactive | 10  |
+------+-------+-------+----------+-----+

Type of change

  • New Feature (non-breaking change which adds functionality)

@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cef5f81f-d799-4eba-9364-5daac46b3c05

📥 Commits

Reviewing files that changed from the base of the PR and between 3ee4a63 and 08bac92.

📒 Files selected for processing (6)
  • internal/admin/enterprise_service.go
  • internal/admin/handler.go
  • internal/admin/service.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go

📝 Walkthrough

Walkthrough

Adds 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 handler.go/service.go, extends the CLI lexer/parser infrastructure with ~14 new keywords and dedicated sub-parsers, and wires ~27 new CLI command handlers into the admin dispatcher.

Enterprise Admin HTTP Layer

Layer / File(s) Summary
Role management handlers and service stubs
internal/admin/enterprise_handler.go, internal/admin/enterprise_service.go, internal/admin/handler.go, internal/admin/service.go
Implements role CRUD and permission grant/revoke handlers in enterprise_handler.go with request DTOs; adds corresponding service stubs in enterprise_service.go returning empty results; removes equivalent implementations from handler.go and service.go.
Per-user and aggregate user handlers with service lookups
internal/admin/enterprise_handler.go, internal/admin/enterprise_service.go
Adds handlers for per-user show endpoints (activity, dataset, summary, storage, quota, index, role update, permission) and aggregate list endpoints (reports, storage, documents, index, quota, summary); service methods look up users by email via dao.DB returning ErrUserNotFound or parameterized response maps with normalized optional filters.
Data visibility and purge handlers with service
internal/admin/enterprise_handler.go, internal/admin/enterprise_service.go
Implements handlers and service methods for data summary, orphan, storage, and index; adds three purge variants (orphan, single user, bulk users) accepting a preview flag and performing email lookup or filter normalization.
Router registration, ListUsers pagination, and base service update
internal/admin/router.go, internal/admin/handler.go, internal/admin/service.go
Routes all new enterprise endpoints; removes duplicate role route pair; updates ListUsers to accept pagination parameters and conditionally dispatch to enterprise or basic list based on JSON binding.

CLI Enterprise Command Expansion

Layer / File(s) Summary
Token constants, lexer keywords, and parser dispatch
internal/cli/types.go, internal/cli/lexer.go, internal/cli/parser.go
Adds TokenInactive and 13 new token constants into the iota sequence; extends lookupIdent to recognize 14 new reserved keywords; adds TokenPurge dispatch to parseAdminPurgeCommand.
Admin and user parser refactoring with new sub-parsers
internal/cli/admin_parser.go, internal/cli/user_parser.go
Refactors parseAdminListCommand and parseAdminShowCommand to delegate to 8 specialized sub-parsers for VERSION/CURRENT/ROLE/USER/USERS/DATA/QUOTA/PURGE with optional-clause loops; removes parseShowUser/parseShowRole implementations from user_parser.go; adjusts SHOW CURRENT control flow.
Admin CLI command implementations (user, data, purge)
internal/cli/admin_command.go
Removes ListUsers and ShowUser; adds 26 new Admin*Command handlers covering per-user info/activity/summary/dataset/storage/quota/index/permission, enterprise-wide user/data visibility, quota summary, and purge operations; each handler enforces admin-mode checks, constructs HTTP requests, and unmarshals responses.
ExecuteAdminCommand dispatcher wiring
internal/cli/cli_http.go
Removes list_users and show_user switch cases; adds ~27 new cases routing admin_show_*, admin_list_*, and admin_purge_* command strings to handler methods.

🎯 4 (Complex) | ⏱️ ~60 minutes

💞 feature

🐇 Hop hop, the admin grows!
New commands sprout in tidy rows,
PURGE and QUOTA, ORPHAN too,
Enterprise edition shines brand new.
The lexer learns its keywords well—
What tales these token constants tell! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description fails to follow the required template structure with a concise problem statement and explicit type-of-change selection. Add a brief 'What problem does this PR solve?' section explaining the business/user problem being addressed, and ensure the type-of-change checkboxes are clearly marked.
Title check ❓ Inconclusive The title 'Go: add statistics command' is vague and overly broad, failing to accurately describe the substantial changes made across multiple files for admin/enterprise functionality. Consider a more specific title such as 'Add admin enterprise statistics and data management commands' to clearly reflect the scope and primary purpose of the changes.
✅ Passed checks (3 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 18, 2026 06:13
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jun 18, 2026
@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 18, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft June 18, 2026 06:13
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 18, 2026 06:14

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between a902152 and 3ee4a63.

📒 Files selected for processing (12)
  • internal/admin/enterprise_handler.go
  • internal/admin/enterprise_service.go
  • internal/admin/handler.go
  • internal/admin/router.go
  • internal/admin/service.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/types.go
  • internal/cli/user_parser.go
💤 Files with no reviewable changes (3)
  • internal/admin/handler.go
  • internal/admin/service.go
  • internal/cli/user_parser.go

Comment on lines +211 to +221
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 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.go

Repository: 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.

Comment on lines +241 to +248
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 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 -5

Repository: 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.go

Repository: 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.go

Repository: 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.go

Repository: 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 -20

Repository: 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.go

Repository: infiniflow/ragflow

Length of output: 785


🏁 Script executed:

# Check lines around 421-428
sed -n '415,435p' internal/admin/enterprise_handler.go

Repository: infiniflow/ragflow

Length of output: 674


🏁 Script executed:

# Check lines around 451-458
sed -n '445,465p' internal/admin/enterprise_handler.go

Repository: infiniflow/ragflow

Length of output: 595


🏁 Script executed:

# Check lines around 634-641
sed -n '628,648p' internal/admin/enterprise_handler.go

Repository: 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 -5

Repository: 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.go

Repository: 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.go

Repository: 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.

Comment on lines +462 to +473
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 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.go

Repository: 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.

Comment on lines +517 to +522
if topStr != "" {
top, err = strconv.Atoi(topStr)
if err != nil {
errorResponse(c, "Top must be an integer", 400)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment on lines +28 to +31
func (s *Service) ListRoles() ([]map[string]interface{}, error) {
// TODO: Implement list roles
return []map[string]interface{}{}, nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy lift

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.

Comment thread internal/cli/admin_command.go Resolved
Comment on lines +1951 to +1968
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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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.

Comment thread internal/cli/admin_parser.go Resolved
Comment on lines +2384 to +2401
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")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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.

Comment on lines +2562 to +2627
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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

codecov Bot commented Jun 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (a902152) to head (3ee4a63).
⚠️ Report is 2 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant