Repository navigation
Go: add volcengine - #14409
Go: add volcengine#14409
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThe pull request introduces support for the VolcEngine provider with a new model driver implementation and factory integration. It improves server startup and shutdown error handling by using Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Signed-off-by: Jin Hai <[email protected]>
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/server_main.go (1)
254-263:⚠️ Potential issue | 🔴 CriticalData race:
errvariable shared between goroutines without synchronization.The closure passed to
NewScheduledTaskat line 259 runs in a spawned goroutine (viaStart()on line 265) and reassignserr. The main function later reassignserragain at line 283 (srv.Shutdown). Both goroutines access this shared variable concurrently without synchronization, causing a data race that can corrupt error values and status behavior.Suggested patch
- if err = heartbeatService.InitHTTPClient(); err != nil { - logger.Warn("Failed to initialize heartbeat service", zap.Error(err)) + if initErr := heartbeatService.InitHTTPClient(); initErr != nil { + logger.Warn("Failed to initialize heartbeat service", zap.Error(initErr)) } else { // Start heartbeat reporter with 30 seconds interval heartbeatReporter := utility.NewScheduledTask("Heartbeat reporter", 3*time.Second, func() { - if err = heartbeatService.SendHeartbeat(); err == nil { + if hbErr := heartbeatService.SendHeartbeat(); hbErr == nil { local.SetAdminStatus(0, "") } else { - local.SetAdminStatus(1, err.Error()) + local.SetAdminStatus(1, hbErr.Error()) //logger.Warn(fmt.Sprintf(err.Error())) } }) heartbeatReporter.Start() defer heartbeatReporter.Stop() } @@ - if err = srv.Shutdown(ctx); err != nil { - logger.Fatal("Server forced to shutdown", zap.Error(err)) + if shutdownErr := srv.Shutdown(ctx); shutdownErr != nil { + logger.Fatal("Server forced to shutdown", zap.Error(shutdownErr)) }Also applies to: lines 283-285
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmd/server_main.go` around lines 254 - 263, The closure passed to utility.NewScheduledTask is reusing the outer variable err causing a data race with other goroutines (e.g., later srv.Shutdown reassigning err); fix by removing use of the outer err inside the scheduled task and instead capture the heartbeat result into a new local variable inside the closure (e.g., hbErr or sendErr) and use that for SetAdminStatus and logging; do not reassign or reference the package-level/outer err anywhere in the closure (alternatively protect shared state with a mutex, but the simplest fix is to use a distinct local variable inside the heartbeat reporter closure and leave srv.Shutdown to use its own err).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@cmd/server_main.go`:
- Around line 241-244: The fatal log for failing to get the local IP drops the
underlying error; update the error handling around utility.GetLocalIP() (the
localIP, err := utility.GetLocalIP() block) to pass the err into the
logger.Fatal call (or use logger.Fatalf/WithError depending on available logger
API) so the fatal message includes the actual error details for debugging.
In `@internal/entity/models/factory.go`:
- Around line 52-53: Factory currently returns NewVolcEngine in the factory case
"volcengine" even though internal/entity/models/volcengine.go hasn't implemented
chat methods referenced by conf/models/volcengine.json; either implement the
missing chat methods in volcengine.go (the handlers used by the chat model) so
NewVolcEngine fully supports chat, or stop registering the provider by changing
the factory case "volcengine" to return an error (e.g. fmt.Errorf("volcengine
chat not implemented")) / nil until those chat methods are implemented;
reference the factory case "volcengine" and the constructor NewVolcEngine and
the chat-related functions in internal/entity/models/volcengine.go when making
the change.
In `@internal/entity/models/volcengine.go`:
- Around line 82-97: In CheckConnection, add nil-input guards and validate
lookup keys: first ensure apiConfig is non-nil, then ensure apiConfig.ApiKey is
non-nil before dereferencing; validate the chosen region exists in z.BaseURL
(e.g., check z.BaseURL[region] is present) and return a descriptive error if
missing instead of constructing a malformed URL; also return an error if
building the URL would be invalid. Update error messages to reference
CheckConnection, APIConfig.ApiKey, z.BaseURL and z.URLSuffix.Files so callers
can diagnose which validation failed.
In `@internal/service/user.go`:
- Line 570: The nolint directive comment near the DecryptPEMBlock usage is
malformed ("// nolint:static check"); remove the extra spaces and correct it to
the proper nolint token syntax so staticcheck is suppressed (use
"//nolint:staticcheck" adjacent to the code/comment referencing DecryptPEMBlock)
to satisfy nolintlint and staticcheck.
---
Outside diff comments:
In `@cmd/server_main.go`:
- Around line 254-263: The closure passed to utility.NewScheduledTask is reusing
the outer variable err causing a data race with other goroutines (e.g., later
srv.Shutdown reassigning err); fix by removing use of the outer err inside the
scheduled task and instead capture the heartbeat result into a new local
variable inside the closure (e.g., hbErr or sendErr) and use that for
SetAdminStatus and logging; do not reassign or reference the package-level/outer
err anywhere in the closure (alternatively protect shared state with a mutex,
but the simplest fix is to use a distinct local variable inside the heartbeat
reporter closure and leave srv.Shutdown to use its own err).
🪄 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: d2ed1e2a-f4a9-436c-a9b2-334b3a441387
📒 Files selected for processing (9)
cmd/admin_server.gocmd/server_main.goconf/models/volcengine.jsoninternal/admin/handler.gointernal/entity/models/factory.gointernal/entity/models/minimax.gointernal/entity/models/volcengine.gointernal/service/user.gointernal/utility/network.go
| localIP, err := utility.GetLocalIP() | ||
| if err != nil { | ||
| logger.Fatal("fail to get local ip address") | ||
| } |
There was a problem hiding this comment.
Include the underlying error in the fatal log.
Line 243 drops err, which makes incident diagnosis harder.
Suggested patch
- if err != nil {
- logger.Fatal("fail to get local ip address")
- }
+ if err != nil {
+ logger.Fatal("fail to get local ip address", zap.Error(err))
+ }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@cmd/server_main.go` around lines 241 - 244, The fatal log for failing to get
the local IP drops the underlying error; update the error handling around
utility.GetLocalIP() (the localIP, err := utility.GetLocalIP() block) to pass
the err into the logger.Fatal call (or use logger.Fatalf/WithError depending on
available logger API) so the fatal message includes the actual error details for
debugging.
| case "volcengine": | ||
| return NewVolcEngine(baseURL, urlSuffix), nil |
There was a problem hiding this comment.
Avoid registering VolcEngine as ready before chat methods exist.
Line 52 exposes volcengine in the factory, but internal/entity/models/volcengine.go (Line 55-80) still returns “not implemented” for chat paths while conf/models/volcengine.json declares a chat model. This makes provider selection fail at runtime for core usage.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/factory.go` around lines 52 - 53, Factory currently
returns NewVolcEngine in the factory case "volcengine" even though
internal/entity/models/volcengine.go hasn't implemented chat methods referenced
by conf/models/volcengine.json; either implement the missing chat methods in
volcengine.go (the handlers used by the chat model) so NewVolcEngine fully
supports chat, or stop registering the provider by changing the factory case
"volcengine" to return an error (e.g. fmt.Errorf("volcengine chat not
implemented")) / nil until those chat methods are implemented; reference the
factory case "volcengine" and the constructor NewVolcEngine and the chat-related
functions in internal/entity/models/volcengine.go when making the change.
| func (z *VolcEngine) CheckConnection(apiConfig *APIConfig) error { | ||
| var region = "default" | ||
| if apiConfig.Region != nil { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Files) | ||
|
|
||
| req, err := http.NewRequest("GET", url, nil) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, locate and examine the file mentioned in the review
find . -name "volcengine.go" -path "*/entity/models/*" -type fRepository: infiniflow/ragflow
Length of output: 101
🏁 Script executed:
# Get the exact content of the file around lines 82-97
cat -n internal/entity/models/volcengine.go | sed -n '70,110p'Repository: infiniflow/ragflow
Length of output: 1682
🏁 Script executed:
# Find APIConfig struct definition to understand its structure
rg "type APIConfig struct" -A 20Repository: infiniflow/ragflow
Length of output: 377
🏁 Script executed:
# Check VolcEngine struct definition
rg "type VolcEngine struct" -A 20Repository: infiniflow/ragflow
Length of output: 1432
🏁 Script executed:
# Look for callers of CheckConnection to understand if there's upstream validation
rg "CheckConnection" -B 2 -A 2Repository: infiniflow/ragflow
Length of output: 3628
Add input guards in CheckConnection to prevent nil pointer panics.
Line 96 dereferences apiConfig.ApiKey without a nil check—this will panic if the pointer is nil. Additionally, the function doesn't validate that apiConfig itself is non-nil (if passed nil, line 84 will panic), and line 88 silently produces a malformed URL when the region key is missing from BaseURL.
Proposed fix
import (
"fmt"
"io"
"net/http"
+ "strings"
"time"
)
@@
func (z *VolcEngine) CheckConnection(apiConfig *APIConfig) error {
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return fmt.Errorf("missing api key")
+ }
+
var region = "default"
if apiConfig.Region != nil {
region = *apiConfig.Region
}
- url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Files)
+ baseURL, ok := z.BaseURL[region]
+ if !ok || baseURL == "" {
+ baseURL = z.BaseURL["default"]
+ }
+ if baseURL == "" {
+ return fmt.Errorf("missing base URL for region %q", region)
+ }
+
+ url := strings.TrimRight(baseURL, "/") + "/" + strings.TrimLeft(z.URLSuffix.Files, "/")📝 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 (z *VolcEngine) CheckConnection(apiConfig *APIConfig) error { | |
| var region = "default" | |
| if apiConfig.Region != nil { | |
| region = *apiConfig.Region | |
| } | |
| url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Files) | |
| req, err := http.NewRequest("GET", url, nil) | |
| if err != nil { | |
| return fmt.Errorf("failed to create request: %w", err) | |
| } | |
| req.Header.Set("Content-Type", "application/json") | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | |
| func (z *VolcEngine) CheckConnection(apiConfig *APIConfig) error { | |
| if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { | |
| return fmt.Errorf("missing api key") | |
| } | |
| var region = "default" | |
| if apiConfig.Region != nil { | |
| region = *apiConfig.Region | |
| } | |
| baseURL, ok := z.BaseURL[region] | |
| if !ok || baseURL == "" { | |
| baseURL = z.BaseURL["default"] | |
| } | |
| if baseURL == "" { | |
| return fmt.Errorf("missing base URL for region %q", region) | |
| } | |
| url := strings.TrimRight(baseURL, "/") + "/" + strings.TrimLeft(z.URLSuffix.Files, "/") | |
| req, err := http.NewRequest("GET", url, nil) | |
| if err != nil { | |
| return fmt.Errorf("failed to create request: %w", err) | |
| } | |
| req.Header.Set("Content-Type", "application/json") | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/volcengine.go` around lines 82 - 97, In
CheckConnection, add nil-input guards and validate lookup keys: first ensure
apiConfig is non-nil, then ensure apiConfig.ApiKey is non-nil before
dereferencing; validate the chosen region exists in z.BaseURL (e.g., check
z.BaseURL[region] is present) and return a descriptive error if missing instead
of constructing a malformed URL; also return an error if building the URL would
be invalid. Update error messages to reference CheckConnection,
APIConfig.ApiKey, z.BaseURL and z.URLSuffix.Files so callers can diagnose which
validation failed.
|
|
||
| // loadPrivateKey loads and decrypts the RSA private key from conf/private.pem | ||
| // nolint:staticcheck // DecryptPEMBlock is deprecated but still works for traditional PEM encryption | ||
| // nolint:static check // DecryptPEMBlock is deprecated but still works for traditional PEM encryption |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find malformed nolint directives that include whitespace in linter identifiers.
rg -nP '//\s*nolint:[^/\n]*\s+[A-Za-z0-9_-]+' --type go
# Confirm canonical staticcheck suppression form usage.
rg -n '//\s*nolint:staticcheck' --type goRepository: infiniflow/ragflow
Length of output: 194
🏁 Script executed:
# Get context around line 570 to understand what warning is being suppressed
sed -n '560,580p' internal/service/user.goRepository: infiniflow/ragflow
Length of output: 647
🌐 Web query:
golangci-lint nolint directive syntax linter identifier spaces staticcheck
💡 Result:
The nolint directive syntax in golangci-lint requires no spaces between '//', 'nolint', ':', and the linter identifier. Valid syntax is '//nolint:lintername' (e.g., '//nolint:staticcheck'). Spaces make it invalid, as per Go directive comment rules (regex: //([a-z0-9]+:[a-z0-9,]+)). Invalid examples: '// nolint:staticcheck', '//nolint :staticcheck', '//nolint: staticcheck'. nolintlint is a golangci-lint linter that detects and reports ill-formed or insufficient nolint directives, including spacing errors and unused directives. staticcheck is a golangci-lint linter for static analysis checks; suppress with '//nolint:staticcheck'. Use '//nolint:all' to suppress all linters on a line/block/file. Inline suppresses only that line; line-start suppresses blocks/files.
Citations:
- 1: https://golangci-lint.run/docs/linters/false-positives/
- 2: https://golangci-lint.run/docs/linters/false-positives
- 3: https://golangci.github.io/legacy-v1-doc/usage/linters/
- 4: https://golangci-lint.run/docs/configuration/file
Fix malformed nolint directive syntax at line 570.
The directive // nolint:static check violates nolint syntax in two ways: it has a space after // and a space in the linter identifier. The correct syntax is //nolint:staticcheck (no spaces). The current form will not suppress the staticcheck warning and may be flagged by the nolintlint linter.
Proposed fix
-// nolint:static check // DecryptPEMBlock is deprecated but still works for traditional PEM encryption
+//nolint:staticcheck // DecryptPEMBlock is deprecated but still works for traditional PEM encryption📝 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.
| // nolint:static check // DecryptPEMBlock is deprecated but still works for traditional PEM encryption | |
| //nolint:staticcheck // DecryptPEMBlock is deprecated but still works for traditional PEM encryption |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/service/user.go` at line 570, The nolint directive comment near the
DecryptPEMBlock usage is malformed ("// nolint:static check"); remove the extra
spaces and correct it to the proper nolint token syntax so staticcheck is
suppressed (use "//nolint:staticcheck" adjacent to the code/comment referencing
DecryptPEMBlock) to satisfy nolintlint and staticcheck.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14409 +/- ##
=======================================
Coverage 95.30% 95.30%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 670 670
Misses 16 16
Partials 17 17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
Type of change