Skip to content

feat(go-api): implement dataset document upload API - #16295

Merged
yuzhichang merged 4 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/dataset-documents/post
Jun 25, 2026
Merged

yuzhichang merged 4 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/dataset-documents/post

Conversation

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

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

  • Router: Registered POST /api/v1/datasets/:dataset_id/documents route.
  • Handler: Implemented UploadDocuments handler and its routing functions (uploadLocalDocuments, uploadWebDocument, uploadEmptyDocument).
  • Service: Implemented UploadLocalDocuments, UploadWebDocument, and UploadEmptyDocument in DocumentService.
  • Refactoring: Moved permission checking logic to a shared helper for reuse in file and document services.
  • Tests: Added comprehensive unit tests for the new handler and service upload paths.

Verification

Ran and passed the test suite for service and handler packages:

  • go test ./internal/service
  • go test ./internal/handler

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 24, 2026
@Harry-Hz-Zhang Harry-Hz-Zhang added ci Continue Integration and removed 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 24, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 24, 2026 05:11
@coderabbitai

coderabbitai Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 36baaabb-8872-43a3-9972-14bcc7651176

📥 Commits

Reviewing files that changed from the base of the PR and between f5d80d8 and 1d78316.

📒 Files selected for processing (7)
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/router/router.go
  • internal/service/dataset.go
  • internal/service/document.go
  • internal/service/document_test.go
  • internal/service/file.go
💤 Files with no reviewable changes (3)
  • internal/service/file.go
  • internal/service/document.go
  • internal/service/document_test.go
✅ Files skipped from review due to trivial changes (1)
  • internal/router/router.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/service/dataset.go
  • internal/handler/document_test.go
  • internal/handler/document.go

📝 Walkthrough

Walkthrough

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

Changes

Document Upload Feature

Layer / File(s) Summary
Shared KB team-permission helper and refactoring
internal/service/team_permission.go, internal/service/file.go, internal/service/file2document.go
Introduces hasKBTeamPermission and rewires file.go and file2document.go to use it. file2document.go also switches parser selection to selectUploadParser and resolves file access through related datasets and KBs.
Upload helpers and KB lookup
go.mod, internal/service/document_upload_helpers.go, internal/dao/document.go, internal/service/dataset.go
Adds the xxh3 dependency, parser-selection and content-hash helpers, document-name lookup by KB, and dataset-service KB lookup and permission-check methods.
Core upload service methods and file-manager linkage
internal/service/document.go
Adds upload service methods for local, empty, and web uploads, along with KB folder creation, file linkage, raw document mapping, name deduplication, and bounded multipart reads.
UploadDocuments handler and route
internal/handler/document.go, internal/router/router.go
Adds UploadDocuments, the local/empty/web request handlers, response helpers, service interface updates, and the authenticated dataset documents POST route.
Service and handler upload tests
internal/service/document_test.go, internal/handler/document_test.go
Adds multipart and storage test helpers, service tests for parser selection and upload behavior, and handler tests for upload success paths and authorization denial.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

💞 feature

Suggested reviewers

  • yuzhichang

Poem

🐇 I hop through uploads, swift and neat,
A parser picks the docs to greet.
With hashes, folders, links in place,
The KB stores each file with grace.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the work, but it does not follow the required template and is missing the 'Type of change' section. Add the template headings 'What problem does this PR solve?' and 'Type of change', and fill the checklist with the appropriate change type.
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: implementing the dataset document upload API.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 24, 2026 05:11

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0c19190 and bd46b03.

📒 Files selected for processing (12)
  • go.mod
  • internal/dao/document.go
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/router/router.go
  • internal/service/dataset.go
  • internal/service/document.go
  • internal/service/document_test.go
  • internal/service/document_upload_helpers.go
  • internal/service/file.go
  • internal/service/file2document.go
  • internal/service/team_permission.go

Comment thread internal/handler/document.go Resolved
Comment thread internal/router/router.go Resolved
Comment thread internal/service/document.go Outdated
Comment on lines +2385 to +2393
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,
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Comment thread internal/service/document.go Outdated
Comment on lines +2396 to +2402
// 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")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread internal/service/document.go Outdated
Comment on lines +2491 to +2501
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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

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

codecov Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (06d45c5) to head (1d78316).
⚠️ Report is 1 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 25, 2026 03:21
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 25, 2026 03:21
@yuzhichang
yuzhichang merged commit a6cc302 into infiniflow:main Jun 25, 2026
3 of 6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants