Repository navigation
feat: Implement file-related functionality - #14011
Conversation
- Add DELETE /files route in router - Implement DeleteFiles handler method - Implement file deletion flow in service layer (permission check, recursive folder deletion, document cleanup) - Add Delete methods in dao layer - Rename knowledgebase to dataset across the codebase
…ions and prevent root folder deletion - Add context.Context parameter to file deletion methods to support timeout control - Add root folder deletion protection logic (when parent_id == id) - Add 300-second timeout control for document engine deletion operations - Unify context propagation for recursive deletion and single file deletion
…to feature/go-file-download
…tions Implement file download API endpoints, including permission checks, retrieval of storage paths, and file content streaming. Migrate file utility functions from the `common` package to the `utility` package and extend their functionality. Add utility functions for file type detection, content type mapping, attachment handling, and related tasks.
|
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:
📝 WalkthroughWalkthroughAdded file management endpoints (delete, move, download), new DAO methods for File/File2Document and Document.UpdateByID (returns error), service-layer file operations and storage/address helpers, renamed knowledgebase→dataset identifiers, and renamed package Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Handler as File Handler
participant Service as FileService
participant DAO as FileDAO
participant Storage as Storage
participant DocEngine as DocumentEngine
Client->>Handler: DELETE /api/v1/files (ids)
Handler->>Service: DeleteFiles(uid, ids)
Service->>DAO: GetByIDs(ids)
DAO-->>Service: []*File
Service->>Storage: Delete object(s) (ParentID+Location)
Storage-->>Service: OK
Service->>DocEngine: deleteDocumentFromEngine(...)
DocEngine-->>Service: OK
Service->>DAO: Unscoped delete file & mappings
DAO-->>Service: OK
Service-->>Handler: result
Handler-->>Client: JSON response
sequenceDiagram
participant Client
participant Handler as File Handler
participant Service as FileService
participant DAO as FileDAO
participant Storage as Storage
participant Utility as Utility
Client->>Handler: POST /api/v1/files/move (srcIDs,destID,newName)
Handler->>Service: MoveFiles(uid, srcIDs, destID, newName)
Service->>DAO: GetByIDs(srcIDs) / GetByIDs([destID])
DAO-->>Service: files
Service->>DAO: Check duplicate names in dest
DAO-->>Service: existing
alt ParentID changed
Service->>Storage: Move object(s)
Storage-->>Service: OK
end
Service->>DAO: Update file records (ParentID, Name)
DAO-->>Service: OK
Service-->>Handler: result
Handler-->>Client: JSON response
sequenceDiagram
participant Client
participant Handler as File Handler
participant Service as FileService
participant DAO as FileDAO
participant Storage as Storage
participant Utility as Utility
Client->>Handler: GET /api/v1/files/:id
Handler->>Service: GetFileContent(uid, fileID)
Service->>DAO: Query file metadata
DAO-->>Service: *File
Handler->>Storage: Primary lookup (ParentID + Location)
alt Found
Storage-->>Handler: binary
else Not Found
Handler->>Service: GetStorageAddress(fileID)
Service->>DAO: Query mapping (file/document)
DAO-->>Service: StorageAddress
Service-->>Handler: StorageAddress
Handler->>Storage: Fallback lookup
Storage-->>Handler: binary
end
Handler->>Utility: GetContentType(ext,fileType)
Utility-->>Handler: contentType
Handler->>Utility: ShouldForceAttachment(ext,contentType)
Utility-->>Handler: bool
Handler-->>Client: Streamed binary with headers
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/dao/document.go`:
- Around line 65-68: Change UpdateByID on DocumentDAO to return an error instead
of a bool: update the signature of UpdateByID(id string, updates
map[string]interface{}) to return error, propagate and return DB operation error
(result.Error) from the call to
DB.Model(&entity.Document{}).Where(...).Updates(updates), and optionally
translate result.RowsAffected == 0 into a not-found error if you want callers to
distinguish "no matching record" (mirroring the pattern used in other DAOs like
ChatDAO/KnowledgebaseDAO/ChatSessionDAO/MemoryDAO/ConnectorDAO); apply the same
change to FileDAO to make both surface database errors instead of silently
returning false.
In `@internal/dao/file.go`:
- Around line 397-399: The loop calling dao.addFileFromKB for each document
ignores its returned error (in the for _, doc := range documents block), which
can leave dataset state inconsistent; update the loop to check and propagate the
error from dao.addFileFromKB (e.g., capture the returned error from
dao.addFileFromKB(&doc, datasetFolderForDataset.ID, tenantID, file2DocumentDAO)
and return or handle it appropriately), ensuring failures during dataset
bootstrap are not silently ignored and include context (document ID or
datasetFolderForDataset.ID) when returning or logging the error.
In `@internal/handler/file.go`:
- Around line 505-507: The Content-Disposition header currently set in the
branch guarded by utility.ShouldForceAttachment(ext, contentType) is just
"attachment" which omits the original file name; update the header call that
uses c.Header("Content-Disposition", ...) to include the original filename
(file.Name) using a proper encoded disposition (e.g., build "attachment;
filename*=UTF-8''<url-encoded-file.Name>" or generate it via
mime.FormatMediaType to handle quoting/encoding), ensuring you URL-encode/escape
file.Name for UTF-8 and pass that string to c.Header so clients save the
response with the correct filename.
In `@internal/service/file.go`:
- Around line 723-730: The destination validation currently only checks
existence; update the block handling destFileID to (1) ensure the target is a
folder (e.g., check destFolder.Type or IsFolder on the entity returned by
s.fileDAO.GetByID) and return an error if it's not, and (2) ensure the
destination folder is not inside the subtree being moved by checking that
destFolder.ID is not equal to the source ID and is not a descendant of the
source (traverse parent_id from destFolder upward or use an ancestor check
helper before calling moveEntryRecursive) to prevent moving a folder into itself
or its descendants; add clear error returns for non-folder and descendant cases.
- Around line 748-759: The duplicate-name check currently only runs when newName
is provided, so a move that preserves the original name can collide; update the
logic in the move/rename flow (referencing variables targetParentID, destFolder,
newName, s.fileDAO.Query and existingFiles) to compute a nameToCheck = newName
if non-empty else file.Name and use that for the query against targetParentID;
then check existingFiles for any entry with the same name (and ignore the moved
file itself by comparing IDs) and return the duplicate error if found.
- Around line 587-622: The code currently proceeds to delete the file even if
s.file2DocumentDAO.GetByFileID or s.file2DocumentDAO.DeleteByFileID fails,
risking orphaned file2document/document rows; change the logic so association
cleanup is part of the same transactional boundary: call
s.file2DocumentDAO.GetByFileID, iterate and delete documents via
documentDAO.Delete and deleteDocumentFromEngine, ensure any error during
GetByFileID, document deletion, deleteDocumentFromEngine or
s.file2DocumentDAO.DeleteByFileID is returned (or causes the outer transaction
to rollback) and aborts removing the file; in short, move the final file
deletion behind a successful mapping cleanup or run the whole sequence in a DB
transaction and propagate errors from GetByFileID, documentDAO.Delete,
deleteDocumentFromEngine and DeleteByFileID so the file row is not hard-deleted
on association cleanup failure.
- Around line 807-809: The code ignores the error from s.fileDAO.CreateFolder
and may proceed with newFolder == nil; change the CreateFolder call to capture
its error (e.g., newFolder, err := s.fileDAO.CreateFolder(...)), check if err !=
nil or newFolder == nil and handle it immediately (return the error up the call
stack or log and abort the copy/move operation) so you never recurse into or
delete the source using a nil newFolder; update all references in this function
that assume newFolder exists (the recursive call and any deletion logic) to only
run when CreateFolder succeeded.
In `@internal/utility/file.go`:
- Around line 217-231: GetContentType currently synthesizes image/<ext> for
FileTypeVISUAL when CONTENT_TYPE_MAP lacks the extension, which produces invalid
MIME types for non-image visual formats (e.g., image/mp4); update GetContentType
to stop generating image/* for unknown visual extensions: consult
CONTENT_TYPE_MAP first, ensure common video types are present in
CONTENT_TYPE_MAP (e.g., mp4, mov, webm) and, if an extension is still unmapped,
return "application/octet-stream" (not image/<ext>); keep references to
GetContentType, CONTENT_TYPE_MAP, and FileTypeVISUAL when making the change.
🪄 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: af66e0f3-b5d3-4c1b-ae73-668e1771e1fa
📒 Files selected for processing (7)
internal/dao/document.gointernal/dao/file.gointernal/dao/file2document.gointernal/handler/file.gointernal/router/router.gointernal/service/file.gointernal/utility/file.go
…ow into feature/go-file-download
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (4)
internal/service/file.go (4)
808-810:⚠️ Potential issue | 🔴 CriticalHandle
CreateFoldererrors before recursing.The
CreateFoldererror is discarded, so recursion can dereferenceniland/or continue to deletion with invalid destination state.Suggested fix
- } else { - // Create new folder - newFolder, _ = s.fileDAO.CreateFolder(destFolder.ID, sourceFile.TenantID, effectiveName, FileTypeFolder) - } + } else { + // Create new folder + var err error + newFolder, err = s.fileDAO.CreateFolder(destFolder.ID, sourceFile.TenantID, effectiveName, FileTypeFolder) + if err != nil || newFolder == nil { + return fmt.Errorf("create destination folder failed: %w", err) + } + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/file.go` around lines 808 - 810, The call to s.fileDAO.CreateFolder that assigns newFolder ignores its returned error, which can lead to nil dereferences and invalid deletion flows; change the CreateFolder invocation in the block that sets newFolder to capture and check the error (err := s.fileDAO.CreateFolder(...)), return or propagate the error (or handle it appropriately) before recursing or proceeding to deletion, and avoid using newFolder if err != nil; reference the CreateFolder call, the newFolder variable, destFolder, sourceFile and effectiveName/FileTypeFolder to locate and update the logic.
724-731:⚠️ Potential issue | 🔴 CriticalValidate destination folder type and moved-subtree constraints.
Current destination validation only checks existence. It still allows non-folder destinations and moving a folder into itself/its descendants, which can corrupt
parent_idsemantics or recurse into unstable state.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/file.go` around lines 724 - 731, The destination validation only checks existence; update the block that uses s.fileDAO.GetByID(destFileID) to also verify destFolder is a folder (e.g., destFolder.Type == entity.FileTypeFolder) and prevent moving a file/folder into itself or one of its descendants by walking the parent chain: starting from destFolder, loop calling s.fileDAO.GetByID(current.ParentID) (or similar) and compare each ancestor's ID to the subject file's ID (the source being moved); if any match, return a clear error (e.g., "Cannot move folder into itself or its descendant") and handle any DAO errors during the ancestor traversal. Ensure you reference destFolder, destFileID, s.fileDAO.GetByID, and the source file ID in the check.
749-760:⚠️ Potential issue | 🟠 MajorApply duplicate-name checks for plain moves too.
Collision validation only runs when
newNameis set. Move-only operations can still create duplicate sibling names in destination.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/file.go` around lines 749 - 760, The duplicate-name check currently only runs when newName is set; for plain moves you must validate collisions against the destination using the file's current name. Compute the nameToCheck = newName if newName != "" else file.Name, determine targetParentID as you already do (destFolder.ID or file.ParentID), then call s.fileDAO.Query(nameToCheck, targetParentID) and iterate existingFiles while skipping the record with the same ID as file.ID; if any other f.Name == nameToCheck return the duplicate error message. Ensure you reference variables newName, file.Name, targetParentID, destFolder, existingFiles, s.fileDAO.Query and file.ID when adding this logic.
587-625:⚠️ Potential issue | 🟠 MajorDo not delete the file row when association cleanup fails.
GetByFileID/document delete/engine delete/DeleteByFileIDfailures are swallowed, buts.fileDAO.Delete(file.ID)still runs. That can orphan mappings/documents and break later resolution.Suggested fix
- informs, err := s.file2DocumentDAO.GetByFileID(file.ID) - if err == nil && len(informs) > 0 { + informs, err := s.file2DocumentDAO.GetByFileID(file.ID) + if err != nil { + return fmt.Errorf("load file2document mappings: %w", err) + } + if len(informs) > 0 { documentDAO := dao.NewDocumentDAO() datasetDAO := dao.NewKnowledgebaseDAO() @@ - if err := documentDAO.Delete(docID); err != nil { - logger.Logger.Error(fmt.Sprintf("Fail to delete document: %s, error: %v", docID, err)) - } + if err := documentDAO.Delete(docID); err != nil { + return fmt.Errorf("delete document %s: %w", docID, err) + } } } // Delete file2document mapping (outside the loop, called once - matching Python behavior) - s.file2DocumentDAO.DeleteByFileID(file.ID) + if err := s.file2DocumentDAO.DeleteByFileID(file.ID); err != nil { + return fmt.Errorf("delete file2document mappings: %w", err) + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/file.go` around lines 587 - 625, The code currently always calls s.fileDAO.Delete(file.ID) even if cleaning up file->document mappings or deleting documents/engine entries fails; change the flow in the block that starts with s.file2DocumentDAO.GetByFileID to track and surface any error from GetByFileID, s.deleteDocumentFromEngine, documentDAO.Delete, and s.file2DocumentDAO.DeleteByFileID (do not swallow them), and only proceed to call s.fileDAO.Delete(file.ID) when no cleanup error occurred; specifically, in the loop over informs from s.file2DocumentDAO.GetByFileID, propagate and aggregate errors coming from documentDAO.GetByID, s.deleteDocumentFromEngine(ctx, doc, tenantID), documentDAO.Delete(docID), and after the loop check the result of s.file2DocumentDAO.DeleteByFileID(file.ID), and if any of these returned an error return that error (or wrap and return) instead of performing s.fileDAO.Delete(file.ID).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/service/file.go`:
- Around line 803-825: The code in moveEntryRecursive reuses existingFolders[0]
without checking if it is the same as sourceFile, which can cause deleting the
source when merging into itself; fix by checking after getting existingFolders
whether existingFolders[0].ID == sourceFile.ID and if so handle specially
(either create a new folder via s.fileDAO.CreateFolder with a disambiguated name
or return an explicit error), then proceed to recursively move children into the
safe newFolder and only delete the source when newFolder is not the source;
ensure this check references existingFolders, sourceFile.ID,
s.fileDAO.CreateFolder and s.fileDAO.Delete so the fix is applied in the block
that currently sets newFolder and later deletes sourceFile.
- Around line 724-731: The code validates the destination folder exists
(destFolder via s.fileDAO.GetByID) but does not enforce that the caller has
write permission there; add the same authorization check used for the source
file earlier in this method to validate the caller can write to destFolder (use
the same permission-check function/logic already present in this file/function),
and if unauthorized return a clear error (e.g., "No permission to write to
destination folder") instead of allowing the move.
- Around line 770-778: The pure-rename branch currently allows setting an empty
newName and only updates the first source file; change this so that if newName
is empty and there are multiple srcFileIDs you return an error (e.g., "New name
required for multi-source rename"), and when performing a pure rename with a
non-empty newName iterate over all srcFileIDs (use srcFileIDs and filesMap to
look up each file) and call s.fileDAO.UpdateByID for each file.ID, returning a
failure if any update fails; also preserve the existing check for
len(srcFileIDs) == 0 and keep the same error messages for not-found/database
errors.
---
Duplicate comments:
In `@internal/service/file.go`:
- Around line 808-810: The call to s.fileDAO.CreateFolder that assigns newFolder
ignores its returned error, which can lead to nil dereferences and invalid
deletion flows; change the CreateFolder invocation in the block that sets
newFolder to capture and check the error (err := s.fileDAO.CreateFolder(...)),
return or propagate the error (or handle it appropriately) before recursing or
proceeding to deletion, and avoid using newFolder if err != nil; reference the
CreateFolder call, the newFolder variable, destFolder, sourceFile and
effectiveName/FileTypeFolder to locate and update the logic.
- Around line 724-731: The destination validation only checks existence; update
the block that uses s.fileDAO.GetByID(destFileID) to also verify destFolder is a
folder (e.g., destFolder.Type == entity.FileTypeFolder) and prevent moving a
file/folder into itself or one of its descendants by walking the parent chain:
starting from destFolder, loop calling s.fileDAO.GetByID(current.ParentID) (or
similar) and compare each ancestor's ID to the subject file's ID (the source
being moved); if any match, return a clear error (e.g., "Cannot move folder into
itself or its descendant") and handle any DAO errors during the ancestor
traversal. Ensure you reference destFolder, destFileID, s.fileDAO.GetByID, and
the source file ID in the check.
- Around line 749-760: The duplicate-name check currently only runs when newName
is set; for plain moves you must validate collisions against the destination
using the file's current name. Compute the nameToCheck = newName if newName !=
"" else file.Name, determine targetParentID as you already do (destFolder.ID or
file.ParentID), then call s.fileDAO.Query(nameToCheck, targetParentID) and
iterate existingFiles while skipping the record with the same ID as file.ID; if
any other f.Name == nameToCheck return the duplicate error message. Ensure you
reference variables newName, file.Name, targetParentID, destFolder,
existingFiles, s.fileDAO.Query and file.ID when adding this logic.
- Around line 587-625: The code currently always calls s.fileDAO.Delete(file.ID)
even if cleaning up file->document mappings or deleting documents/engine entries
fails; change the flow in the block that starts with
s.file2DocumentDAO.GetByFileID to track and surface any error from GetByFileID,
s.deleteDocumentFromEngine, documentDAO.Delete, and
s.file2DocumentDAO.DeleteByFileID (do not swallow them), and only proceed to
call s.fileDAO.Delete(file.ID) when no cleanup error occurred; specifically, in
the loop over informs from s.file2DocumentDAO.GetByFileID, propagate and
aggregate errors coming from documentDAO.GetByID,
s.deleteDocumentFromEngine(ctx, doc, tenantID), documentDAO.Delete(docID), and
after the loop check the result of s.file2DocumentDAO.DeleteByFileID(file.ID),
and if any of these returned an error return that error (or wrap and return)
instead of performing s.fileDAO.Delete(file.ID).
🪄 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: 696b9435-0b60-4ec8-b64a-8fe01f488f38
📒 Files selected for processing (1)
internal/service/file.go
This reverts commit fe012e4.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (5)
internal/service/file.go (5)
807-809:⚠️ Potential issue | 🔴 CriticalHandle
CreateFoldererrors before recursive move.Line 808 drops the error; recursion at Line 817 can then run with an invalid
newFolder, causing nil dereference and partial move state.Suggested fix
- } else { - // Create new folder - newFolder, _ = s.fileDAO.CreateFolder(destFolder.ID, sourceFile.TenantID, effectiveName, FileTypeFolder) - } + } else { + // Create new folder + var err error + newFolder, err = s.fileDAO.CreateFolder(destFolder.ID, sourceFile.TenantID, effectiveName, FileTypeFolder) + if err != nil || newFolder == nil { + return fmt.Errorf("create destination folder failed") + } + }Also applies to: 817-819
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/file.go` around lines 807 - 809, The code currently ignores the error returned by s.fileDAO.CreateFolder when assigning newFolder in the move logic; check the error from s.fileDAO.CreateFolder (the call creating newFolder) and handle it immediately (return the error up, log and abort the move, or otherwise stop recursion) before using newFolder in the subsequent recursive call/path; ensure the same fix is applied to the other CreateFolder call around the recursive move (the block at the later occurrence) so you never recurse or continue with a nil newFolder and thus avoid nil dereference and partial move state.
748-759:⚠️ Potential issue | 🟠 MajorRun duplicate-name validation for plain moves too.
Current collision checks only run when
newNameis provided. Move-only operations can still create duplicate sibling names in the destination.Suggested fix
- // 5. Validate new_name if provided - if newName != "" { + // 5. Validate naming/collision constraints + if newName != "" { if len(srcFileIDs) > 1 { return false, "new_name can only be used with a single file" } @@ - // Check for duplicate names in target folder - targetParentID := file.ParentID - if destFolder != nil { - targetParentID = destFolder.ID - } - existingFiles := s.fileDAO.Query(newName, targetParentID) - for _, f := range existingFiles { - if f.Name == newName { - return false, "Duplicated file name in the same folder." - } - } } + + for _, file := range files { + nameToCheck := file.Name + if newName != "" { + nameToCheck = newName + } + targetParentID := file.ParentID + if destFolder != nil { + targetParentID = destFolder.ID + } + existingFiles := s.fileDAO.Query(nameToCheck, targetParentID) + for _, f := range existingFiles { + if f.Name == nameToCheck && f.ID != file.ID { + return false, "Duplicated file name in the same folder." + } + } + }Also applies to: 762-768
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/file.go` around lines 748 - 759, The duplicate-name collision check only runs when newName is set; for plain moves you must check using the file's existing name as well. In the move handling code (references: variable newName, file.ParentID, destFolder, and s.fileDAO.Query) set a nameToCheck := newName if newName != "" else file.Name and use nameToCheck when calling s.fileDAO.Query and comparing f.Name to detect duplicates; apply the same change to the other occurrence around the second block (the 762-768 region) so both rename+move and move-only flows validate sibling name collisions in the destination folder.
802-806:⚠️ Potential issue | 🔴 CriticalGuard against self-target folder merge deleting the source.
If
existingFolders[0]is the same folder assourceFile, recursion becomes a no-op and Line 823 deletes the source folder.Also applies to: 822-823
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/file.go` around lines 802 - 806, The code currently assigns newFolder = existingFolders[0] without checking whether that folder is actually the source (sourceFile), which can make the subsequent recursion a no-op and then delete the source; add a guard after computing existingFolders (and before using existingFolders[0]) to compare IDs (e.g., existingFolders[0].ID vs sourceFile.ID or pointer equality) and if they match, skip the merge/recursion path (return early or set newFolder to sourceFile and skip deletion logic) so the source folder is not removed by the merge into itself; update any callers of newFolder/recursion in this block to respect that early-return/skip behavior.
587-625:⚠️ Potential issue | 🟠 MajorDon’t delete the file row when association cleanup fails.
Line 587/Line 621 cleanup failures are effectively ignored, but Line 625 still deletes the file record. This can orphan
file2document/document state and break later storage resolution.Suggested fix
- informs, err := s.file2DocumentDAO.GetByFileID(file.ID) - if err == nil && len(informs) > 0 { + informs, err := s.file2DocumentDAO.GetByFileID(file.ID) + if err != nil { + return fmt.Errorf("get file2document by file id: %w", err) + } + if len(informs) > 0 { documentDAO := dao.NewDocumentDAO() datasetDAO := dao.NewKnowledgebaseDAO() @@ - if err := documentDAO.Delete(docID); err != nil { - logger.Logger.Error(fmt.Sprintf("Fail to delete document: %s, error: %v", docID, err)) - } + if err := documentDAO.Delete(docID); err != nil { + return fmt.Errorf("delete document %s: %w", docID, err) + } } @@ - s.file2DocumentDAO.DeleteByFileID(file.ID) + if err := s.file2DocumentDAO.DeleteByFileID(file.ID); err != nil { + return fmt.Errorf("delete file2document mapping: %w", err) + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/file.go` around lines 587 - 625, The current flow always calls s.fileDAO.Delete(file.ID) even if removing document associations or deleting documents fails; change the logic in the surrounding function so that any error from s.file2DocumentDAO.GetByFileID, document deletions (documentDAO.Delete), dataset lookup (datasetDAO.GetByID), deleteDocumentFromEngine, or s.file2DocumentDAO.DeleteByFileID is recorded and causes the function to return (or propagate) that error instead of proceeding to call s.fileDAO.Delete; specifically, inside the block using s.file2DocumentDAO.GetByFileID and the loop over informs, aggregate or short-circuit on any non-nil error from documentDAO.GetByID, datasetDAO.GetByID, deleteDocumentFromEngine, and documentDAO.Delete, and only call s.file2DocumentDAO.DeleteByFileID and finally s.fileDAO.Delete(file.ID) when no prior errors occurred (or return the aggregated error), so that s.fileDAO.Delete is not executed when association cleanup fails.
723-730:⚠️ Potential issue | 🔴 CriticalValidate destination write permission (and destination type) before move.
Line 726 only checks destination existence. Missing auth on destination lets users move into folders they can’t write to; also destination should be enforced as a folder.
Suggested fix
if destFileID != "" { destFolder, err = s.fileDAO.GetByID(destFileID) if err != nil || destFolder == nil { return false, "Parent folder not found!" } + if destFolder.Type != FileTypeFolder { + return false, "Destination must be a folder." + } + if !s.checkFileTeamPermission(destFolder, uid) { + return false, "No authorization." + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/file.go` around lines 723 - 730, The current check only verifies destination existence (destFolder via s.fileDAO.GetByID) but must also enforce that the destination is a folder and that the current user has write permission to it; update the block that handles destFileID to (1) verify destFolder.Type (or an equivalent field/method on entity.File) indicates a folder and return an appropriate error if not, and (2) call the service/authorizer used elsewhere in this file (e.g., s.authorizer, s.permissionService, or existing auth helper used for other ops) to check write permission for the requester on destFolder and return a permission-denied error if the check fails, ensuring error messages are specific (e.g., "Destination is not a folder" or "No write permission on destination folder") while leaving the existing existence check in place.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/service/file.go`:
- Around line 848-863: The storage move and DB update are not atomic: after
calling storageImpl.Move(sourceFile.ParentID, *sourceFile.Location,
destFolder.ID, newLocation) you must attempt to roll back the blob if
s.fileDAO.UpdateByID(sourceFile.ID, updates) fails. Modify the logic around
storageImpl.Move and s.fileDAO.UpdateByID so that after a successful Move you
call UpdateByID and, on its failure, call storageImpl.Move(destFolder.ID,
newLocation, sourceFile.ParentID, *sourceFile.Location) to move the blob back
(with logging and an error that includes both the DB error and any rollback
error); ensure you handle and surface both errors from UpdateByID and the
compensating Move, and consider retry/backoff for the rollback to reduce risk of
orphaned blobs.
---
Duplicate comments:
In `@internal/service/file.go`:
- Around line 807-809: The code currently ignores the error returned by
s.fileDAO.CreateFolder when assigning newFolder in the move logic; check the
error from s.fileDAO.CreateFolder (the call creating newFolder) and handle it
immediately (return the error up, log and abort the move, or otherwise stop
recursion) before using newFolder in the subsequent recursive call/path; ensure
the same fix is applied to the other CreateFolder call around the recursive move
(the block at the later occurrence) so you never recurse or continue with a nil
newFolder and thus avoid nil dereference and partial move state.
- Around line 748-759: The duplicate-name collision check only runs when newName
is set; for plain moves you must check using the file's existing name as well.
In the move handling code (references: variable newName, file.ParentID,
destFolder, and s.fileDAO.Query) set a nameToCheck := newName if newName != ""
else file.Name and use nameToCheck when calling s.fileDAO.Query and comparing
f.Name to detect duplicates; apply the same change to the other occurrence
around the second block (the 762-768 region) so both rename+move and move-only
flows validate sibling name collisions in the destination folder.
- Around line 802-806: The code currently assigns newFolder = existingFolders[0]
without checking whether that folder is actually the source (sourceFile), which
can make the subsequent recursion a no-op and then delete the source; add a
guard after computing existingFolders (and before using existingFolders[0]) to
compare IDs (e.g., existingFolders[0].ID vs sourceFile.ID or pointer equality)
and if they match, skip the merge/recursion path (return early or set newFolder
to sourceFile and skip deletion logic) so the source folder is not removed by
the merge into itself; update any callers of newFolder/recursion in this block
to respect that early-return/skip behavior.
- Around line 587-625: The current flow always calls s.fileDAO.Delete(file.ID)
even if removing document associations or deleting documents fails; change the
logic in the surrounding function so that any error from
s.file2DocumentDAO.GetByFileID, document deletions (documentDAO.Delete), dataset
lookup (datasetDAO.GetByID), deleteDocumentFromEngine, or
s.file2DocumentDAO.DeleteByFileID is recorded and causes the function to return
(or propagate) that error instead of proceeding to call s.fileDAO.Delete;
specifically, inside the block using s.file2DocumentDAO.GetByFileID and the loop
over informs, aggregate or short-circuit on any non-nil error from
documentDAO.GetByID, datasetDAO.GetByID, deleteDocumentFromEngine, and
documentDAO.Delete, and only call s.file2DocumentDAO.DeleteByFileID and finally
s.fileDAO.Delete(file.ID) when no prior errors occurred (or return the
aggregated error), so that s.fileDAO.Delete is not executed when association
cleanup fails.
- Around line 723-730: The current check only verifies destination existence
(destFolder via s.fileDAO.GetByID) but must also enforce that the destination is
a folder and that the current user has write permission to it; update the block
that handles destFileID to (1) verify destFolder.Type (or an equivalent
field/method on entity.File) indicates a folder and return an appropriate error
if not, and (2) call the service/authorizer used elsewhere in this file (e.g.,
s.authorizer, s.permissionService, or existing auth helper used for other ops)
to check write permission for the requester on destFolder and return a
permission-denied error if the check fails, ensuring error messages are specific
(e.g., "Destination is not a folder" or "No write permission on destination
folder") while leaving the existing existence check in place.
🪄 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: 050a26e0-a2f4-459d-855b-87d586b360b4
📒 Files selected for processing (1)
internal/service/file.go
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
internal/utility/file.go (1)
137-199:⚠️ Potential issue | 🟠 MajorStop synthesizing MIME types for unmapped downloads.
FilenameTyperecognizes aural/visual extensions that still are not covered here, soGetContentTypefalls back to values likeapplication/mp3orimage/asf, and it returns""for extensionless files. That gives the download endpoint an invalid or missingContent-Type, which breaks clients and leaves unknown files sniffable. Please add explicit mappings for the supported audio/video/image formats and fall back toapplication/octet-streamfor every unmapped case.Also applies to: 235-247
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/utility/file.go` around lines 137 - 199, Update the CONTENT_TYPE_MAP to include explicit MIME mappings for common audio/video/image formats (e.g., mp3, wav, aac, ogg, flac, amr, wma, aac, avi variants, asf, mpe, etc.) and ensure the GetContentType function returns "application/octet-stream" for any unmapped or extensionless files; also apply the same additions to the other duplicate map instance referenced in the file so both lookup sites use the expanded CONTENT_TYPE_MAP and the safe default.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/handler/file.go`:
- Around line 456-459: The handler currently maps every GetFileContent error to
common.CodeUnauthorized; change it to distinguish not-found errors by checking
the returned error from h.fileService.GetFileContent and returning
common.CodeNotFound (instead of CodeUnauthorized) when the error indicates a
missing document (e.g., err.Error() == "Document not found!" or, better, by
matching a sentinel error from the service if available), otherwise keep the
unauthorized response; update the code around the call to
h.fileService.GetFileContent and the jsonError calls accordingly.
- Around line 472-493: The code treats zero-length blob as missing; change the
logic in the block around file.Location, storageImpl.Get and the fallback to use
the storage error (getErr) or an explicit not-found sentinel instead of
len(blob)==0: call storageImpl.Get(file.ParentID, *file.Location) and if getErr
!= nil && isNotFound(getErr) then call h.fileService.GetStorageAddress(fileID)
and retry with storageImpl.Get(storageAddr.Bucket, storageAddr.Name); treat a
successful Get (getErr == nil) — even if len(blob) == 0 — as a valid result and
only return the “Failed to retrieve file blob” jsonError when getErr != nil (or
when the storage not-found sentinel indicates the object truly does not exist);
update any helpers or checks to use the storage package’s not-found sentinel
(e.g., storage.IsNotFound or storage.ErrNotFound) when deciding to fallback or
error.
- Around line 508-509: The current use of url.QueryEscape to produce encodedName
for the Content-Disposition header is incorrect for RFC 5987 (it encodes spaces
as '+' and doesn't percent-encode required characters); replace that logic by
implementing RFC 5987 ext-value percent-encoding for file.Name (UTF-8 bytes ->
percent-encode octets, ensure "'" and other reserved chars are percent-encoded
and use UTF-8'' prefix) and then set the header using
c.Header("Content-Disposition", "attachment; filename*="+rfc5987Encoded) so
clients handle non-ASCII and spaces correctly; update the code paths that
reference encodedName/file.Name to use the new rfc5987 encoder function.
---
Duplicate comments:
In `@internal/utility/file.go`:
- Around line 137-199: Update the CONTENT_TYPE_MAP to include explicit MIME
mappings for common audio/video/image formats (e.g., mp3, wav, aac, ogg, flac,
amr, wma, aac, avi variants, asf, mpe, etc.) and ensure the GetContentType
function returns "application/octet-stream" for any unmapped or extensionless
files; also apply the same additions to the other duplicate map instance
referenced in the file so both lookup sites use the expanded CONTENT_TYPE_MAP
and the safe default.
🪄 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: 71718e2d-ef28-4f05-a7a5-50717e2b79ff
📒 Files selected for processing (5)
internal/dao/document.gointernal/dao/file.gointernal/handler/file.gointernal/service/file.gointernal/utility/file.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/service/file.go
- internal/dao/file.go
| file, err := h.fileService.GetFileContent(userID, fileID) | ||
| if err != nil { | ||
| jsonError(c, common.CodeUnauthorized, err.Error()) | ||
| return |
There was a problem hiding this comment.
Return “not found” separately from “unauthorized”.
GetFileContent in internal/service/file.go:915-925 returns "Document not found!" for a missing file, but this handler converts every failure into common.CodeUnauthorized. That gives clients the wrong error branch for missing IDs.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/handler/file.go` around lines 456 - 459, The handler currently maps
every GetFileContent error to common.CodeUnauthorized; change it to distinguish
not-found errors by checking the returned error from
h.fileService.GetFileContent and returning common.CodeNotFound (instead of
CodeUnauthorized) when the error indicates a missing document (e.g., err.Error()
== "Document not found!" or, better, by matching a sentinel error from the
service if available), otherwise keep the unauthorized response; update the code
around the call to h.fileService.GetFileContent and the jsonError calls
accordingly.
| if file.Location != nil && *file.Location != "" { | ||
| blob, getErr = storageImpl.Get(file.ParentID, *file.Location) | ||
| } | ||
|
|
||
| // If blob is empty, try fallback via file2document | ||
| if len(blob) == 0 { | ||
| storageAddr, err := h.fileService.GetStorageAddress(fileID) | ||
| if err != nil { | ||
| jsonError(c, common.CodeServerError, "Failed to get file storage address: "+err.Error()) | ||
| return | ||
| } | ||
| blob, getErr = storageImpl.Get(storageAddr.Bucket, storageAddr.Name) | ||
| } | ||
|
|
||
| // Check if we got valid data | ||
| if len(blob) == 0 { | ||
| errMsg := "Failed to retrieve file blob" | ||
| if getErr != nil { | ||
| errMsg += ": " + getErr.Error() | ||
| } | ||
| jsonError(c, common.CodeServerError, errMsg) | ||
| return |
There was a problem hiding this comment.
Don't treat zero-byte files as missing.
This path uses len(blob) == 0 to decide whether storage lookup failed. A valid empty file will fall through to the fallback path and can still end up as "Failed to retrieve file blob" even when the object exists. Key the retry/error logic off storage errors or an explicit not-found signal instead of payload length.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/handler/file.go` around lines 472 - 493, The code treats zero-length
blob as missing; change the logic in the block around file.Location,
storageImpl.Get and the fallback to use the storage error (getErr) or an
explicit not-found sentinel instead of len(blob)==0: call
storageImpl.Get(file.ParentID, *file.Location) and if getErr != nil &&
isNotFound(getErr) then call h.fileService.GetStorageAddress(fileID) and retry
with storageImpl.Get(storageAddr.Bucket, storageAddr.Name); treat a successful
Get (getErr == nil) — even if len(blob) == 0 — as a valid result and only return
the “Failed to retrieve file blob” jsonError when getErr != nil (or when the
storage not-found sentinel indicates the object truly does not exist); update
any helpers or checks to use the storage package’s not-found sentinel (e.g.,
storage.IsNotFound or storage.ErrNotFound) when deciding to fallback or error.
| encodedName := url.QueryEscape(file.Name) | ||
| c.Header("Content-Disposition", "attachment; filename*=UTF-8''"+encodedName) |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
In Go's standard library, is url.QueryEscape appropriate for an HTTP Content-Disposition filename* parameter, or should url.PathEscape or mime.FormatMediaType be used for RFC 5987-compatible encoding?
💡 Result:
url.QueryEscape is not appropriate for Content-Disposition: ...; filename*=... because it implements URL query escaping and turns spaces into + (form-style), while filename* (RFC 5987 as used by RFC 6266) uses percent-encoding (e.g. spaces as %20) inside an ext-value like UTF-8''.... In Go’s net/url, QueryEscape explicitly encodes spaces as + in query mode. [1] RFC 6266 shows filename* examples using %20, and defines filename* as an ext-value from RFC 5987. [2]
url.PathEscape is closer (it uses %20 for spaces), but it is still not RFC 5987–correct, because RFC 5987’s allowed character set for the value portion is narrower than an RFC 3986 path segment (notably it must percent-encode characters like ', (, ), etc., since ' is a delimiter in charset'lang'value). [2][3]
mime.FormatMediaType is useful to correctly format the overall header and quote the ASCII filename="..." fallback, but Go’s standard library mime.FormatMediaType only targets RFC 2045 / RFC 2616 “media type with parameters” formatting and does not implement RFC 5987 filename* encoding for you. [4]
Practical guidance (stdlib-only):
- Use
mime.FormatMediaType("attachment", map[string]string{"filename": asciiFallback})forfilename=...(ASCII) [4] - Append
; filename*=UTF-8''+ your own RFC 5987 percent-encoder for the UTF-8 name (do not useQueryEscape, and don’t rely onPathEscapeto be fully correct). [1][2]
Sources
- Go
net/urlsource showsQueryEscapeencodes spaces as+in query mode. [1] - RFC 6266 defines
filename*and gives examples likefilename*=utf-8''%e2%82%ac%20rates. [2] - RFC 5987 defines
ext-valueascharset'lang'value, making'a delimiter that cannot appear unescaped in the value. [3] - Go
mime.FormatMediaTypedocs: formats per RFC 2045 and RFC 2616; no RFC 5987 support mentioned. [4]
[1] (go.googlesource.com) [2] (ietf.org) [3] (datatracker.ietf.org) [4] (pkg.go.dev)
Citations:
- 1: https://go.googlesource.com/go/%2B/refs/heads/dev.boringcrypto.go1.15/src/net/url/url.go
- 2: https://www.ietf.org/ietf-ftp/rfc/rfc6266.txt.pdf
- 3: https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-content-disp-04?utm_source=openai
- 4: https://pkg.go.dev/mime
Use proper RFC 5987 percent-encoding for filename*= parameter.
url.QueryEscape encodes spaces as +, which is query-string encoding, not RFC 5987 encoding required by Content-Disposition: attachment; filename*=. This causes clients to save filenames with literal + characters or mishandle non-ASCII names.
url.PathEscape and mime.FormatMediaType are insufficient here—neither implements the RFC 5987 ext-value encoding spec (which requires percent-encoding of ' as a delimiter and other reserved characters). Implement proper RFC 5987 percent-encoding for the UTF-8 name, or use a library that handles filename*= correctly.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/handler/file.go` around lines 508 - 509, The current use of
url.QueryEscape to produce encodedName for the Content-Disposition header is
incorrect for RFC 5987 (it encodes spaces as '+' and doesn't percent-encode
required characters); replace that logic by implementing RFC 5987 ext-value
percent-encoding for file.Name (UTF-8 bytes -> percent-encode octets, ensure "'"
and other reserved chars are percent-encoded and use UTF-8'' prefix) and then
set the header using c.Header("Content-Disposition", "attachment;
filename*="+rfc5987Encoded) so clients handle non-ASCII and spaces correctly;
update the code paths that reference encodedName/file.Name to use the new
rfc5987 encoder function.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14011 +/- ##
==========================================
- Coverage 98.11% 96.66% -1.45%
==========================================
Files 10 10
Lines 690 690
Branches 108 108
==========================================
- Hits 677 667 -10
- Misses 4 8 +4
- Partials 9 15 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
### What problem does this PR solve? feat: Implement file-related functionality - Implement file deletion API and business logic - Add context support for file deletion operations and prevent root folder deletion - Implement file move functionality - Add File Download API Endpoints and Utility Functions ### Type of change - [x] New Feature (non-breaking change which adds functionality) --------- Co-authored-by: Yingfeng <[email protected]>
feat: Implement file-related functionality - Implement file deletion API and business logic - Add context support for file deletion operations and prevent root folder deletion - Implement file move functionality - Add File Download API Endpoints and Utility Functions - [x] New Feature (non-breaking change which adds functionality) --------- Co-authored-by: Yingfeng <[email protected]>
feat: Implement file-related functionality - Implement file deletion API and business logic - Add context support for file deletion operations and prevent root folder deletion - Implement file move functionality - Add File Download API Endpoints and Utility Functions - [x] New Feature (non-breaking change which adds functionality) --------- Co-authored-by: Yingfeng <[email protected]>
### What problem does this PR solve? feat: Implement file-related functionality - Implement file deletion API and business logic - Add context support for file deletion operations and prevent root folder deletion - Implement file move functionality - Add File Download API Endpoints and Utility Functions ### Type of change - [x] New Feature (non-breaking change which adds functionality) --------- Co-authored-by: Yingfeng <[email protected]>
What problem does this PR solve?
feat: Implement file-related functionality
Type of change