Skip to content

feat(go-api): Align document metadata batch APIs and upload_info with Python - #16269

Merged
yuzhichang merged 3 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/dataset-metadata/patch/post
Jun 24, 2026
Merged

yuzhichang merged 3 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/dataset-metadata/patch/post

Conversation

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

Summary

Align the Go implementations of these APIs with the Python behavior:

  • POST /api/v1/datasets/:dataset_id/metadata/update
  • PATCH /api/v1/datasets/:dataset_id/documents/metadatas
  • POST /api/v1/documents/upload

What changed

  • Added the Go routes and handlers for the 3 APIs.
  • Aligned batch document metadata updates with Python semantics:
    • support match in update items
    • support list append / replace behavior
    • support deleting specific list values
    • remove metadata entirely when it becomes empty
    • create metadata for documents that previously had none when updates apply
    • count updated only when a document actually changes
  • Aligned documents/upload file uploads with Python-style upload_info behavior:
    • store upload-info blobs in the per-user downloads bucket
    • return lightweight upload descriptors instead of normal file-management responses
  • Improved URL upload behavior:
    • SSRF-guarded fetch with redirect validation
    • redirect limit aligned to Python behavior
    • normalize filename and MIME type
    • add .pdf when the fetched content is PDF
    • normalize HTML content into readable text instead of storing raw HTML shells

Validation

Unit tests

Passed:

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

Also verified targeted cases for:

  • batch metadata update semantics
  • upload_info URL handling
  • upload_info download bucket behavior

curl checks

Verified the new Go endpoints with curl and compared the response shape and behavior with Python for:

  • POST /api/v1/datasets/{dataset_id}/metadata/update
  • PATCH /api/v1/datasets/{dataset_id}/documents/metadatas
  • POST /api/v1/documents/upload

The Go responses were checked against Python for:

  • argument validation
  • success response shape
  • metadata update results
  • upload_info result structure
  • file vs URL input handling

@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 23, 2026
@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds three new authenticated API endpoints: POST /api/v1/documents/upload for multipart or URL-based document info ingestion, POST /api/v1/datasets/:dataset_id/metadata/update, and PATCH /api/v1/datasets/:dataset_id/documents/metadatas for batch metadata updates/deletes with match semantics. Implements SSRF-protected URL fetching, HTML-to-markdown normalization, filename sanitization, and deep clone/apply/compare logic for metadata mutation.

Changes

Document Upload Info and Batch Metadata Update

Layer / File(s) Summary
FileService upload-info and remote URL fetch logic
internal/service/file.go
Adds UploadInfos (multipart) and UploadFromURL methods with SSRF-guarded HTTP fetching with per-hop IP validation, 100MB size cap, HTML-to-markdown normalization, filename sanitization (including Windows reserved-name protection), blob persistence to per-user downloads buckets, and package-level assertURLSafe/pinnedHTTPClient aliases.
FileService upload-from-URL tests
internal/service/file_test.go
Extends fakeStorage to track Put/ObjExist calls; adds four tests for PDF extension/MIME assertion, HTML normalization/content stripping, PDF precedence over HTML detection, and oversized input rejection, all using httptest servers with overridden URL-safety/HTTP-client globals.
BatchUpdateDocumentMetadatas service types, logic, and helpers
internal/service/document.go, internal/service/metadata.go
Introduces DocumentMetadataUpdate, DocumentMetadataDelete, DocumentMetadataSelector, and BatchUpdateDocumentMetadatasResponse types; implements BatchUpdateDocumentMetadatas with document-ID resolution, per-document deep-clone/update/delete/compare cycle, and empty-metadata deletion; adds all internal helpers for value normalization, list dedup, and metadata flattening; adds UploadDocumentInfos/UploadDocumentInfoByURL delegation and request validation; expands mergeFieldValues to handle numeric, boolean, and []string types.
BatchUpdateDocumentMetadatas tests with in-memory engine
internal/service/document_test.go
Introduces metadataDocEngine with in-memory SearchMetadata, UpdateMetadata, and DeleteMetadata; adds six tests validating match-based update/delete semantics, no-op behavior, numeric string normalization, validation rejection, nested empty list handling in aggregateMetadata, and numeric preservation in mergeFieldValues.
Handler methods and router wiring
internal/handler/document.go, internal/handler/document_test.go, internal/router/router.go
Extends documentServiceIface with the three new methods; adds UploadInfo, MetadataBatchUpdate, and UpdateDocumentMetadatas handlers with input validation and handleBatchUpdateDocumentMetadatas shared logic; updates fakeDocumentService stubs; registers all three routes.

Sequence Diagram(s)

