Repository navigation
Go CLI: refactor - #16355
Go CLI: refactor#16355
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:
📝 WalkthroughWalkthroughAPI-specific CLI commands now cover reset, show-log, list, and variable operations. System handlers, services, and routes add variable management and environment listing endpoints, with shared system-setting helpers used across admin and service code. ChangesCLI command parsing and routing
System settings API
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✅ Passed checks (2 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 |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/cli/user_parser.go (1)
2072-2121: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick winEmit the API reset command type from the reset parser.
parseAPIResetCommandsnow routes API user resets here, butparseAPIResetDefaultModelstill createsreset_default_modelwhileExecuteUserCommandonly handlesapi_reset_default_model.RESET DEFAULT ... MODELwill fall through as an unknown API command.🐛 Proposed fix
- cmd := NewCommand("reset_default_model") + cmd := NewCommand("api_reset_default_model")🤖 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/user_parser.go` around lines 2072 - 2121, The reset parser is emitting a command name that does not match what execution handles, so API reset default model commands are treated as unknown. Update parseAPIResetDefaultModel (and any related reset command construction in parseAPIResetCommands) to create the same command type that ExecuteUserCommand expects, namely api_reset_default_model. Keep the existing token parsing for DEFAULT, model type, and MODEL unchanged, and ensure the returned Command.Params["model_type"] still carries the parsed type.
🤖 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.
Outside diff comments:
In `@internal/cli/user_parser.go`:
- Around line 2072-2121: The reset parser is emitting a command name that does
not match what execution handles, so API reset default model commands are
treated as unknown. Update parseAPIResetDefaultModel (and any related reset
command construction in parseAPIResetCommands) to create the same command type
that ExecuteUserCommand expects, namely api_reset_default_model. Keep the
existing token parsing for DEFAULT, model type, and MODEL unchanged, and ensure
the returned Command.Params["model_type"] still carries the parsed type.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 5f7de70d-1b3e-4071-b324-fb8745492887
📒 Files selected for processing (4)
internal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/parser.gointernal/cli/user_parser.go
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/cli/user_parser.go (1)
3593-3624: 🎯 Functional Correctness | 🔴 CriticalUNSET KEY syntax is broken due to missing case in parseUserStatement
While
RESET KEYis correctly routed viaTokenResetinparser.gotoapi_unset_api_key, the legacyUNSETkeyword falls through to the default error case.TokenUnsetis missing from the user statement switch ininternal/cli/user_parser.go, causingUNSET KEYto fail with "invalid user statement".Add
case TokenUnset: return p.parseAPIResetKey()to maintain backward compatibility with the legacy syntax.🤖 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/user_parser.go` around lines 3593 - 3624, The user statement dispatcher in parseUserStatement is missing support for the legacy UNSET keyword, so UNSET KEY falls into the default invalid user statement path. Add a TokenUnset branch in Parser.parseUserStatement that routes to the same API key reset handler used by RESET KEY, reusing parseAPIResetKey to preserve backward compatibility while keeping the existing token-based dispatch structure intact.
🤖 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.
Outside diff comments:
In `@internal/cli/user_parser.go`:
- Around line 3593-3624: The user statement dispatcher in parseUserStatement is
missing support for the legacy UNSET keyword, so UNSET KEY falls into the
default invalid user statement path. Add a TokenUnset branch in
Parser.parseUserStatement that routes to the same API key reset handler used by
RESET KEY, reusing parseAPIResetKey to preserve backward compatibility while
keeping the existing token-based dispatch structure intact.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 0bea5f6f-e55a-4da6-a1d9-f5436dfa227d
📒 Files selected for processing (1)
internal/cli/user_parser.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16355 +/- ##
=======================================
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]>
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
internal/handler/system.go (1)
230-233: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse the shared response-code constants instead of magic numbers.
The sibling handler
SetLogLevel(Line 201) usescommon.CodeDataError, but these new handlers hardcode500and400. Align with the existingcommon.Code*constants for consistency across the API surface.Also applies to: 256-257, 280-281, 296-298
🤖 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/handler/system.go` around lines 230 - 233, The new handler responses are hardcoding numeric codes instead of using the shared common.Code* constants, which makes them inconsistent with SetLogLevel and the rest of the API. Update the JSON payloads in the affected handler methods in system.go to use the appropriate shared response-code constants from common (for example, the same pattern used by SetLogLevel) rather than literal 500 or 400 values, and apply the same change to all listed response sites.internal/service/system.go (1)
395-423: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff
SystemService.SetVariableduplicatesadmin.Service.SetVariableverbatim.This method (and
ListAllVariables/ListEnvironmentsbelow) are near-identical copies of the implementations ininternal/admin/service.go. The only deltas are the error constructor (fmt.ErrorfvsNewAdminException). Since both now delegate to the samecommon.*helpers, consider extracting the shared body into a common helper that takes the DAO + an error formatter, to avoid the two copies drifting over time.🤖 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/service/system.go` around lines 395 - 423, SystemService.SetVariable is a near-verbatim copy of admin.Service.SetVariable, so the logic can drift between the two implementations. Extract the shared variable-update flow into a common helper that takes the DAO and an error-construction callback, then have both SystemService.SetVariable and admin.Service.SetVariable delegate to it while preserving their different error types. Keep the common validation/create/update path in one place and reuse the existing common.ValidateSystemSettingValue and common.InferSystemSettingDataType calls.
🤖 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/user_command.go`:
- Around line 3415-3417: The JSON unmarshal error message in
APIListVariablesCommand is using the wrong operation name, which makes
troubleshooting confusing. Update the fmt.Errorf text in the variables command
path so it refers to listing variables rather than listing environments, keeping
the existing unmarshal failure context and err wrapping intact. Use the
APIListVariablesCommand and json.Unmarshal flow to locate the message.
In `@internal/handler/system.go`:
- Around line 252-276: In SystemHandler.SetVariable, the explicit empty-string
validation for req.VarName and req.VarValue is redundant because
binding:"required" already makes ShouldBindJSON reject missing/empty values;
remove those unreachable branches and keep validation in one place. Also update
the ShouldBindJSON error response so it reports a bind/validation failure
generically or with the correct field context, instead of always returning "Var
name is required".
In `@internal/service/system.go`:
- Around line 437-491: ListEnvironments is duplicating config defaults instead
of using the resolved values, which can drift from the real application
settings. Update SystemService.ListEnvironments to read from the central config
source or resolved config accessor for DOC_ENGINE, DEFAULT_SUPERUSER_EMAIL,
DB_TYPE, DEVICE, and STORAGE_IMPL rather than hardcoding fallbacks. Also review
the route exposure for ListEnvironments in the authorized group and, if
DEFAULT_SUPERUSER_EMAIL should not be visible to all authenticated users,
restrict that field or move the endpoint behind admin-only access.
---
Nitpick comments:
In `@internal/handler/system.go`:
- Around line 230-233: The new handler responses are hardcoding numeric codes
instead of using the shared common.Code* constants, which makes them
inconsistent with SetLogLevel and the rest of the API. Update the JSON payloads
in the affected handler methods in system.go to use the appropriate shared
response-code constants from common (for example, the same pattern used by
SetLogLevel) rather than literal 500 or 400 values, and apply the same change to
all listed response sites.
In `@internal/service/system.go`:
- Around line 395-423: SystemService.SetVariable is a near-verbatim copy of
admin.Service.SetVariable, so the logic can drift between the two
implementations. Extract the shared variable-update flow into a common helper
that takes the DAO and an error-construction callback, then have both
SystemService.SetVariable and admin.Service.SetVariable delegate to it while
preserving their different error types. Keep the common validation/create/update
path in one place and reuse the existing common.ValidateSystemSettingValue and
common.InferSystemSettingDataType calls.
🪄 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: 99792ad4-8140-4464-b4f1-13a21904f7b7
📒 Files selected for processing (8)
internal/admin/service.gointernal/cli/cli_http.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/common/status_message.gointernal/handler/system.gointernal/router/router.gointernal/service/system.go
✅ Files skipped from review due to trivial changes (1)
- internal/common/status_message.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/cli/user_parser.go
| if err = json.Unmarshal(resp.Body, &result); err != nil { | ||
| return nil, fmt.Errorf("list environments failed: invalid JSON (%w)", err) | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Fix mismatched error text in variables command.
The unmarshal error message says “list environments failed” inside APIListVariablesCommand, which is misleading during troubleshooting.
Suggested patch
- return nil, fmt.Errorf("list environments failed: invalid JSON (%w)", err)
+ return nil, fmt.Errorf("list variables 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 = json.Unmarshal(resp.Body, &result); err != nil { | |
| return nil, fmt.Errorf("list environments failed: invalid JSON (%w)", err) | |
| } | |
| if err = json.Unmarshal(resp.Body, &result); err != nil { | |
| return nil, fmt.Errorf("list variables 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/user_command.go` around lines 3415 - 3417, The JSON unmarshal
error message in APIListVariablesCommand is using the wrong operation name,
which makes troubleshooting confusing. Update the fmt.Errorf text in the
variables command path so it refers to listing variables rather than listing
environments, keeping the existing unmarshal failure context and err wrapping
intact. Use the APIListVariablesCommand and json.Unmarshal flow to locate the
message.
| func (h *SystemHandler) SetVariable(c *gin.Context) { | ||
| var req SetVariableHTTPRequest | ||
| if err := c.ShouldBindJSON(&req); err != nil { | ||
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": 400, | ||
| "message": "Var name is required", | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| if req.VarName == "" { | ||
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": 400, | ||
| "message": "Var name is required", | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| if req.VarValue == "" { | ||
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": 400, | ||
| "message": "Var value is required", | ||
| }) | ||
| return | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
binding:"required" makes the explicit empty-string checks unreachable, and the bind-error message is misleading.
With binding:"required" on both fields, ShouldBindJSON already fails for empty/missing var_name or var_value, so the req.VarName == "" / req.VarValue == "" branches at Lines 262-276 can never trigger. Additionally, any bind failure (malformed JSON, or a missing var_value) returns "Var name is required", which is incorrect for those cases.
♻️ Suggested simplification
var req SetVariableHTTPRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 400,
- "message": "Var name is required",
+ "message": "var_name and var_value are required",
})
return
}
-
- if req.VarName == "" {
- c.JSON(http.StatusOK, gin.H{
- "code": 400,
- "message": "Var name is required",
- })
- return
- }
-
- if req.VarValue == "" {
- c.JSON(http.StatusOK, gin.H{
- "code": 400,
- "message": "Var value is required",
- })
- return
- }📝 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 (h *SystemHandler) SetVariable(c *gin.Context) { | |
| var req SetVariableHTTPRequest | |
| if err := c.ShouldBindJSON(&req); err != nil { | |
| c.JSON(http.StatusOK, gin.H{ | |
| "code": 400, | |
| "message": "Var name is required", | |
| }) | |
| return | |
| } | |
| if req.VarName == "" { | |
| c.JSON(http.StatusOK, gin.H{ | |
| "code": 400, | |
| "message": "Var name is required", | |
| }) | |
| return | |
| } | |
| if req.VarValue == "" { | |
| c.JSON(http.StatusOK, gin.H{ | |
| "code": 400, | |
| "message": "Var value is required", | |
| }) | |
| return | |
| } | |
| func (h *SystemHandler) SetVariable(c *gin.Context) { | |
| var req SetVariableHTTPRequest | |
| if err := c.ShouldBindJSON(&req); err != nil { | |
| c.JSON(http.StatusOK, gin.H{ | |
| "code": 400, | |
| "message": "var_name and var_value are required", | |
| }) | |
| 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/handler/system.go` around lines 252 - 276, In
SystemHandler.SetVariable, the explicit empty-string validation for req.VarName
and req.VarValue is redundant because binding:"required" already makes
ShouldBindJSON reject missing/empty values; remove those unreachable branches
and keep validation in one place. Also update the ShouldBindJSON error response
so it reports a bind/validation failure generically or with the correct field
context, instead of always returning "Var name is required".
| func (s *SystemService) ListEnvironments() ([]map[string]interface{}, error) { | ||
| result := make([]map[string]interface{}, 0) | ||
|
|
||
| // DOC_ENGINE | ||
| docEngine := os.Getenv("DOC_ENGINE") | ||
| if docEngine == "" { | ||
| docEngine = "elasticsearch" | ||
| } | ||
| result = append(result, map[string]interface{}{ | ||
| "env": "DOC_ENGINE", | ||
| "value": docEngine, | ||
| }) | ||
|
|
||
| // DEFAULT_SUPERUSER_EMAIL | ||
| defaultSuperuserEmail := os.Getenv("DEFAULT_SUPERUSER_EMAIL") | ||
| if defaultSuperuserEmail == "" { | ||
| defaultSuperuserEmail = "[email protected]" | ||
| } | ||
| result = append(result, map[string]interface{}{ | ||
| "env": "DEFAULT_SUPERUSER_EMAIL", | ||
| "value": defaultSuperuserEmail, | ||
| }) | ||
|
|
||
| // DB_TYPE | ||
| dbType := os.Getenv("DB_TYPE") | ||
| if dbType == "" { | ||
| dbType = "mysql" | ||
| } | ||
| result = append(result, map[string]interface{}{ | ||
| "env": "DB_TYPE", | ||
| "value": dbType, | ||
| }) | ||
|
|
||
| // DEVICE | ||
| device := os.Getenv("DEVICE") | ||
| if device == "" { | ||
| device = "cpu" | ||
| } | ||
| result = append(result, map[string]interface{}{ | ||
| "env": "DEVICE", | ||
| "value": device, | ||
| }) | ||
|
|
||
| // STORAGE_IMPL | ||
| storageImpl := os.Getenv("STORAGE_IMPL") | ||
| if storageImpl == "" { | ||
| storageImpl = "MINIO" | ||
| } | ||
| result = append(result, map[string]interface{}{ | ||
| "env": "STORAGE_IMPL", | ||
| "value": storageImpl, | ||
| }) | ||
|
|
||
| return result, nil | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find where these env vars' real defaults are defined to compare against the literals here.
rg -nP '\b(DOC_ENGINE|DEFAULT_SUPERUSER_EMAIL|DB_TYPE|DEVICE|STORAGE_IMPL)\b' -g '!**/*_test.go' -C2Repository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
# Find the route registration for ListEnvironments to verify the authentication group
grep -rn "ListEnvironments" internal/server/ --include="*.go" | head -20Repository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
# Find route definitions in server routers
find internal/server -name "router.go" -o -name "*router*.go" | xargs grep -n "environments" -i 2>/dev/null | head -20Repository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
# Search for the API handler path registration using the function name as a hint
# Try to find where the handler is wired up, likely in a route definition file or method chaining
grep -rn "GET.*Environments" internal/ --include="*.go" 2>/dev/null || grep -rn "r\.GET.*Environment" internal/ --include="*.go" 2>/dev/null | head -10Repository: infiniflow/ragflow
Length of output: 342
🏁 Script executed:
#!/bin/bash
# Find the route registration for ListEnvironments to verify the authentication group
grep -rn "ListEnvironments" internal/server/ --include="*.go" | head -20Repository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
# Check the router.go file around line 562 to verify the auth middleware used for the environments route
sed -n '550,575p' internal/router/router.goRepository: infiniflow/ragflow
Length of output: 898
🏁 Script executed:
#!/bin/bash
# Check the router.go file context to determine which group 'system' belongs to (public, authorized, or admin)
sed -n '520,565p' internal/router/router.goRepository: infiniflow/ragflow
Length of output: 2101
🏁 Script executed:
#!/bin/bash
# Determine which group 'v1' is and what middleware it has (public vs auth)
# Also check if there's specific logic guarding the environments endpoint elsewhere
sed -n '1,100p' internal/router/router.go | grep -A 5 -B 5 'v1.Group'
# Check the function definition where this routing happens to see if 'v1' is inside an auth check
grep -n "func.*HandleRoutes" internal/router/router.go | head -5Repository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
# Find where the routes are registered to see the middleware stack for the /system endpoint
grep -n 'SetupRouter\|Serve\|ListenAndServe' internal/router/router.go | head -5Repository: infiniflow/ragflow
Length of output: 470
🏁 Script executed:
#!/bin/bash
# Scan the beginning of the file to find how 'v1' is constructed (middleware)
head -150 internal/router/router.go | grep -A 3 -B 3 'api_v1\|v1.Group'Repository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
# Read the full file structure to understand the Router setup
wc -l internal/router/router.go
sed -n '1,50p' internal/router/router.goRepository: infiniflow/ragflow
Length of output: 2066
🏁 Script executed:
#!/bin/bash
# Search for where the 'v1' router group is instantiated with authentication middleware
grep -rn 'v1 :=\|api_v1 :=' internal/router/router.go | head -5
grep -rn "Use.*auth" internal/router/router.go | head -10Repository: infiniflow/ragflow
Length of output: 248
Align default values with the config source and verify if superuser email disclosure is intended for all authenticated users.
ListEnvironments hardcodes fallback values (e.g., "mysql", "elasticsearch", "[email protected]") that currently match the application defaults, but this duplication creates a risk of drift. If the default logic changes in the config module, this endpoint will report outdated values. It should ideally read the resolved configuration directly.
Additionally, the endpoint is registered under the authorized group, meaning any authenticated user can view the DEFAULT_SUPERUSER_EMAIL. Given this sensitivity, please confirm if exposure to all authenticated users is intended or if it requires admin-only restriction.
Code Snippet
func (s *SystemService) ListEnvironments() ([]map[string]interface{}, error) {
result := make([]map[string]interface{}, 0)
// DOC_ENGINE
docEngine := os.Getenv("DOC_ENGINE")
if docEngine == "" {
docEngine = "elasticsearch"
}
// ... similar logic for DB_TYPE, DEVICE, and STORAGE_IMPL
// DEFAULT_SUPERUSER_EMAIL reporting immediately follows
}
🤖 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/service/system.go` around lines 437 - 491, ListEnvironments is
duplicating config defaults instead of using the resolved values, which can
drift from the real application settings. Update SystemService.ListEnvironments
to read from the central config source or resolved config accessor for
DOC_ENGINE, DEFAULT_SUPERUSER_EMAIL, DB_TYPE, DEVICE, and STORAGE_IMPL rather
than hardcoding fallbacks. Also review the route exposure for ListEnvironments
in the authorized group and, if DEFAULT_SUPERUSER_EMAIL should not be visible to
all authenticated users, restrict that field or move the endpoint behind
admin-only access.
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/cli/user_parser.go (1)
2044-2081: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAlign parsed log levels with the API contract.
/system/config/logdocumentsDEBUG,INFO,WARNING, andERROR; acceptingfatal/panicand sendingwarncan create commands the API rejects.Proposed fix
case TokenDebug: - cmd.Params["level"] = "debug" + cmd.Params["level"] = "DEBUG" case TokenInfo: - cmd.Params["level"] = "info" + cmd.Params["level"] = "INFO" case TokenWarn: - cmd.Params["level"] = "warn" + cmd.Params["level"] = "WARNING" case TokenError: - cmd.Params["level"] = "error" - case TokenFatal: - cmd.Params["level"] = "fatal" - case TokenPanic: - cmd.Params["level"] = "panic" + cmd.Params["level"] = "ERROR"🤖 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/user_parser.go` around lines 2044 - 2081, The log-level parsing in Parser.parseAPISetLogLevel is accepting values that do not match the /system/config/log API contract. Update the TokenDebug/TokenInfo/TokenWarn/TokenError handling to emit the documented levels only, map the warning token to the API’s expected WARNING value instead of warn, and remove the unsupported fatal/panic cases so the generated api_set_log_level command stays contract-compliant.
🤖 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/user_command.go`:
- Around line 244-245: The log config update in user_command.go is using admin
auth for a login-protected endpoint, which can break normal API-mode sessions.
Update the request in the SetLogLevel flow to use web auth consistently with the
matching GET path, specifically in the code that calls httpClient.Request for
"/system/config/log". Keep the change localized to the existing client/request
logic so the endpoint is accessed with the same auth mode as the read path.
- Around line 250-259: The user registration response handling in
`RegisterUser`/`SimpleResponse` is forcing failures to look successful by
overwriting the response code with 0. Remove the unconditional `result.Code = 0`
assignment after `json.Unmarshal`, and preserve the application-level code
returned by the API so `resp.StatusCode == 200` responses can still surface an
error when the payload indicates failure.
---
Outside diff comments:
In `@internal/cli/user_parser.go`:
- Around line 2044-2081: The log-level parsing in Parser.parseAPISetLogLevel is
accepting values that do not match the /system/config/log API contract. Update
the TokenDebug/TokenInfo/TokenWarn/TokenError handling to emit the documented
levels only, map the warning token to the API’s expected WARNING value instead
of warn, and remove the unsupported fatal/panic cases so the generated
api_set_log_level command stays contract-compliant.
🪄 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: 89cd142e-8028-4cbe-8a76-c606077be2eb
📒 Files selected for processing (4)
internal/admin/service_variables_test.gointernal/cli/cli_http.gointernal/cli/user_command.gointernal/cli/user_parser.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/cli/cli_http.go
| httpClient := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer] | ||
| resp, err := httpClient.Request("PUT", "/system/config/log", "admin", nil, payload) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Use web auth for the log config endpoint.
The matching GET path uses "web", and /system/config/log is login-protected; "admin" can make set log level fail for normal API-mode sessions.
Proposed fix
- resp, err := httpClient.Request("PUT", "/system/config/log", "admin", nil, payload)
+ resp, err := httpClient.Request("PUT", "/system/config/log", "web", nil, payload)📝 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.
| httpClient := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer] | |
| resp, err := httpClient.Request("PUT", "/system/config/log", "admin", nil, payload) | |
| httpClient := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer] | |
| resp, err := httpClient.Request("PUT", "/system/config/log", "web", nil, payload) |
🤖 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/user_command.go` around lines 244 - 245, The log config update
in user_command.go is using admin auth for a login-protected endpoint, which can
break normal API-mode sessions. Update the request in the SetLogLevel flow to
use web auth consistently with the matching GET path, specifically in the code
that calls httpClient.Request for "/system/config/log". Keep the change
localized to the existing client/request logic so the endpoint is accessed with
the same auth mode as the read path.
| if resp.StatusCode != 200 { | ||
| return nil, fmt.Errorf("failed to register user: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) | ||
| } | ||
|
|
||
| return nil, fmt.Errorf("no log level") | ||
| var result SimpleResponse | ||
| if err = json.Unmarshal(resp.Body, &result); err != nil { | ||
| return nil, fmt.Errorf("change log level failed: invalid JSON (%w)", err) | ||
| } | ||
| result.Code = 0 | ||
| result.Duration = resp.Duration |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not force log-level updates to success.
Line 258 overwrites any application-level error code with 0, so an HTTP 200 error response can be reported as success.
Proposed fix
if resp.StatusCode != 200 {
- return nil, fmt.Errorf("failed to register user: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
+ return nil, fmt.Errorf("failed to change log level: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
}
var result SimpleResponse
if err = json.Unmarshal(resp.Body, &result); err != nil {
return nil, fmt.Errorf("change log level failed: invalid JSON (%w)", err)
}
- result.Code = 0
+ if result.Code != 0 {
+ return nil, fmt.Errorf("%s", result.Message)
+ }
result.Duration = resp.Duration📝 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 resp.StatusCode != 200 { | |
| return nil, fmt.Errorf("failed to register user: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) | |
| } | |
| return nil, fmt.Errorf("no log level") | |
| var result SimpleResponse | |
| if err = json.Unmarshal(resp.Body, &result); err != nil { | |
| return nil, fmt.Errorf("change log level failed: invalid JSON (%w)", err) | |
| } | |
| result.Code = 0 | |
| result.Duration = resp.Duration | |
| if resp.StatusCode != 200 { | |
| return nil, fmt.Errorf("failed to change log level: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) | |
| } | |
| var result SimpleResponse | |
| if err = json.Unmarshal(resp.Body, &result); err != nil { | |
| return nil, fmt.Errorf("change log level failed: invalid JSON (%w)", err) | |
| } | |
| if result.Code != 0 { | |
| return nil, fmt.Errorf("%s", result.Message) | |
| } | |
| result.Duration = resp.Duration |
🤖 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/user_command.go` around lines 250 - 259, The user registration
response handling in `RegisterUser`/`SimpleResponse` is forcing failures to look
successful by overwriting the response code with 0. Remove the unconditional
`result.Code = 0` assignment after `json.Unmarshal`, and preserve the
application-level code returned by the API so `resp.StatusCode == 200` responses
can still surface an error when the payload indicates failure.
Signed-off-by: Jin Hai <[email protected]>
What problem does this PR solve?