RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
refactor: remove unused go functions (#20455)
Jin Hai12f450587d24
diff --git a/internal/common/format.go b/internal/common/format.goindex 98996edc79..39c0d1399f 100644--- a/internal/common/format.go+++ b/internal/common/format.go@@ -24,7 +24,6 @@ import ("slices""strconv""strings"- "time""github.com/cespare/xxhash/v2")@@ -174,13 +173,6 @@ func ParseBytesString(s string) int64 {return int64(val * float64(multiplier))}-func FormatTime(t *int64) string {- if t == nil {- return "N/A"- }- return time.UnixMilli(*t).Format("2006-01-02 15:04:05")-}-func IsValidString(v interface{}) bool {str, ok := v.(string)return ok && str != ""diff --git a/internal/utility/captcha_png.go b/internal/utility/captcha_png.goindex 6715fdd0c8..9e973443ad 100644--- a/internal/utility/captcha_png.go+++ b/internal/utility/captcha_png.go@@ -14,14 +14,15 @@// limitations under the License.//+// Package utility// Stdlib-only PNG captcha renderer.//// PR #15290 review (Hz-186): the previous SVG renderer embedded the// captcha text in <text> nodes, so a scripted client could base64-// decode the response and read the answer with a regex — defeating// the captcha entirely. The reviewer asked for either a raster-// captcha or something that doesn't put the answer in machine--// readable response content. We have no image-captcha library+// captcha or something that doesn't put the answer in machine-readable+// response content. We have no image-captcha library// vendored in go.mod and no network access during build, so this// renders a real PNG using only stdlib `image`, `image/color`,// `image/draw`, and `image/png`, with a hand-rolled 5x7 bitmap font@@ -128,9 +129,9 @@ func RenderCaptchaPNG(text string) []byte {height := captchaTopPadding*2 + glyphH + 8 // a bit of headroom for jitterimg := image.NewRGBA(image.Rect(0, 0, width, height))- // Background — light, slightly cool grey.+ // Background — light, slightly cool gray.bg := color.RGBA{R: 0xf5, G: 0xf5, B: 0xf7, A: 0xff}- draw.Draw(img, img.Bounds(), &image.Uniform{bg}, image.Point{}, draw.Src)+ draw.Draw(img, img.Bounds(), &image.Uniform{C: bg}, image.Point{}, draw.Src)// Distractor lines drawn under the glyphs.for i := 0; i < captchaNoiseLines; i++ {@@ -142,7 +143,7 @@ func RenderCaptchaPNG(text string) []byte {)}- // Glyphs, each with x/y jitter and a per-glyph foreground colour.+ // Glyphs, each with x/y jitter and a per-glyph foreground color.x := captchaSidePaddingfor i := 0; i < len(upper); i++ {ch := upper[i]@@ -175,7 +176,7 @@ func RenderCaptchaPNGDataURL(text string) string {return "data:image/png;base64," + base64.StdEncoding.EncodeToString(pngBytes)}-// drawGlyph blits a 5x7 bitmap at (x, y) using captchaPNGScale x+// drawGlyph paints a 5x7 bitmap at (x, y) using captchaPNGScale x// captchaPNGScale pixel blocks. Each '#' in the bitmap becomes a// scale*scale block of `fg`.func drawGlyph(img *image.RGBA, x, y int, bitmap [7]string, fg color.RGBA) {diff --git a/internal/utility/convert.go b/internal/utility/convert.goindex 878880917f..e15ab4edd6 100644--- a/internal/utility/convert.go+++ b/internal/utility/convert.go@@ -51,26 +51,6 @@ func GetProjectBaseDirectory() string {return cwd}-// StringPtr converts a string to a pointer of string.-// If the input string is empty, it returns nil.-//-// Parameters:-// - s: The string to convert to a pointer.-//-// Returns:-// - *string: A pointer to the input string, or nil if the input is empty.-//-// Example:-//-// name := utility.StringPtr("example") // returns &"example"-// empty := utility.StringPtr("") // returns nil-func StringPtr(s string) *string {- if s == "" {- return nil- }- return &s-}-// ConfigBool reads a Python JSON bool/string flag.func ConfigBool[M ~map[string]any](config M, key string) bool {value, ok := config[key]@@ -87,34 +67,6 @@ func ConfigBool[M ~map[string]any](config M, key string) bool {}}-// ParseInt64 parses a string to int64.-// If parsing fails, it returns 0.-//-// Parameters:-// - s: The string to parse.-//-// Returns:-// - int64: The parsed integer value, or 0 if parsing fails.-//-// Example:-//-// val := utility.ParseInt64("123") // returns 123-// val := utility.ParseInt64("abc") // returns 0-// val := utility.ParseInt64("") // returns 0-func ParseInt64(s string) int64 {- var result int64- fmt.Sscanf(s, "%d", &result)- return result-}--// FormatTime formats time for display-func FormatTime(t time.Time) string {- if t.IsZero() {- return "N/A (Perpetual)"- }- return t.Format("2006-01-02 15:04:05")-}-// FormatTimeToString converts time.Time to string in specified formatfunc FormatTimeToString(t *time.Time, format string) interface{} {if t == nil {@@ -156,26 +108,6 @@ func ConvertHexToPositionIntArray(hexStr string) interface{} {return result}-// ConvertPositionIntArrayToHex converts position_int list (2D) to hex string-// e.g. [[1,2],[3,4]] -> "0000000100000002_0000000300000004"-func ConvertPositionIntArrayToHex(list []interface{}) string {- var hexParts []string- for _, item := range list {- if inner, ok := item.([]interface{}); ok {- for _, num := range inner {- if n, ok := num.(float64); ok {- hexParts = append(hexParts, fmt.Sprintf("%08x", int64(n)))- } else if n, ok := num.(int64); ok {- hexParts = append(hexParts, fmt.Sprintf("%08x", n))- } else if n, ok := num.(int); ok {- hexParts = append(hexParts, fmt.Sprintf("%08x", n))- }- }- }- }- return strings.Join(hexParts, "_")-}-// ConvertHexToIntArray converts hex string to int array (split by "_")func ConvertHexToIntArray(hexStr string) interface{} {if hexStr == "" {@@ -355,12 +287,3 @@ func ConvertMapToJSONString(v interface{}) interface{} {}return v}--// FloatToString formats a float like Python's str() - adds ".0" if needed-func FloatToString(f float64) string {- s := strconv.FormatFloat(f, 'f', -1, 64)- if !strings.Contains(s, ".") && !strings.Contains(s, "e") {- s = s + ".0"- }- return s-}diff --git a/internal/utility/http_client.go b/internal/utility/http_client.goindex 464b5530af..9a29906611 100644--- a/internal/utility/http_client.go+++ b/internal/utility/http_client.go@@ -259,7 +259,7 @@ func (c *HTTPClient) Delete(path string) (*http.Response, error) {return c.httpClient.Do(req)}-// Do performs a request with the given method+// Do perform a request with the given methodfunc (c *HTTPClient) Do(method, path string, body []byte) (*http.Response, error) {urlStr := c.GetFullURL(path)var bodyReader io.Readerdiff --git a/internal/utility/mcp_call.go b/internal/utility/mcp_call.goindex 9dce50b50b..7c04646bad 100644--- a/internal/utility/mcp_call.go+++ b/internal/utility/mcp_call.go@@ -65,7 +65,7 @@ type CallResult struct {// tools/call) — a future optimization can pool sessions.func CallTool(ctx context.Context, opts CallOptions) (*CallResult, error) {if opts.URL == "" {- return nil, errors.New("Invalid url.")+ return nil, errors.New("invalid url")}if opts.ToolName == "" {return nil, errors.New("MCP tool name is required")@@ -102,7 +102,7 @@ func CallTool(ctx context.Context, opts CallOptions) (*CallResult, error) {}return parseCallResult(result)default:- return nil, fmt.Errorf("Unsupported MCP server type.")+ return nil, fmt.Errorf("unsupported MCP server type: %s", opts.ServerType)}}diff --git a/internal/utility/mcp_call_test.go b/internal/utility/mcp_call_test.goindex 42094d0ce8..e2e9049780 100644--- a/internal/utility/mcp_call_test.go+++ b/internal/utility/mcp_call_test.go@@ -517,7 +517,7 @@ func TestCallTool_MissingURL(t *testing.T) {if err == nil {t.Fatalf("expected error for empty URL")}- if !strings.Contains(err.Error(), "Invalid url") {+ if !strings.Contains(err.Error(), "invalid url") {t.Errorf("got %v, want URL error", err)}}diff --git a/internal/utility/mcp_client.go b/internal/utility/mcp_client.goindex 655012d147..e302969fa6 100644--- a/internal/utility/mcp_client.go+++ b/internal/utility/mcp_client.go@@ -14,7 +14,7 @@// limitations under the License.//-// Package mcpclient is a minimal Model Context Protocol (MCP) client used by+// Package utility mcp client is a minimal Model Context Protocol (MCP) client used by// the Go MCP-management endpoints to list a remote server's tools during// import and the "test" endpoint. It implements just enough of the spec to// negotiate a session and call tools/list:@@ -87,7 +87,7 @@ type FetchOptions struct {// has via pin_dns_global + assert_url_is_safe.func FetchTools(ctx context.Context, opts FetchOptions) ([]Tool, error) {if opts.URL == "" {- return nil, errors.New("Invalid url.")+ return nil, errors.New("invalid url")}if opts.Timeout <= 0 {opts.Timeout = 10 * time.Second@@ -117,7 +117,7 @@ func FetchTools(ctx context.Context, opts FetchOptions) ([]Tool, error) {case TransportSSE:return fetchToolsSSE(connectCtx, opts.URL, headers, opts.HTTPClient)default:- return nil, fmt.Errorf("Unsupported MCP server type.")+ return nil, fmt.Errorf("unsupported MCP server type: %s", opts.ServerType)}}diff --git a/internal/utility/mcp_client_test.go b/internal/utility/mcp_client_test.goindex cba5b474cd..06aeabe20d 100644--- a/internal/utility/mcp_client_test.go+++ b/internal/utility/mcp_client_test.go@@ -37,7 +37,7 @@ func allowLoopbackForTests(t *testing.T) func() {orig := common.LookupHostcommon.LookupHost = func(host string) ([]string, error) {// Return a public IPv4 so the guard sees the host as global; the- // httptest server is on loopback but we connect via raw URL.+ // httptest server is on loopback, but we connect via raw URL.return []string{"8.8.8.8"}, nil}return func() { common.LookupHost = orig }@@ -272,14 +272,14 @@ func TestFetchToolsUnsupportedType(t *testing.T) {ServerType: "stdio",Timeout: time.Second,})- if err == nil || !strings.Contains(err.Error(), "Unsupported MCP server type") {+ if err == nil || !strings.Contains(err.Error(), "unsupported MCP server type") {t.Fatalf("expected unsupported-type error, got %v", err)}}func TestFetchToolsEmptyURL(t *testing.T) {_, err := FetchTools(t.Context(), FetchOptions{URL: "", ServerType: TransportSSE})- if err == nil || !strings.Contains(err.Error(), "Invalid url") {+ if err == nil || !strings.Contains(err.Error(), "invalid url") {t.Fatalf("expected Invalid url error, got %v", err)}}diff --git a/internal/utility/otp.go b/internal/utility/otp.goindex 3972e5dea5..b8b607d176 100644--- a/internal/utility/otp.go+++ b/internal/utility/otp.go@@ -14,9 +14,6 @@// limitations under the License.//-// OTP / captcha helpers for the forgot-password flow.-// Constants and key shapes mirror api/utils/web_utils.py so the Python-// and Go backends share the same Redis namespace and contract.package utilityimport (diff --git a/internal/utility/pdf_pages_test.go b/internal/utility/pdf_pages_test.goindex ccd24946d3..682e722cd7 100644--- a/internal/utility/pdf_pages_test.go+++ b/internal/utility/pdf_pages_test.go@@ -30,7 +30,7 @@ func TestNormalizePDFPages(t *testing.T) {{"overlap merged", f64([2]float64{1, 200}, [2]float64{111, 333}), [][]int{{1, 333}}},{"adjacent merged", f64([2]float64{1, 100}, [2]float64{101, 200}), [][]int{{1, 200}}},{"unsorted input sorted", f64([2]float64{400, 500}, [2]float64{1, 100}), [][]int{{1, 100}, {400, 500}}},- {"int accepted", []any{[]any{int(1), int(100)}}, [][]int{{1, 100}}},+ {"int accepted", []any{[]any{1, 100}}, [][]int{{1, 100}}},{"int64 accepted", []any{[]any{int64(1), int64(100)}}, [][]int{{1, 100}}},{"single page range", f64([2]float64{5, 5}), [][]int{{5, 5}}},}diff --git a/internal/utility/scheduled_task.go b/internal/utility/scheduled_task.goindex 1a0247ec71..bcf7bcd644 100644--- a/internal/utility/scheduled_task.go+++ b/internal/utility/scheduled_task.go@@ -17,8 +17,6 @@package utilityimport (- "encoding/json"- "fmt""ragflow/internal/common""sync""sync/atomic"@@ -27,56 +25,6 @@ import ("go.uber.org/zap")-type StatusMessage struct {- ID int `json:"id"`- Version string `json:"version"`- Timestamp time.Time `json:"timestamp"`- NodeName string `json:"node_name"`- ExtInfo string `json:"ext_info"`-}--func NewStatusMessage(id int, version string, nodeName string, extInfo string) *StatusMessage {- return &StatusMessage{- ID: id,- Version: version,- Timestamp: time.Now(),- NodeName: nodeName,- ExtInfo: extInfo,- }-}--func StatusMessageSending() {- // Construct status message- statusMessage := NewStatusMessage(0, "v1", "ragflow", "")-- // Serialize to JSON- jsonData, err := json.Marshal(statusMessage)- if err != nil {- common.Error("Failed to marshal status message", err)- return- }-- // Create HTTP client- client := NewHTTPClientBuilder().- WithHost("127.0.0.1").- WithPort(9381).- WithSSL(false).- WithTimeout(10 * time.Second).- Build()-- // Send POST request- resp, err := client.PostJSON("/v1/admin/status", jsonData)- if err != nil {- common.Error("Error sending status message", err)- return- }- defer resp.Body.Close()-- if resp.StatusCode < 200 || resp.StatusCode >= 300 {- common.Error("Failed to send status message", fmt.Errorf("status: %d", resp.StatusCode))- }-}-// ScheduledTask represents a periodic tasktype ScheduledTask struct {Name stringdiff --git a/internal/utility/smtp.go b/internal/utility/smtp.goindex fa37559045..c0fee02132 100644--- a/internal/utility/smtp.go+++ b/internal/utility/smtp.go@@ -132,9 +132,9 @@ func sendMail(cfg common.SMTPConfig, from, to string, msg []byte) error {if err != nil {return fmt.Errorf("SMTP tls dial: %w", err)}+ defer conn.Close()client, err := smtp.NewClient(conn, cfg.MailServer)if err != nil {- conn.Close()return fmt.Errorf("SMTP client init: %w", err)}defer client.Quit()diff --git a/internal/utility/token.go b/internal/utility/token.goindex ea13984ea2..a21c123310 100644--- a/internal/utility/token.go+++ b/internal/utility/token.go@@ -194,11 +194,11 @@ func bytesToInt(data []byte) int64 {// GenerateSecretKey generates a 32-byte hex string (equivalent to Python's secrets.token_hex(32))func GenerateSecretKey() (string, error) {- bytes := make([]byte, 32) // 32 bytes = 256 bits- if _, err := rand.Read(bytes); err != nil {+ byteArray := make([]byte, 32) // 32 bytes = 256 bits+ if _, err := rand.Read(byteArray); err != nil {return "", fmt.Errorf("failed to generate random key: %w", err)}- return hex.EncodeToString(bytes), nil+ return hex.EncodeToString(byteArray), nil}func GenerateToken() string {@@ -217,13 +217,13 @@ func GenerateUUID() string {// GenerateAPIToken generates secure random access keyfunc GenerateAPIToken() string {// Generate 32 random bytes- bytes := make([]byte, 32)- if _, err := rand.Read(bytes); err != nil {+ bytesArray := make([]byte, 32)+ if _, err := rand.Read(bytesArray); err != nil {// Fallback to UUID if random generation failsreturn "ragflow-" + strings.ReplaceAll(uuid.New().String(), "-", "")}// Use URL-safe base64 encoding- return "ragflow-" + base64.RawURLEncoding.EncodeToString(bytes)+ return "ragflow-" + base64.RawURLEncoding.EncodeToString(bytesArray)}// GenerateBetaAPIToken generates a beta access keydiff --git a/internal/utility/workerpool.go b/internal/utility/workerpool.goindex c4a98675f2..1ad429abef 100644--- a/internal/utility/workerpool.go+++ b/internal/utility/workerpool.go@@ -33,7 +33,7 @@ type WorkerPoolFuture[T any, R any] struct {ch <-chan WorkerPoolResult[T, R]}-// Wait blocks until the task completes or ctx is cancelled.+// Wait blocks until the task completes or ctx is canceled.func (f WorkerPoolFuture[T, R]) Wait(ctx context.Context) (WorkerPoolResult[T, R], error) {select {case <-ctx.Done():diff --git a/internal/utility/workerpool_test.go b/internal/utility/workerpool_test.goindex 41f9c463e7..c4d02433fe 100644--- a/internal/utility/workerpool_test.go+++ b/internal/utility/workerpool_test.go@@ -2,6 +2,7 @@ package utilityimport ("context"+ "errors""sync""sync/atomic""testing"@@ -134,7 +135,7 @@ func TestStopWaitConcurrentSubmitDoesNotPanic(t *testing.T) {default:}if _, err := pool.Submit(t.Context(), seed+i); err != nil {- if err != ErrWorkerPoolStopped {+ if !errors.Is(err, ErrWorkerPoolStopped) {t.Errorf("unexpected submit error: %v", err)}return@@ -211,7 +212,7 @@ func TestSubmitAfterStopWaitReturnsStopped(t *testing.T) {return in, nil})pool.StopWait()- if _, err := pool.Submit(t.Context(), 1); err != ErrWorkerPoolStopped {+ if _, err := pool.Submit(t.Context(), 1); !errors.Is(err, ErrWorkerPoolStopped) {t.Fatalf("Submit after StopWait = %v, want ErrWorkerPoolStopped", err)}}