Repository navigation
feat(go-api): implement dataset document upload API - #16295
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (7)
💤 Files with no reviewable changes (3)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughAdds dataset document upload handling for local multipart files, empty documents, and web uploads. Adds shared KB permission checks, parser-selection and content-hash helpers, upload service logic, a new dataset documents POST route, and test coverage for upload flows. ChangesDocument Upload Feature
Sequence Diagram(s)sequenceDiagram
participant Client
participant UploadDocuments
participant DatasetService
participant DocumentService
participant ObjectStorage
participant Database
Client->>UploadDocuments: POST /api/v1/datasets/:dataset_id/documents?type=local
UploadDocuments->>DatasetService: GetKnowledgebaseByID(dataset_id)
DatasetService-->>UploadDocuments: kb
UploadDocuments->>DatasetService: CheckKBTeamPermission(kb, userID)
DatasetService-->>UploadDocuments: allowed / denied
UploadDocuments->>DocumentService: UploadLocalDocuments(kb, tenantID, files, path, override)
DocumentService->>Database: ListNamesByKbID
DocumentService->>ObjectStorage: Put(blob)
DocumentService->>Database: Insert document row
DocumentService->>Database: addFileFromKB / file2document link
DocumentService-->>UploadDocuments: raw documents + errors
UploadDocuments-->>Client: JSON response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ 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: 5
🤖 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/document.go`:
- Around line 605-608: The UploadLocalDocuments flow in documentHandler
currently treats any per-file error as a full request failure and discards the
successful `data`, which can cause duplicate uploads on retry. Update this
branch to return the successful upload results from
`h.documentService.UploadLocalDocuments` even when `errMsgs` is non-empty, and
only surface the file-level errors alongside the partial success instead of
calling `jsonError` and returning a total failure.
In `@internal/router/router.go`:
- Line 297: The upload route registered in router setup is missing the leading
slash, so the Gin group path is concatenated incorrectly. Update the route
registration in the datasets route block where UploadDocuments is attached so it
uses the proper “/:dataset_id/documents” pattern, ensuring the endpoint matches
the documented /api/v1/datasets/:dataset_id/documents path.
In `@internal/service/document.go`:
- Around line 2385-2393: The file-manager entry created in the document upload
flow is not cleaned up if the later file-to-document mapping insert fails,
leaving an orphaned File record. Update the create path in s.fileDAO.Create and
s.file2DocumentDAO.Create so that when file2DocumentDAO.Create returns an error,
the newly created File row is rolled back or deleted before returning the error.
Use the existing fileID/docID values and the surrounding document creation logic
to locate the cleanup point.
- Around line 2396-2402: The UploadWebDocument path in DocumentService is still
a stub that always returns a “not supported” error, so the web upload mode
exposed by the handler remains nonfunctional. Replace the hardcoded failure in
UploadWebDocument with the real web-upload flow used by the endpoint: fetch the
URL content, convert it to the expected document/PDF representation, generate
the thumbnail, and return the same result structure as the other upload paths.
Use the existing UploadWebDocument method and its surrounding handler wiring to
ensure type=web succeeds instead of always failing.
- Around line 2491-2501: The readFileHeaderBytes helper is silently truncating
uploads when fh.Size under-reports the actual content, because the
io.LimitReader path never verifies whether more data exists. Update
readFileHeaderBytes to detect oversized content beyond maxUploadDocSize by
checking for extra bytes after reading the capped payload, and return an error
instead of succeeding with truncated data. Keep the fix localized to
readFileHeaderBytes in document.go so callers that rely on the returned blob and
hash only proceed for complete files.
🪄 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: 12933922-873a-4d33-a526-3ec3042c4c97
📒 Files selected for processing (12)
go.modinternal/dao/document.gointernal/handler/document.gointernal/handler/document_test.gointernal/router/router.gointernal/service/dataset.gointernal/service/document.gointernal/service/document_test.gointernal/service/document_upload_helpers.gointernal/service/file.gointernal/service/file2document.gointernal/service/team_permission.go
| if err := s.fileDAO.Create(file); err != nil { | ||
| return err | ||
| } | ||
| docID := doc.ID | ||
| return s.file2DocumentDAO.Create(&entity.File2Document{ | ||
| ID: strings.ReplaceAll(uuid.New().String(), "-", ""), | ||
| FileID: &fileID, | ||
| DocumentID: &docID, | ||
| }) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Roll back the File row when the mapping insert fails.
Lines 2385-2393 create the file-manager entry before the file2document row. If file2DocumentDAO.Create fails, callers only remove the blob/document, so the orphaned file row remains and pollutes the dataset folder state.
🤖 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/service/document.go` around lines 2385 - 2393, The file-manager
entry created in the document upload flow is not cleaned up if the later
file-to-document mapping insert fails, leaving an orphaned File record. Update
the create path in s.fileDAO.Create and s.file2DocumentDAO.Create so that when
file2DocumentDAO.Create returns an error, the newly created File row is rolled
back or deleted before returning the error. Use the existing fileID/docID values
and the surrounding document creation logic to locate the cleanup point.
| // UploadWebDocument is not yet supported on the Go server: the Python path | ||
| // converts the URL to PDF via html2pdf and generates a thumbnail, neither of | ||
| // which has a Go equivalent. Request validation happens in the handler; this | ||
| // surfaces an explicit, honest error rather than silently misbehaving. | ||
| func (s *DocumentService) UploadWebDocument(kb *entity.Knowledgebase, tenantID, name, url string) (map[string]interface{}, common.ErrorCode, error) { | ||
| return nil, common.CodeServerError, fmt.Errorf("web upload (URL → PDF) is not supported by the Go server yet") | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🔴 Critical | 🏗️ Heavy lift
type=web is wired up but still guaranteed to fail.
Line 2400 returns a hardcoded “not supported” error for every request. The handler exposes type=web, and the PR objective says web uploads are part of this endpoint, so this mode is still nonfunctional as merged.
🤖 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/service/document.go` around lines 2396 - 2402, The UploadWebDocument
path in DocumentService is still a stub that always returns a “not supported”
error, so the web upload mode exposed by the handler remains nonfunctional.
Replace the hardcoded failure in UploadWebDocument with the real web-upload flow
used by the endpoint: fetch the URL content, convert it to the expected
document/PDF representation, generate the thumbnail, and return the same result
structure as the other upload paths. Use the existing UploadWebDocument method
and its surrounding handler wiring to ensure type=web succeeds instead of always
failing.
| func readFileHeaderBytes(fh *multipart.FileHeader) ([]byte, error) { | ||
| if fh.Size > maxUploadDocSize { | ||
| return nil, fmt.Errorf("file exceeds the maximum allowed size of %d bytes", maxUploadDocSize) | ||
| } | ||
| src, err := fh.Open() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| defer src.Close() | ||
| // LimitReader guards against a header that under-reports the real size. | ||
| return io.ReadAll(io.LimitReader(src, maxUploadDocSize)) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Detect under-reported oversized files instead of silently truncating them.
Line 2501 caps the reader at maxUploadDocSize, but it never checks whether more bytes were available. If fh.Size under-reports the upload, this path stores and hashes a truncated blob as a successful document.
Proposed fix
func readFileHeaderBytes(fh *multipart.FileHeader) ([]byte, error) {
if fh.Size > maxUploadDocSize {
return nil, fmt.Errorf("file exceeds the maximum allowed size of %d bytes", maxUploadDocSize)
}
src, err := fh.Open()
if err != nil {
return nil, err
}
defer src.Close()
- // LimitReader guards against a header that under-reports the real size.
- return io.ReadAll(io.LimitReader(src, maxUploadDocSize))
+ data, err := io.ReadAll(io.LimitReader(src, maxUploadDocSize+1))
+ if err != nil {
+ return nil, err
+ }
+ if int64(len(data)) > maxUploadDocSize {
+ return nil, fmt.Errorf("file exceeds the maximum allowed size of %d bytes", maxUploadDocSize)
+ }
+ return data, 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.
| func readFileHeaderBytes(fh *multipart.FileHeader) ([]byte, error) { | |
| if fh.Size > maxUploadDocSize { | |
| return nil, fmt.Errorf("file exceeds the maximum allowed size of %d bytes", maxUploadDocSize) | |
| } | |
| src, err := fh.Open() | |
| if err != nil { | |
| return nil, err | |
| } | |
| defer src.Close() | |
| // LimitReader guards against a header that under-reports the real size. | |
| return io.ReadAll(io.LimitReader(src, maxUploadDocSize)) | |
| func readFileHeaderBytes(fh *multipart.FileHeader) ([]byte, error) { | |
| if fh.Size > maxUploadDocSize { | |
| return nil, fmt.Errorf("file exceeds the maximum allowed size of %d bytes", maxUploadDocSize) | |
| } | |
| src, err := fh.Open() | |
| if err != nil { | |
| return nil, err | |
| } | |
| defer src.Close() | |
| data, err := io.ReadAll(io.LimitReader(src, maxUploadDocSize+1)) | |
| if err != nil { | |
| return nil, err | |
| } | |
| if int64(len(data)) > maxUploadDocSize { | |
| return nil, fmt.Errorf("file exceeds the maximum allowed size of %d bytes", maxUploadDocSize) | |
| } | |
| return data, nil | |
| } |
🤖 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/service/document.go` around lines 2491 - 2501, The
readFileHeaderBytes helper is silently truncating uploads when fh.Size
under-reports the actual content, because the io.LimitReader path never verifies
whether more data exists. Update readFileHeaderBytes to detect oversized content
beyond maxUploadDocSize by checking for extra bytes after reading the capped
payload, and return an error instead of succeeding with truncated data. Keep the
fix localized to readFileHeaderBytes in document.go so callers that rely on the
returned blob and hash only proceed for complete files.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16295 +/- ##
=======================================
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:
|
Summary
Migrated the dataset document upload API (
POST /api/v1/datasets/:dataset_id/documents) from Python to the Go backend. It supports local file uploads (type=local), web page ingestion (type=web), and empty document creation (type=empty).Changes
POST /api/v1/datasets/:dataset_id/documentsroute.UploadDocumentshandler and its routing functions (uploadLocalDocuments,uploadWebDocument,uploadEmptyDocument).UploadLocalDocuments,UploadWebDocument, andUploadEmptyDocumentinDocumentService.Verification
Ran and passed the test suite for service and handler packages:
go test ./internal/servicego test ./internal/handler