Skip to content

Go: add volcengine - #14409

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
JinHai-CN:fix400
Apr 28, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
JinHai-CN:fix400

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Apr 28, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

  1. Refactor server_main
  2. Add volcengine

Type of change

  • Refactoring

Signed-off-by: Jin Hai <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The 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 errors.Is() for proper wrapped error detection, refactors the network utility to propagate IP resolution errors, removes the unused AdminServer struct, and applies documentation corrections across multiple files.

Changes

Cohort / File(s) Summary
VolcEngine Provider Integration
conf/models/volcengine.json, internal/entity/models/volcengine.go, internal/entity/models/factory.go
Adds VolcEngine provider configuration with doubao-seed-2-0-pro-260215 model, implements VolcEngine driver with connection checking, and registers provider in model factory dispatch logic.
Server Error Handling & Validation
cmd/admin_server.go, cmd/server_main.go
Removes unused AdminServer struct, replaces direct HTTP error comparisons with errors.Is(err, http.ErrServerClosed) for proper wrapped error detection, adds earlier configuration validation with immediate failure on zero port, and improves local IP error handling with fail-fast behavior.
Network Utility Refactoring
internal/utility/network.go
Refactors GetLocalIP() from string return to (string, error) signature, propagates network errors instead of falling back, removes obsolete GetLocalIPWithFallback helper.
Documentation & Cosmetic Updates
internal/admin/handler.go, internal/entity/models/minimax.go, internal/service/user.go
Corrects endpoint documentation comments (Health, Login), fixes GoDoc references from Zhipu AI to Minimax, renames timestamp variable from snake\_case to camelCase (now_date → nowDate), and adjusts lint directive formatting.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A new provider hops into town,
VolcEngine brings no errors down,
Error handling is now quite tight,
Network utilities do what's right,
Code review brings a smile around! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description includes required sections (problem statement and type of change) but lacks detail about what the refactoring entails and why VolcEngine was added. Add more context explaining the specific improvements in server_main refactoring and the motivation for adding VolcEngine support.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: add volcengine' is specific and directly relates to the main change of adding VolcEngine support, though it omits mention of the server_main refactoring.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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 changed the title Go: refactor codes Go: add volcengine Apr 28, 2026
@JinHai-CN JinHai-CN added the ci Continue Integration label Apr 28, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review April 28, 2026 02:54
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 28, 2026

@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: 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 | 🔴 Critical

Data race: err variable shared between goroutines without synchronization.

The closure passed to NewScheduledTask at line 259 runs in a spawned goroutine (via Start() on line 265) and reassigns err. The main function later reassigns err again 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0cf105d and 49abf50.

📒 Files selected for processing (9)
  • cmd/admin_server.go
  • cmd/server_main.go
  • conf/models/volcengine.json
  • internal/admin/handler.go
  • internal/entity/models/factory.go
  • internal/entity/models/minimax.go
  • internal/entity/models/volcengine.go
  • internal/service/user.go
  • internal/utility/network.go

Comment thread cmd/server_main.go
Comment on lines +241 to 244
localIP, err := utility.GetLocalIP()
if err != nil {
logger.Fatal("fail to get local ip address")
}

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

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.

Comment on lines +52 to +53
case "volcengine":
return NewVolcEngine(baseURL, urlSuffix), 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

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.

Comment on lines +82 to +97
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))

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

🧩 Analysis chain

🏁 Script executed:

# First, locate and examine the file mentioned in the review
find . -name "volcengine.go" -path "*/entity/models/*" -type f

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

Repository: infiniflow/ragflow

Length of output: 377


🏁 Script executed:

# Check VolcEngine struct definition
rg "type VolcEngine struct" -A 20

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

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

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

Comment thread internal/service/user.go

// 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

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
# 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 go

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

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


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.

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

codecov Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (965717c) to head (49abf50).
⚠️ Report is 7 commits behind head on main.

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.
📢 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.

@JinHai-CN
JinHai-CN merged commit 819257f into infiniflow:main Apr 28, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant