Repository navigation
Go: refactor - #17511
Go: refactor#17511
Conversation
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughServer configuration now separates API-server and general settings. Startup failures exit explicitly, admin handlers propagate request contexts, and logging APIs and error handling are updated. ChangesServer runtime and admin behavior
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related PRs
Sequence Diagram(s)sequenceDiagram
participant AdminHandler
participant EnterpriseService
participant GORM
AdminHandler->>EnterpriseService: pass c.Request.Context()
EnterpriseService->>GORM: query with dao.DB.WithContext(ctx)
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✅ Passed checks (2 passed)
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]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
cmd/ragflow_server.go (1)
381-415: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftDo not bypass deferred shutdown on runtime failures.
These
os.Exit(1)calls skipserver.ShutdownServer,engine.Close,redis.Close,storage.CloseStorage, and logger flushing. Return an exit code from arun()helper and callos.Exit(run())only from the outermain.🤖 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 `@cmd/ragflow_server.go` around lines 381 - 415, The server startup and mode-error paths currently call os.Exit directly, bypassing deferred cleanup. Refactor the flow around server.StartServer and the mode switch into a run() helper that returns an exit code, replace runtime os.Exit(1) calls with returns after preserving error reporting, and invoke os.Exit(run()) only from the outer main so deferred server.ShutdownServer, engine.Close, redis.Close, storage.CloseStorage, and logger flushing execute.
🤖 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 `@cmd/ragflow_server.go`:
- Around line 226-234: Update the exit statuses in the help/version handling
around printHelp and common.GetRAGFlowVersion so both successful CLI requests
terminate with status 0 instead of 1; preserve the existing output and argument
checks.
In `@internal/common/logger.go`:
- Around line 191-200: Update common.Error to always include zap.Error(err) in
the Logger.Error fields, while preserving optional debug/stack details through
additional fields rather than formatting err into the message. Then revise stale
GinLogger comments so they accurately describe the structured-error behavior.
In `@internal/dao/user.go`:
- Around line 74-77: Update the error handling in the user lookup flow around
query.First so it wraps the original GORM error with contextual text using
errors.Wrap or equivalent %w formatting. Preserve the underlying
gorm.ErrRecordNotFound cause so callers can identify absent users correctly.
In `@internal/server/config.go`:
- Around line 707-720: Move the ragflow mode and secret-key migration out of the
APIServer.Port == 0 guard so it always runs when ragflow configuration exists,
while retaining port mapping only for an unset port. Update the relevant
config-loading logic around globalConfig, ragflowConfig, General.Mode, and
General.SecretKey, and remove the stale commented-out ServerConfig assignment
and obsolete comments.
---
Outside diff comments:
In `@cmd/ragflow_server.go`:
- Around line 381-415: The server startup and mode-error paths currently call
os.Exit directly, bypassing deferred cleanup. Refactor the flow around
server.StartServer and the mode switch into a run() helper that returns an exit
code, replace runtime os.Exit(1) calls with returns after preserving error
reporting, and invoke os.Exit(run()) only from the outer main so deferred
server.ShutdownServer, engine.Close, redis.Close, storage.CloseStorage, and
logger flushing execute.
🪄 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 Plus
Run ID: 6ed4f674-8cc5-4d60-b250-6c91b027061b
📒 Files selected for processing (11)
cmd/ragflow_server.gointernal/admin/handler.gointernal/admin/handler_ee.gointernal/admin/service_ee.gointernal/common/logger.gointernal/dao/database.gointernal/dao/user.gointernal/handler/system.gointernal/server/config.gointernal/server/variable.gointernal/service/user.go
| if arguments.helpFlag || arguments.mode == nil { | ||
| printHelp(arguments) | ||
| return | ||
| os.Exit(1) | ||
| } | ||
|
|
||
| if arguments.versionFlag { | ||
| fmt.Printf("RAGFlow version: %s\n", common.GetRAGFlowVersion()) | ||
| return | ||
| os.Exit(1) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Return success for --help and --version.
Both are successful CLI requests; exiting with status 1 breaks scripts and package-manager probes.
🤖 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 `@cmd/ragflow_server.go` around lines 226 - 234, Update the exit statuses in
the help/version handling around printHelp and common.GetRAGFlowVersion so both
successful CLI requests terminate with status 0 instead of 1; preserve the
existing output and argument checks.
| func Error(msg string, err error, fields ...zap.Field) { | ||
| if Logger == nil { | ||
| return | ||
| } | ||
| if err != nil { | ||
| fields = append(fields, zap.Error(err)) | ||
|
|
||
| if IsDebugEnabled() { | ||
| Logger.Error(fmt.Sprintf("%s, %+v", msg, err), fields...) | ||
| } else { | ||
| Logger.Error(fmt.Sprintf("%s, %v", msg, err), fields...) | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
rg -n -C 3 'func Error\(|zap\.Error\(|common\.Error\(' \
internal/common/logger.go internal/handler internal/adminRepository: infiniflow/ragflow
Length of output: 15814
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
echo "== logger.go relevant sections =="
sed -n '1,180p' internal/common/logger.go
echo
sed -n '180,220p' internal/common/logger.go
echo
sed -n '270,310p' internal/common/logger.go
echo
echo "== common.Error call sites (all files) =="
rg -n -C 2 '\bcommon\.Error\(' .
echo
echo "== package imports/modules =="
find . -path './vendor' -prune -o -path './.git' -prune -o -name 'go.mod' -print | sed 's#^\./##' | while read -r f; do
echo "-- $f"
rg -n '^\s*(module|zap|gin)' "$f" || true
done
echo
echo "== struct/json field references =="
rg -n -C 2 '"error"|zap\.Error|type .*Log|Logger' internal/common internal | head -n 200Repository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
echo "== logger.go Error implementation =="
python3 - <<'PY'
from pathlib import Path
p = Path("internal/common/logger.go")
text = p.read_text()
start = text.index("func Error(msg string, err error, fields ...zap.Field)")
end = text.index("\nfunc Debug", start)
print(text[start:end])
PY
echo
echo "== deterministic zap fields produced by current implementation =="
cat > /tmp/zap_error_field_probe.go <<'GO'
package main
import (
"errors"
"fmt"
"go.uber.org/zap"
"go.uber.org/zap/zaptest/observer"
)
func Error(msg string, err error, fields ...zap.Field) {
if err == nil {
return
}
core, logs := observer.New(zap.ErrorLevel)
logger := zap.New(core).With(fields...)
logger.Error(fmt.Sprintf("%s, %v", msg, err))
for _, entry := range logs.All() {
fmt.Println(entry.Message)
fmt.Println("field_count:", len(entry.Context))
for _, f := range entry.Context {
fmt.Printf("key=%s type=%s string=%q\n", f.Key, f.GetTypeName(), f.String)
}
}
}
func main() {
Error("rollback failed", errors.New("connection refused"))
}
GO
go run /tmp/zap_error_field_probe.go 2>/dev/null || trueRepository: infiniflow/ragflow
Length of output: 508
🌐 Web query:
Zap Field Error returns structured error field zap.Error(err)
💡 Result:
The zap.Error(err) function in the Uber Zap logging library is a helper used to create a structured logging field that captures an error [1]. It is equivalent to calling zap.NamedError("error", err), which stores the error's message under the key "error" [1]. Key characteristics and behaviors of zap.Error(err) include: Structured Logging: It ensures the error is treated as a structured field rather than a plain string, allowing log processors to index it correctly [2][3]. Special Error Handling: If the error is nil, the field is treated as a no-op (skipped) [1]. If the error implements fmt.Formatter (e.g., those created by github.com/pkg/errors), Zap will automatically add a secondary field named errorVerbose containing the full formatted error output [1][4][5]. If the error implements the errorGroup interface (from go.uber.org/multierr) or causer interface, an errorCauses field is added, containing an array of the underlying errors [4]. Convenience: zap.Error(err) is the idiomatic way to log errors when you want to use the default "error" key [1]. If you need to use a different key, you can use zap.NamedError(key, err) instead [1]. Usage Example: logger.Error("Operation failed", zap.Error(err)) [6][3] This will result in a structured log entry similar to: { "level": "error", "msg": "Operation failed", "error": "actual error message", "errorVerbose": "..." // if applicable } [4]
Citations:
- 1: https://github.com/uber-go/zap/blob/master/error.go
- 2: https://pkg.go.dev/go.uber.org/zap
- 3: https://betterstack.com/community/guides/logging/go/zap/
- 4: https://github.com/uber-go/zap/blob/master/zapcore/error.go
- 5: method to inject alternate call site uber-go/zap#807
- 6: https://www.dash0.com/guides/logging-in-go-with-zap
Preserve Zap’s structured error field.
common.Error now formats err into msg, so zap.Error(err) is never added and structured aggregation no longer sees an error field. Keep zap.Error(err) in Error() and pass the optional stack/debug details as additional fields instead of %+v. Also update/stale comments in GinLogger so they do not claim common.Error still emits a structured error field.
🤖 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/common/logger.go` around lines 191 - 200, Update common.Error to
always include zap.Error(err) in the Logger.Error fields, while preserving
optional debug/stack details through additional fields rather than formatting
err into the message. Then revise stale GinLogger comments so they accurately
describe the structured-error behavior.
Source: Coding guidelines
| query := db.WithContext(ctx).Where("email = ?", email) | ||
| err := query.First(&user).Error | ||
| if err != nil { | ||
| return nil, err | ||
| return nil, errors.Errorf("%+v", err) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
rg -n -C 3 \
'GetByEmail|errors\.Errorf\("%\+v"|errors\.(Wrap|Is)|gorm\.ErrRecordNotFound' \
internal/dao/user.go internal/service/user.goRepository: infiniflow/ragflow
Length of output: 4619
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf '--- imports/usages in dao and service ---\n'
rg -n '^(import|)$|errors|fmt|gorm|Wrap|ErrRecordNotFound|CodeOperatingError|CodeServerError' internal/dao/user.go internal/service/user.go
printf '\n--- relevant source slices ---\n'
sed -n '1,90p' internal/dao/user.go
sed -n '100,128p' internal/service/user.go
printf '\n--- module dependency versions ---\n'
if [ -f go.mod ]; then
rg -n 'github.com/pkg/errors|gorm.io/gorm' go.mod
fiRepository: infiniflow/ragflow
Length of output: 247
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- imports/usages in dao and service ---'
rg -n '^(import|)$|errors|fmt|gorm|Wrap|ErrRecordNotFound|CodeOperatingError|CodeServerError' internal/dao/user.go internal/service/user.go
printf '%s\n' ''
printf '%s\n' '--- relevant source slices ---'
sed -n '1,90p' internal/dao/user.go
sed -n '100,128p' internal/service/user.go
printf '%s\n' ''
printf '%s\n' '--- module dependency versions ---'
if [ -f go.mod ]; then
rg -n 'github.com/pkg/errors|gorm.io/gorm' go.mod
fiRepository: infiniflow/ragflow
Length of output: 20005
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- pkg/errors package availability ---'
if command -v go >/dev/null 2>&1 && [ -d "$GOPATH/pkg/mod/github.com/pkg/[email protected]" ]; then
sed -n '1,180p' "$GOPATH/pkg/mod/github.com/pkg/[email protected]/errors.go"
else
printf '%s\n' 'pkg/errors cache not present; inspecting repo vendored module if present'
find . -path '*/pkg/errors*errors.go' -print -exec sh -c 'echo "--- $1"; sed -n "1,180p" "$1"' sh {} \;
fi
printf '%s\n' ''
printf '%s\n' '--- error chain behavior probe using installed package source if available ---'
python3 - <<'PL'
from pathlib import Path
p = Path(__import__('os').environ.get('GOPATH') or '') / 'pkg/mod/github.com/pkg/[email protected]/errors.go'
print('found=' + str(p.exists()))
if p.exists():
s = p.read_text()
for name in ['Errorf', 'Wrap', 'WithMessage']:
idx = s.find(name)
print(name, 'line=', s[:idx + 1].count('\n'), 'snippet=', s[idx:idx+300])
PLRepository: infiniflow/ragflow
Length of output: 6360
Wrap the GORM error instead of formatting it.
errors.Errorf("%+v", err) creates a new pkg/errors error without preserving the underlying gorm.ErrRecordNotFound cause, so registration treats an absent user as a server error. Use errors.Wrap(err, "get user by email") (or fmt.Errorf("get user by email: %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/dao/user.go` around lines 74 - 77, Update the error handling in the
user lookup flow around query.First so it wraps the original GORM error with
contextual text using errors.Wrap or equivalent %w formatting. Preserve the
underlying gorm.ErrRecordNotFound cause so callers can identify absent users
correctly.
| if globalConfig != nil && globalConfig.APIServer.Port == 0 { | ||
| // Try to map from ragflow section | ||
| if v.IsSet("ragflow") { | ||
| ragflowConfig := v.Sub("ragflow") | ||
| if ragflowConfig != nil { | ||
| globalConfig.Server.Port = ragflowConfig.GetInt("http_port") + 4 // 9384, by default | ||
| globalConfig.APIServer.Port = ragflowConfig.GetInt("http_port") + 4 // 9384, by default | ||
| //globalConfig.Server.Port = ragflowConfig.GetInt("http_port") // Correct | ||
| // If mode is not set, default to debug | ||
| if globalConfig.Server.Mode == "" { | ||
| globalConfig.Server.Mode = "release" | ||
| if globalConfig.General.Mode == "" { | ||
| globalConfig.General.Mode = "release" | ||
| } | ||
| secretKey := ragflowConfig.GetString("secret_key") | ||
| if secretKey != "" { | ||
| globalConfig.Server.SecretKey = &secretKey | ||
| globalConfig.General.SecretKey = &secretKey |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Always map ragflow mode and secret key.
APIServer.Port is already populated by Unmarshal from the same ragflow section, so this guard normally skips mode/secret-key migration. Configured ragflow.secret_key is ignored, causing GetSecretKey to generate/use a different Redis value; General.Mode also remains empty. Map these fields independently of the port condition, and remove the stale ServerConfig comment/commented-out assignment.
As per coding guidelines, remove commented-out Go code and keep comments aligned with the current runtime path.
🤖 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/server/config.go` around lines 707 - 720, Move the ragflow mode and
secret-key migration out of the APIServer.Port == 0 guard so it always runs when
ragflow configuration exists, while retaining port mapping only for an unset
port. Update the relevant config-loading logic around globalConfig,
ragflowConfig, General.Mode, and General.SecretKey, and remove the stale
commented-out ServerConfig assignment and obsolete comments.
Source: Coding guidelines
Signed-off-by: Jin Hai <[email protected]>
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/server/config.go (1)
717-735: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winApply the API port offset only once.
When this mapping block executes, line 717 stores
http_port + 4, and lines 731-735 add another 4. The server therefore binds tohttp_port + 8instead ofhttp_port + 4.Proposed fix
- globalConfig.APIServer.Port = ragflowConfig.GetInt("http_port") + 4 // 9384, by default + globalConfig.APIServer.Port = ragflowConfig.GetInt("http_port")🤖 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/server/config.go` around lines 717 - 735, Update the API port assignment in the configuration mapping and the fallback adjustment around globalConfig.APIServer.Port so the +4 offset is applied exactly once. Preserve the default port of 9384 when the configured port is zero, while preventing mapped http_port values from being incremented again.
♻️ Duplicate comments (1)
internal/server/config.go (1)
712-727: 🔒 Security & Privacy | 🟠 MajorDo not gate secret-key migration on the API port.
Because
APIServeris unmarshaled fromragflow,APIServer.Portmay already be non-zero before this block. In that case,ragflow.secret_keyis never copied toGeneral.SecretKey, soGetSecretKeyfalls back to the generated/Redis value ininternal/server/variable.go:92-108and ignores the configured secret. Keep only the port fallback conditional; always map mode and secret key whenragflowexists.🤖 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/server/config.go` around lines 712 - 727, Separate ragflow migration from the APIServer.Port fallback: keep only the port assignment under the globalConfig.APIServer.Port == 0 condition, while always applying General.Mode and ragflow.secret_key mapping whenever the ragflow subsection exists. Update the surrounding configuration logic so configured secrets reach General.SecretKey even when APIServer.Port was already populated.
🤖 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/server/config.go`:
- Around line 717-735: Update the API port assignment in the configuration
mapping and the fallback adjustment around globalConfig.APIServer.Port so the +4
offset is applied exactly once. Preserve the default port of 9384 when the
configured port is zero, while preventing mapped http_port values from being
incremented again.
---
Duplicate comments:
In `@internal/server/config.go`:
- Around line 712-727: Separate ragflow migration from the APIServer.Port
fallback: keep only the port assignment under the globalConfig.APIServer.Port ==
0 condition, while always applying General.Mode and ragflow.secret_key mapping
whenever the ragflow subsection exists. Update the surrounding configuration
logic so configured secrets reach General.SecretKey even when APIServer.Port was
already populated.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7dc65cd1-4b20-46f3-b8c3-e5d8b9439683
📒 Files selected for processing (1)
internal/server/config.go
Signed-off-by: Jin Hai <[email protected]>
No description provided.