Repository navigation
feat: Implement API of ragflow server in Go - #15256
xugangqiang merged 8 commits into
Conversation
|
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:
📝 WalkthroughWalkthroughAdds DELETE /api/v1/messages/{memory_id}:{message_id}: service ForgetMessage with access checks and doc-engine update, handler parsing/error mapping and tests, router registration for the endpoint, plus a cgo linker flag change to use -lpcre2-8. ChangesForget Message API Feature
Linker flag update
sequenceDiagram
participant Client as Client(API Request)
participant Handler as MemoryHandler
participant Service as MemoryService
participant Require as requireMemoryAccess
participant DocEngine as DocEngine(Index)
Client->>Handler: DELETE /api/v1/messages/{memory_id}:{message_id}
Handler->>Service: ForgetMessage(ctx, userID, memoryID, messageID)
Service->>Require: requireMemoryAccess(ctx, userID, memoryID)
Require-->>Service: allowed / denied
Service->>DocEngine: Update index "memory_{tenantID}" set forget_at / forget_at_flt for "{memoryID}_{messageID}"
DocEngine-->>Service: update result
Service-->>Handler: success or ResourceNotFoundError / other error
Handler-->>Client: HTTP 200 or mapped error
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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.
Actionable comments posted: 1
🤖 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/handler/system.go`:
- Around line 219-252: The handler currently ignores req.PkgName and always
calls common.SetLevel(level) and mutates config.Log.Level; change it to validate
req.PkgName against the supported package list (or allowed package map) before
applying any changes, and if the name is unknown return a 400 with a clear
message; if you support per-package levels, route the change to the
package-specific setter instead of calling common.SetLevel (or document that
only a special global name like "global" is accepted) and only update
server.GetConfig().Log.Level when the pkg name denotes the global logger. Ensure
you reference and check req.PkgName, common.SetLevel, and
server.GetConfig().Log.Level in the implementation.
🪄 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: 29942f7e-f440-43ad-9497-0a8093769d19
📒 Files selected for processing (6)
internal/binding/rag_analyzer.gointernal/handler/system.gointernal/handler/system_test.gointernal/router/router.gointernal/service/llm.gointernal/service/system.go
| var req struct { | ||
| PkgName string `json:"pkg_name" binding:"required"` | ||
| Level string `json:"level" binding:"required"` | ||
| } | ||
| if err := c.ShouldBindJSON(&req); err != nil { | ||
| c.JSON(http.StatusBadRequest, gin.H{ | ||
| "code": 400, | ||
| "message": "pkg_name and level are required", | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| level := normalizeLogLevel(req.Level) | ||
| if err := common.SetLevel(level); err != nil { | ||
| c.JSON(http.StatusBadRequest, gin.H{ | ||
| "code": 400, | ||
| "message": "Invalid log level: " + req.Level, | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| config := server.GetConfig() | ||
| if config != nil { | ||
| config.Log.Level = level | ||
| } | ||
|
|
||
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": 0, | ||
| "message": "success", | ||
| "data": gin.H{ | ||
| "pkg_name": req.PkgName, | ||
| "level": req.Level, | ||
| }, | ||
| }) |
There was a problem hiding this comment.
Validate pkg_name before applying global log level.
SetConfigLogLevel accepts any pkg_name but always mutates one global logger level. This can return false-positive success for unsupported package targets. Please reject unknown package names (or explicitly scope behavior) to avoid contract drift.
Proposed fix
func (h *SystemHandler) SetConfigLogLevel(c *gin.Context) {
var req struct {
PkgName string `json:"pkg_name" binding:"required"`
Level string `json:"level" binding:"required"`
}
@@
+ if req.PkgName != "ragflow" {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "code": 400,
+ "message": "unsupported pkg_name: " + req.PkgName,
+ })
+ return
+ }
+
level := normalizeLogLevel(req.Level)
if err := common.SetLevel(level); err != nil {📝 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.
| var req struct { | |
| PkgName string `json:"pkg_name" binding:"required"` | |
| Level string `json:"level" binding:"required"` | |
| } | |
| if err := c.ShouldBindJSON(&req); err != nil { | |
| c.JSON(http.StatusBadRequest, gin.H{ | |
| "code": 400, | |
| "message": "pkg_name and level are required", | |
| }) | |
| return | |
| } | |
| level := normalizeLogLevel(req.Level) | |
| if err := common.SetLevel(level); err != nil { | |
| c.JSON(http.StatusBadRequest, gin.H{ | |
| "code": 400, | |
| "message": "Invalid log level: " + req.Level, | |
| }) | |
| return | |
| } | |
| config := server.GetConfig() | |
| if config != nil { | |
| config.Log.Level = level | |
| } | |
| c.JSON(http.StatusOK, gin.H{ | |
| "code": 0, | |
| "message": "success", | |
| "data": gin.H{ | |
| "pkg_name": req.PkgName, | |
| "level": req.Level, | |
| }, | |
| }) | |
| var req struct { | |
| PkgName string `json:"pkg_name" binding:"required"` | |
| Level string `json:"level" binding:"required"` | |
| } | |
| if err := c.ShouldBindJSON(&req); err != nil { | |
| c.JSON(http.StatusBadRequest, gin.H{ | |
| "code": 400, | |
| "message": "pkg_name and level are required", | |
| }) | |
| return | |
| } | |
| if req.PkgName != "ragflow" { | |
| c.JSON(http.StatusBadRequest, gin.H{ | |
| "code": 400, | |
| "message": "unsupported pkg_name: " + req.PkgName, | |
| }) | |
| return | |
| } | |
| level := normalizeLogLevel(req.Level) | |
| if err := common.SetLevel(level); err != nil { | |
| c.JSON(http.StatusBadRequest, gin.H{ | |
| "code": 400, | |
| "message": "Invalid log level: " + req.Level, | |
| }) | |
| return | |
| } | |
| config := server.GetConfig() | |
| if config != nil { | |
| config.Log.Level = level | |
| } | |
| c.JSON(http.StatusOK, gin.H{ | |
| "code": 0, | |
| "message": "success", | |
| "data": gin.H{ | |
| "pkg_name": req.PkgName, | |
| "level": req.Level, | |
| }, | |
| }) |
🤖 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 219 - 252, The handler currently
ignores req.PkgName and always calls common.SetLevel(level) and mutates
config.Log.Level; change it to validate req.PkgName against the supported
package list (or allowed package map) before applying any changes, and if the
name is unknown return a 400 with a clear message; if you support per-package
levels, route the change to the package-specific setter instead of calling
common.SetLevel (or document that only a special global name like "global" is
accepted) and only update server.GetConfig().Log.Level when the pkg name denotes
the global logger. Ensure you reference and check req.PkgName, common.SetLevel,
and server.GetConfig().Log.Level in the implementation.
There was a problem hiding this comment.
Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!
09bfc89 to
231e9d2
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/binding/rag_analyzer.go`:
- Line 21: The cgo LDFLAGS in internal/binding/rag_analyzer.go currently
hardcodes a distro-specific library path and a versioned SONAME; update the
LDFLAGS line (the line starting with "`#cgo` linux LDFLAGS:") to remove
"-L/usr/lib/x86_64-linux-gnu" and replace "-l:libpcre2-8.so.0" with the generic
"-lpcre2-8", keeping the existing static archive and other flags
("${SRCDIR}/../cpp/cmake-build-release/librag_tokenizer_c_api.a -lstdc++ -lm
-lpthread") so the linker will use standard system search paths and an
unversioned PCRE2 symbol without introducing pkg-config.
In `@internal/service/memory.go`:
- Around line 787-789: The error from s.docEngine.UpdateChunks is being
swallowed and replaced with a generic message; change the return to preserve the
original error so callers can distinguish not-found vs server errors by wrapping
the returned err (e.g., return fmt.Errorf("failed to forget message '%d' in
memory '%s': %w", messageID, memoryID, err)) instead of discarding err when
handling the UpdateChunks call in the code that invokes
s.docEngine.UpdateChunks.
🪄 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: 525f7c5a-26d5-4f86-9356-df55b55eeabe
📒 Files selected for processing (5)
internal/binding/rag_analyzer.gointernal/handler/memory.gointernal/handler/memory_message_test.gointernal/router/router.gointernal/service/memory.go
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/handler/memory.go (1)
580-589:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftDon't map arbitrary backend
"not found"text toCodeNotFound.
ForgetMessagenow preserves the underlying doc-engine error, so backend failures like a missingmemory_{tenant}index can also match"not found"/"does not exist"here and get returned as a client 404. That hides real server-side failures. Please branch on a dedicated service error for "memory/message missing" instead of substring matching the full error text.🤖 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/memory.go` around lines 580 - 589, The handler currently maps any backend text containing "not found" to CodeNotFound; change it to check for a dedicated sentinel/type error exported by the memory service (e.g., memory.ErrMessageNotFound or an error type returned by h.memoryService.ForgetMessage) using errors.Is or a type assertion instead of substring matching; only when that specific error is matched return the 404 CodeNotFound response, otherwise treat other errors as internal server errors (log and return CodeInternal/500). Locate the call to h.memoryService.ForgetMessage and the subsequent err handling to replace the string checks with errors.Is(err, memory.ErrMessageNotFound) or a type switch against the service's exported error 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/handler/memory.go`:
- Around line 580-589: The handler currently maps any backend text containing
"not found" to CodeNotFound; change it to check for a dedicated sentinel/type
error exported by the memory service (e.g., memory.ErrMessageNotFound or an
error type returned by h.memoryService.ForgetMessage) using errors.Is or a type
assertion instead of substring matching; only when that specific error is
matched return the 404 CodeNotFound response, otherwise treat other errors as
internal server errors (log and return CodeInternal/500). Locate the call to
h.memoryService.ForgetMessage and the subsequent err handling to replace the
string checks with errors.Is(err, memory.ErrMessageNotFound) or a type switch
against the service's exported error type.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 593f3d0b-9fcf-46fb-b43b-95370b3e5ed4
📒 Files selected for processing (3)
internal/binding/rag_analyzer.gointernal/handler/memory.gointernal/service/memory.go
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/service/memory.go`:
- Around line 804-808: The requireMemoryAccess function currently maps any error
from s.memoryDAO.GetByID to a ResourceNotFoundError; change it to detect
gorm.ErrRecordNotFound (use errors.Is(err, gorm.ErrRecordNotFound)) and return
the 404 ResourceNotFoundError only in that case, while for any other error
propagate or wrap the original DB/infra error (e.g., return err or a new non-404
database error) so callers get a non-404 for real DB failures; update the error
handling in requireMemoryAccess (and similar branches in that function) to
follow this pattern and import "errors" and reference gorm.ErrRecordNotFound as
needed.
🪄 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: 3666ef2b-dbf7-4d80-afc9-7414db6d1088
📒 Files selected for processing (3)
internal/handler/memory.gointernal/handler/memory_message_test.gointernal/service/memory.go
## Summary - Add Go REST support for `GET /api/v1/system/healthz`. - Return Python-compatible `ok`/`nok` dependency fields for DB, Redis, document engine, and storage. - Return HTTP 200 only when all checks pass; otherwise return HTTP 500 with `_meta` failure details. - Add focused service coverage for the unhealthy dependency response when Go dependencies are not initialized. ## Scope This is a small, isolated slice of #15240. It avoids current open connector PRs (#15274, #15300, #15265, #15264), tenant/member PRs (#15295, #15301, #15276), MCP PRs (#15281, #15253, #15254, #15260, #15261, #15262), and the memory-message PR (#15256). Refs #15240
Harry-Hz-Zhang
left a comment
There was a problem hiding this comment.
Hi, @jonathanchang31
The success and missing-memory responses match Python, but the existing-memory/missing-message case is not compatible.
Python returns {"code":0,"message":true} because it uses update-by-query and treats zero matched documents as success, while the Go implementation updates by id, gets no ES hit, and maps that to a 500 response.
Please make the Go path treat a missing message document the same way as Python, or intentionally document and test the changed behavior.
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
echo "=== internal/handler/memory.go ==="
cat internal/handler/memory.go
echo ""
echo "=== internal/handler/memory_message_test.go ==="
cat internal/handler/memory_message_test.go
echo ""
echo "=== internal/service/memory.go ==="
cat internal/service/memory.go
echo ""
echo "=== internal/router/router.go ==="
cat internal/router/router.go
echo ""
echo "=== internal/binding/rag_analyzer.go (cgo section) ==="
head -30 internal/binding/rag_analyzer.goLength of output: 76474
Overall AssessmentThe implementation is solid and well-structured. The handler/service split is clean, error typing with 🔴 Issues1. Stale TODO comment in Near the bottom of the file there's still a leftover comment that contradicts the implementation: // TODO: ForgetMessage - Implementation pending - depends on embedding engine
// func (s *MemoryService) ForgetMessage(memoryID string, messageID int) (bool, error) { ... }This should be removed since 2. func isMemoryServiceNotFound(err error) bool {
var notFoundErr *service.ResourceNotFoundError
return errors.As(err, ¬FoundErr) // matches ANY ResourceNotFoundError
}If other resources later use func isMemoryServiceNotFound(err error) bool {
var notFoundErr *service.ResourceNotFoundError
return errors.As(err, ¬FoundErr) && notFoundErr.Resource == "Memory"
}3. func (s *MemoryService) requireMemoryAccess(userID string, memoryID string) (*entity.Memory, error) {The DAO calls inside ( func (s *MemoryService) requireMemoryAccess(ctx context.Context, userID string, memoryID string) (*entity.Memory, error) {🟡 Minor Points4. Silent success on missing message document In if isMessageDocumentNotFound(err) {
return nil // silently succeeds
}This makes the delete idempotent (good), but it's worth adding a comment explaining the intent, since returning 5. Linux dynamic PCRE2 linking Switching from static 6. now := time.Now().Local()
forgetTime := now.Format("2006-01-02 15:04:05")Using local time can produce inconsistent values across distributed nodes with different timezone settings. Unless matching Python's behavior requires local time, ✅ What Looks Good
The two highest-priority fixes before merging are |
Harry-Hz-Zhang
left a comment
There was a problem hiding this comment.
@jonathanchang31, LGTM ! ! ! ! ! ! ! !
|
@jonathanchang31 please resolve conflict, then click |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15256 +/- ##
=======================================
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:
|
|
@yingfeng Could you plz review my PR? Thanks! |
Harry-Hz-Zhang
left a comment
There was a problem hiding this comment.
@jonathanchang31, LGTM!
Summary
DELETE /api/v1/messages/{memory_id}:{message_id}memory_id:message_id.forget_at.code: 0,message: true,data: null.Related Issue
Closes: #15240
Change Type
Implemented API
DELETE /api/v1/messages/{memory_id}:{message_id}Real Behavior Proof
Validated with targeted Go tests:
/tmp/go1.25.0/bin/go test ./internal/handler ./internal/routerResult:
Validated server entrypoint build:
Result:
Validated patch formatting:
Result:
Checklist
DELETE /api/v1/messages/{memory_id}:{message_id}.git diff --check.