sequenceDiagram
  rect rgba(173, 216, 230, 0.5)
    note over Client,FileService: Upload Info Flow
    Client->>DocumentHandler: POST /api/v1/documents/upload
    DocumentHandler->>DocumentService: UploadDocumentInfos(files) or UploadDocumentInfoByURL(url)
    DocumentService->>FileService: UploadInfos(userID, files) or UploadFromURL(tenantID, url)
    FileService->>FileService: fetchRemoteFileSafely + SSRF guards
    FileService->>FileService: normalizeUploadInfoContent (HTML→markdown, PDF detection)
    FileService->>Storage: Put to {userID}-downloads bucket
    Storage-->>FileService: stored key
    FileService-->>DocumentHandler: descriptor map
    DocumentHandler-->>Client: 200 with upload metadata
  end
  rect rgba(144, 238, 144, 0.5)
    note over Client,MetadataStore: Batch Metadata Update Flow
    Client->>DocumentHandler: POST/PATCH /datasets/:id/metadata/update
    DocumentHandler->>DocumentService: BatchUpdateDocumentMetadatas(datasetID, selector, updates, deletes)
    DocumentService->>MetadataStore: SearchMetadata with selector/conditions
    MetadataStore-->>DocumentService: matched document IDs
    loop each matched document
      DocumentService->>MetadataStore: fetch + clone current metadata
      DocumentService->>DocumentService: applyDocumentMetadataUpdates + applyDocumentMetadataDeletes
      DocumentService->>MetadataStore: UpdateMetadata or DeleteMetadata
    end
    DocumentService-->>Client: BatchUpdateDocumentMetadatasResponse
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related issues

  • [Subtask]: Implement remaining Document/metadata APIs in Go #15671: This PR directly implements the three document/metadata API endpoints (POST /api/v1/documents/upload, PATCH /api/v1/datasets/<dataset_id>/documents/metadatas, POST /api/v1/datasets/<dataset_id>/metadata/update) specified as tasks in this issue, with matching handler methods, service logic, and route registrations.

Suggested reviewers

  • Haruko386

Poem

🐇 Hop hop, a new upload path appears,
From multipart files to URLs, no fears!
SSRF guards keep the bad actors away,
Metadata batches update and sway.
The rabbit stores blobs in downloads buckets bright,
And HTML turns to markdown — what a delight! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides comprehensive details but does not follow the template structure with the required 'What problem does this PR solve?' and 'Type of change' sections. Restructure the description to include the template sections: add a 'What problem does this PR solve?' section at the top and include the 'Type of change' checklist with the appropriate option selected.
Docstring Coverage ⚠️ Warning Docstring coverage is 19.51% 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
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.
Title check ✅ Passed The title clearly summarizes the main change: aligning the document metadata batch APIs and upload_info behavior with Python.

✏️ 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 added the ci Continue Integration label Jun 23, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft June 23, 2026 09:34
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review June 23, 2026 09:34

@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: 3

🤖 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/document.go`:
- Around line 2295-2298: The validation check in the loop over updates only
verifies that the Key field is not empty but does not check that the Value field
is also provided. Update the conditional in the loop that checks
`strings.TrimSpace(upd.Key) == ""` to also validate that `upd.Value` is not
empty or nil, ensuring both key and value are required for each update before
processing reaches `applyDocumentMetadataUpdates`.

In `@internal/service/file.go`:
- Around line 419-427: The multipart file upload in this function reads the
entire file into memory without size constraints, which can exhaust handler
memory for large authenticated uploads. Wrap the opened file source with
io.LimitedReader using the same maxRemoteFileSize limit that is applied to URL
uploads, then pass the limited reader to io.ReadAll instead of the raw src file
returned by fileHeader.Open().
- Around line 1329-1340: The code currently processes HTML conversion via
htmlToReadableMarkdown before checking for PDF content via bytesLooksLikePDF,
which corrupts binary PDF data when PDFs are served with text/html content type.
Reorder the conditional blocks so that the PDF detection check (the condition
checking lowerCT == "application/pdf" || bytesLooksLikePDF(data)) executes
before the HTML normalization block, ensuring PDF content is identified and
preserved before any markdown conversion is attempted.
🪄 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: 58be9f05-ca7a-436b-b0fa-9b13739b9ec1

📥 Commits

Reviewing files that changed from the base of the PR and between dec2ce4 and 78b9279.

📒 Files selected for processing (8)
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/router/router.go
  • internal/service/document.go
  • internal/service/document_test.go
  • internal/service/file.go
  • internal/service/file_test.go
  • internal/service/metadata.go

Comment thread internal/service/document.go Resolved
Comment thread internal/service/file.go Resolved
Comment thread internal/service/file.go Resolved
@codecov

codecov Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16269   +/-   ##
=======================================
  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 changed the title feat: Align document metadata batch APIs and upload_info with Python feat(go-api): Align document metadata batch APIs and upload_info with Python Jun 24, 2026

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. lgtm This PR has been approved by a maintainer 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