Skip to content

feat[Go]: implement document upload, dataset metadata bulk-update APIs - #15672

Closed
hunnyboy1217 wants to merge 9 commits into
infiniflow:mainfrom
hunnyboy1217:feat/go-document-metadata-upload-apis
Closed

hunnyboy1217 wants to merge 9 commits into
infiniflow:mainfrom
hunnyboy1217:feat/go-document-metadata-upload-apis

Conversation

@hunnyboy1217

@hunnyboy1217 hunnyboy1217 commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Closes #15671 — ports three Document/metadata endpoints from Python (api/apps/restful_apis/document_api.py) to the Go API layer.

Method Path Handler Python source
POST /api/v1/documents/upload UploadInfo upload_info
PATCH /api/v1/datasets/:dataset_id/documents/metadatas UpdateDocumentMetadatas update_metadata
POST /api/v1/datasets/:dataset_id/metadata/update MetadataBatchUpdate metadata_batch_update

Type of change

  • New Feature (non-breaking change which adds functionality)

Implementation notes

Files changed:

internal/service/file.go      – UploadFromURL helper
internal/service/document.go  – BatchUpdateDocumentMetadata + supporting types
internal/handler/document.go  – three new handlers + shared batchMetadataUpdate
internal/router/router.go     – route registration

Functional parity table:

Concern Go behaviour
UploadInfo — file path c.MultipartForm() → fileService.UploadFile(tenantID, "", files) (existing method); single file returns scalar, multiple returns array — same as Python
UploadInfo — URL path New FileService.UploadFromURL: validates http/https scheme, GET remote content (100 MB cap), stores to tenant root folder, returns same file-info map as the file path
Both inputs provided Returns CodeArgumentError mirroring Python get_error_argument_result
Neither provided Returns CodeArgumentError
PATCH /metadatas and POST /metadata/update Identical logic via shared batchMetadataUpdate(c) — dataset access check via datasetService.Accessible, request body validated, delegated to DocumentService.BatchUpdateDocumentMetadata
document_ids validation documentDAO.GetAllDocIDsByKBIDs([datasetID]) builds allowed set; unknown IDs returned as error — mirrors KnowledgebaseService.list_documents_by_ids
metadata_condition filter metadataSvc.GetFlattedMetaByKBs([datasetID]) + ApplyMetaFilter(flattedMeta, conditions, logic) — reuses the same Go function already used by RetrievalTest
Selector intersection When both document_ids and metadata_condition given, result is their intersection (Python target_doc_ids & filtered_ids)
Early exit When metadata_condition.conditions present but nothing matched: returns {updated:0, matched_docs:0}
Per-doc update SetDocumentMetadata for updates, DeleteDocumentMetadata for deletes
Response {updated: N, matched_docs: M} matching Python's get_result(data={...}) shape

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 4, 2026
@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds multipart or URL document upload with SSRF-safe remote fetching and filename sanitization, implements DocumentService batch metadata selector/updates/deletes, and exposes three HTTP endpoints with tests: upload and two dataset-level bulk metadata operations.

Changes

Document upload and batch metadata management

Layer / File(s) Summary
File upload service
internal/service/file.go, internal/service/file_test.go
Implements FileService.UploadFromURL with SSRF-safe fetch (fetchRemoteFileSafely), max 100MB cap, isPublicIP, sanitizeFilename (reserved-name guard), storage persistence, and entity.File creation; adds unit tests for filename sanitization, IP checks, and invalid URL handling.
Batch metadata update service
internal/service/document.go
Adds MetadataSelector, MetadataUpdate, MetadataDelete, BatchUpdateMetadataRequest/Result and DocumentService.BatchUpdateDocumentMetadata to resolve/validate target document IDs, optionally filter by metadata conditions, apply per-document set/delete ops with per-document warnings, and return matched/updated counts.
HTTP handlers, routes, and handler tests
internal/handler/document.go, internal/router/router.go, internal/handler/document_test.go, internal/handler/file_handler_test.go
DocumentHandler adds fileService and extends documentServiceIface; implements UploadInfo (multipart file or ?url=, mutual-exclusion validation) and shared batchMetadataUpdate used by UpdateDocumentMetadatas and MetadataBatchUpdate; router registers POST /api/v1/documents/upload, POST /api/v1/datasets/:dataset_id/metadata/update, and PATCH /api/v1/datasets/:dataset_id/documents/metadatas; adds/updates handler tests covering upload validation, batch metadata cases, and LinkToDatasets scenarios.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant UploadInfo as DocumentHandler.UploadInfo
  participant FileService
  participant Fetch as fetchRemoteFileSafely
  participant Storage as ObjectStorage
  participant DocumentService

  Client->>UploadInfo: POST /api/v1/documents/upload (file or url)
  UploadInfo->>FileService: UploadFile(...) or UploadFromURL(userID, url)
  FileService->>Fetch: fetchRemoteFileSafely(url)
  Fetch-->>FileService: bytes, filename
  FileService->>Storage: Save file bytes
  FileService->>DocumentService: Insert/Create file metadata
  FileService-->>UploadInfo: file response
  UploadInfo-->>Client: JSON response

  Client->>UploadInfo: POST/PATCH dataset metadata endpoints
  UploadInfo->>DocumentService: BatchUpdateDocumentMetadata(datasetID, request)
  DocumentService->>DocumentService: Resolve/filter IDs, apply updates/deletes
  DocumentService-->>UploadInfo: Matched/Updated counts
  UploadInfo-->>Client: JSON result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

💞 feature, size:L

Suggested reviewers

  • Hz-186

"I nibbled bytes down safe and small,
Fetched far-off files and kept them all.
Metadata hopped into tidy rows,
Bulk updates danced where the handler goes.
Hooray — uploads and batches, neatly called!"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main changeset—implementing three document upload and metadata bulk-update APIs in Go—matching the PR's primary objective of porting endpoints from Python.
Description check ✅ Passed The PR description follows the template structure, clearly states the problem (closes #15671), specifies the type of change (New Feature), provides detailed implementation notes, and includes a functional parity table demonstrating behavior alignment with Python source.
Linked Issues check ✅ Passed The PR implementation meets all three primary coding objectives from #15671: implements POST /documents/upload with multipart and URL support [#15671], PATCH /datasets/:id/documents/metadatas with bulk metadata updates [#15671], POST /datasets/:id/metadata/update with shared batchMetadataUpdate logic [#15671].
Out of Scope Changes check ✅ Passed All code changes directly support the three endpoint implementations and their functional requirements (file upload service, batch metadata service, handler endpoints, and route registration); no extraneous changes observed outside the scope of #15671.

✏️ 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 and usage tips.

@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

🧹 Nitpick comments (1)
internal/handler/document.go (1)

914-918: 💤 Low value

Silently ignoring MultipartForm() error may hide issues.

The error from c.MultipartForm() is discarded. While this allows non-multipart requests (URL-only) to proceed, it also hides legitimate parsing errors (e.g., malformed multipart boundary, exceeding memory limits). Consider distinguishing between "no multipart form" and "invalid multipart form".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/document.go` around lines 914 - 918, The code currently
discards the error from c.MultipartForm() which hides parsing failures; update
the block around c.MultipartForm() (where files := form.File["file"] is set) to
capture the returned error, then distinguish "not a multipart request" from real
parsing errors: if err == nil use form.File["file"]; if err indicates “not
multipart” (e.g., http.ErrNotMultipart or the framework’s equivalent) continue
treating it as a URL-only request; otherwise return/abort with a 400 and log the
parsing error (or propagate the error) so malformed multipart boundaries or size
issues aren’t silently ignored.
🤖 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 1308-1310: In parseMetadataConditions the code only sets mfc.Value
when cond["value"] is a string, so numeric/boolean JSON values are ignored;
update the logic in parseMetadataConditions to handle non-string primitives by
detecting types (e.g., float64 for JSON numbers, bool) or by converting any
non-nil cond["value"] to a string representation (e.g., fmt.Sprintf("%v",
cond["value"])) before assigning to mfc.Value; ensure you still preserve string
values and avoid panics on nil values when reading cond["value"].
- Around line 1265-1288: The loop increments the updated counter even when
DeleteDocumentMetadata fails, causing inconsistent counts versus
SetDocumentMetadata which uses continue on error; modify the
BatchUpdateDocumentMetadata logic that iterates over ids (and checks req.Updates
/ req.Deletes) so that for each docID you perform SetDocumentMetadata and
DeleteDocumentMetadata but only increment updated when all requested operations
for that doc complete successfully; e.g. call SetDocumentMetadata and if it
fails continue, call DeleteDocumentMetadata and if it fails continue (or track
an error flag and only updated++ when no errors), ensuring both
SetDocumentMetadata and DeleteDocumentMetadata outcomes determine whether
updated is incremented.

In `@internal/service/file.go`:
- Around line 1011-1022: The code uses http.Get(rawURL) and
io.LimitReader(resp.Body, 100<<20) which leaves no client timeout and silently
truncates bodies; replace http.Get with a request executed by an http.Client
with a bounded timeout (or use context.WithTimeout) when calling rawURL (same
call site where http.Get(rawURL) is used), and after reading via
io.LimitReader(resp.Body, 100<<20) verify truncation didn't occur by checking
resp.ContentLength against 100<<20 when available or attempting to read one
extra byte from resp.Body (or using io.ReadAll on a reader wrapped to detect
overflow) and return an explicit error if the body exceeded the 100<<20 limit;
keep defers to close resp.Body and propagate errors using the existing
fmt.Errorf pattern.
- Around line 1025-1028: The filename derivation uses filepath.Base(parsed.Path)
and already avoids query-string extraction, but it doesn't sanitize path-derived
names; update the logic around filename (the variable set from
filepath.Base(parsed.Path)) to clean/normalize the base segment by removing or
replacing filesystem-invalid characters (e.g., <>:"/\\|?*), collapse/control
whitespace, and enforce platform-safe constraints (trim trailing dots/spaces,
handle reserved names like CON/PRN/NUL on Windows); also add collision handling
(e.g., append numeric suffix) and fallback to "download" only after sanitization
fails so Save/Write code receives a safe, unique filename. Ensure these changes
are applied where filename is used downstream so no unsanitized name is
persisted.
- Around line 1005-1008: The URL validation in internal/service/file.go (used by
UploadFromURL) only checks scheme and is vulnerable to SSRF; update
UploadFromURL (or the helper that calls url.Parse) to: 1) parse the hostname and
resolve its A/AAAA records up front, 2) reject any resolved IPs in
private/loopback/link-local ranges and known cloud metadata ranges (e.g.,
169.254.169.254/32, 169.254.0.0/16, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16,
::1/128, fc00::/7, fe80::/10), 3) prevent DNS rebinding by pinning the resolved
IP(s) and using a custom http.Transport DialContext that connects only to those
IPs, 4) disable or strictly validate redirects (set CheckRedirect to disallow
redirecting to different host/IPs or re-run the same IP whitelist on each
redirect target), and 5) fail fast with a clear error from UploadFromURL when
any check fails. Ensure these checks are applied before performing the
http.Get/fetch and reference the functions/methods UploadFromURL and any HTTP
client/Transport/CheckRedirect setup in file.go.

---

Nitpick comments:
In `@internal/handler/document.go`:
- Around line 914-918: The code currently discards the error from
c.MultipartForm() which hides parsing failures; update the block around
c.MultipartForm() (where files := form.File["file"] is set) to capture the
returned error, then distinguish "not a multipart request" from real parsing
errors: if err == nil use form.File["file"]; if err indicates “not multipart”
(e.g., http.ErrNotMultipart or the framework’s equivalent) continue treating it
as a URL-only request; otherwise return/abort with a 400 and log the parsing
error (or propagate the error) so malformed multipart boundaries or size issues
aren’t silently ignored.
🪄 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: 16761187-0092-4a38-ab75-03367547b471

📥 Commits

Reviewing files that changed from the base of the PR and between 96a4166 and 449c8ee.

📒 Files selected for processing (4)
  • internal/handler/document.go
  • internal/router/router.go
  • internal/service/document.go
  • internal/service/file.go

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

@Harry-Hz-Zhang Harry-Hz-Zhang 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.

Hi, @hunnyboy1217

This change still has two parity gaps before it can be merged.

First, the Go metadata batch-update path does not parse metadata_condition in the same shape as Python. Python sends conditions as {name, comparison_operator, value}, but parseMetadataConditions() currently only reads {key|field, op, value}. That means valid Python-style requests will not be filtered correctly.

Second, POST /api/v1/documents/upload?url=... is missing the Python SSRF guard. Python validates the remote URL with assert_url_is_safe(url) before fetching it, while Go currently only checks the scheme and then performs http.Get directly.

Comment thread internal/service/document.go Outdated
}

// parseMetadataConditions converts metadata_condition.conditions to MetaFilterConditions.
func parseMetadataConditions(mc map[string]interface{}) []MetaFilterCondition {

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.

here

// @Param url query string false "Remote URL to fetch"
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/documents/upload [post]
func (h *DocumentHandler) UploadInfo(c *gin.Context) {

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.

here

hunnyboy1217 added a commit to hunnyboy1217/ragflow that referenced this pull request Jun 5, 2026
…nfiniflow#15672)

Applies the final-review feedback from Hz-186 and CodeRabbit, and adapts to the
GetFlattedMetaByKBs → common.MetaData change merged from main (infiniflow#15656).

Hz-186 — Python parity gaps:
  - metadata condition shape: the metadata_condition filter now goes through the
    canonical common.ParseAndConvert + common.MetaFilter (the Go port of Python
    convert_conditions + meta_filter). Conditions are read as
    {name, comparison_operator, value} with the Python operator mapping
    (is→=, not is→≠, >=→≥, <=→≤, !=→≠). This also fixes a compile break: after
    infiniflow#15656, GetFlattedMetaByKBs returns common.MetaData, which the old
    ApplyMetaFilter(map[string]interface{}) call site no longer accepted. The
    bespoke parseMetadataConditions helper is removed.
  - SSRF protection: the ?url= upload now mirrors Python assert_url_is_safe —
    scheme allowlist, host resolved, every resolved IP must be globally routable
    (loopback/private/link-local/multicast/unspecified/CGNAT rejected), and the
    validated IP is pinned in the dialer (re-validated on each redirect hop) to
    defeat DNS rebinding.

CodeRabbit:
  - BatchUpdateDocumentMetadata: the "updated" counter no longer increments when
    a delete fails — a document is counted only when every requested operation
    (updates AND deletes) succeeds.
  - non-string metadata condition values (numbers, booleans) are now honoured via
    common.ParseAndConvert's interface{} value instead of being dropped.
  - UploadFromURL HTTP client: added connect (10s) and overall (30s) timeouts via
    a custom http.Client; the body is read one byte past the 100 MB cap so an
    oversized file is rejected rather than silently truncated by io.LimitReader.
  - UploadFromURL filename: derived filename is sanitized — directory components
    stripped, unsafe/control chars replaced, Windows reserved names rejected,
    length bounded, "download" fallback.
  - UploadInfo: a malformed multipart body now returns HTTP 400 instead of being
    silently ignored; a non-multipart request (http.ErrNotMultipart) stays benign
    so the ?url= path is unaffected.
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 5, 2026
Closes infiniflow#15671. Ports three document/metadata endpoints from Python to Go:
  POST  /api/v1/documents/upload                          (UploadInfo)
  PATCH /api/v1/datasets/:dataset_id/documents/metadatas  (UpdateDocumentMetadatas)
  POST  /api/v1/datasets/:dataset_id/metadata/update      (MetadataBatchUpdate)

Files: internal/service/file.go, internal/service/document.go,
internal/handler/document.go, internal/router/router.go.

Incorporates the earlier review fixes:
  - metadata_condition filtering goes through the canonical common.ParseAndConvert
    + common.MetaFilter (Python convert_conditions/meta_filter parity; works with
    GetFlattedMetaByKBs' common.MetaData return type)
  - BatchUpdateDocumentMetadata counts a document only when every requested
    update AND delete succeeds
  - ?url= upload is SSRF-guarded (scheme allowlist, resolve host, reject
    non-public IPs, pin the validated IP), with client timeout, truncation
    detection, and filename sanitization
  - UploadInfo returns HTTP 400 on a malformed multipart body (benign for
    non-multipart / ?url= requests)

Rebased onto latest main: collapsed the feature + review commits (and the
intermediate merge that pulled in infiniflow#15656) into a single commit, resolving the
import/interface conflicts with upstream's new artifact/preview/download
document APIs.
@hunnyboy1217
hunnyboy1217 force-pushed the feat/go-document-metadata-upload-apis branch from 900eb59 to 1102d62 Compare June 8, 2026 05:40
@hunnyboy1217

Copy link
Copy Markdown
Contributor Author

Hi, @Hz-186 ,
Could you please review this PR?

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

🧹 Nitpick comments (2)
internal/handler/document_test.go (2)

706-731: 💤 Low value

Remove duplicate gin.SetMode call.

Line 713 calls gin.SetMode(gin.TestMode) redundantly; it was already set on line 707.

♻️ Suggested cleanup
 func TestUploadInfo_URLInvalidFormat(t *testing.T) {
 	gin.SetMode(gin.TestMode)
 	h := &DocumentHandler{
 		documentService: &fakeDocumentService{},
 		datasetService:  service.NewDatasetService(),
 		fileService:     service.NewFileService(),
 	}
-	gin.SetMode(gin.TestMode)
 	w := httptest.NewRecorder()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/document_test.go` around lines 706 - 731, The test
TestUploadInfo_URLInvalidFormat contains a duplicate call to
gin.SetMode(gin.TestMode); remove the redundant call (the second invocation) so
only one gin.SetMode(gin.TestMode) remains at the start of the test; keep the
rest of the setup for the DocumentHandler and the UploadInfo(c) invocation
unchanged.

763-788: ⚡ Quick win

Verify HTTP status consistently across all batch metadata tests.

TestBatchMetadataUpdate_Success (line 753) checks w.Code != http.StatusOK, but the error-case tests skip this assertion. Adding the check ensures that unexpected status codes (e.g., 500) are caught early rather than causing cryptic unmarshal failures.

🔍 Suggested consistency fix

For each error-case test, insert the status check before unmarshaling:

 	h.UpdateDocumentMetadatas(c)

+	if w.Code != http.StatusOK {
+		t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+	}
 	var resp map[string]interface{}
 	json.Unmarshal(w.Body.Bytes(), &resp)

Apply the same pattern to TestBatchMetadataUpdate_NoPermission, TestBatchMetadataUpdate_UpdateMissingKey, and TestBatchMetadataUpdate_DeleteMissingKey.

Also applies to: 790-814, 816-840

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/document_test.go` around lines 763 - 788, Add the same HTTP
status assertion used in TestBatchMetadataUpdate_Success to each error-case test
(TestBatchMetadataUpdate_NoPermission, TestBatchMetadataUpdate_UpdateMissingKey,
TestBatchMetadataUpdate_DeleteMissingKey) before calling json.Unmarshal: check
that w.Code == http.StatusOK and fail (t.Fatalf) if not so that unexpected HTTP
statuses are caught early; locate the checks around where
UpdateDocumentMetadatas is invoked on the DocumentHandler and place the new
status assertion immediately after h.UpdateDocumentMetadatas(c) and before
unmarshaling the response body.
🤖 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.

Nitpick comments:
In `@internal/handler/document_test.go`:
- Around line 706-731: The test TestUploadInfo_URLInvalidFormat contains a
duplicate call to gin.SetMode(gin.TestMode); remove the redundant call (the
second invocation) so only one gin.SetMode(gin.TestMode) remains at the start of
the test; keep the rest of the setup for the DocumentHandler and the
UploadInfo(c) invocation unchanged.
- Around line 763-788: Add the same HTTP status assertion used in
TestBatchMetadataUpdate_Success to each error-case test
(TestBatchMetadataUpdate_NoPermission, TestBatchMetadataUpdate_UpdateMissingKey,
TestBatchMetadataUpdate_DeleteMissingKey) before calling json.Unmarshal: check
that w.Code == http.StatusOK and fail (t.Fatalf) if not so that unexpected HTTP
statuses are caught early; locate the checks around where
UpdateDocumentMetadatas is invoked on the DocumentHandler and place the new
status assertion immediately after h.UpdateDocumentMetadatas(c) and before
unmarshaling the response body.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bffb74e2-e90a-447b-85c1-e6548371219b

📥 Commits

Reviewing files that changed from the base of the PR and between 90c5a6e and 0a159aa.

📒 Files selected for processing (6)
  • internal/handler/document_test.go
  • internal/handler/file_handler_test.go
  • internal/router/router.go
  • internal/service/document.go
  • internal/service/file.go
  • internal/service/file_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/router/router.go
  • internal/service/document.go
  • internal/service/file.go

@Harry-Hz-Zhang Harry-Hz-Zhang 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.

@hunnyboy1217

The Go upload API is not compatible with the Python response shape. Timestamp naming differences are minor, but the actual returned fields differ: Python returns upload-info fields like extension, mime_type, and preview_url, while Go returns internal file-record fields like parent_id, tenant_id, location, source_type, and type.

Please return the same non-timestamp fields as Python instead of the generic file response.

Go Tests

/usr/local/go/bin/go test ./internal/handler ./internal/service failed:

  • internal/service: passed
  • internal/handler: failed
    • TestBatchMetadataUpdate_NoPermission: expected code 102, got 0 at internal/handler/document_test.go:786
    • TestLinkToDatasets_MissingBothArgs: panic nil pointer via service.NewFile2DocumentService() at internal/handler/file_handler_test.go:70, which calls NewDocumentService() and dereferences config at internal/service/document.go:67

…d fix test/nil-config bugs

- Add toUploadInfoResponse returning id/name/size/extension/mime_type/created_by/created_at/preview_url
  to match Python FileService.upload_info; UploadFile and UploadFromURL now use it
- Guard server.GetConfig() nil dereference in NewDocumentService so tests that call
  NewFile2DocumentService() no longer panic
- Fix TestBatchMetadataUpdate_NoPermission: override the user context key read by
  GetUser rather than user_id, so Accessible sees the non-owner user ID
@hunnyboy1217

Copy link
Copy Markdown
Contributor Author

Hi, @Hz-186 ,
Could you please review this PR?

@Harry-Hz-Zhang Harry-Hz-Zhang 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.

@hunnyboy1217, I cant run server

In internal/service/document.go, inside the NewDocumentService function, declaring engineType using a blank string literal makes the compiler infer it as a standard string.

This causes compilation errors because both server.GetConfig().DocEngine.Type and the DocumentService.engineType struct field expect the custom type server.

EngineType instead of a raw string. Please declare engineType using the server.

EngineType type directly to fix the type mismatch.

hunnyboy1217 and others added 2 commits June 11, 2026 23:01
…type mismatch (infiniflow#15672)

The nil-guard added for NewDocumentService declared engineType with a blank
string literal, so Go inferred it as a plain string. But both
server.GetConfig().DocEngine.Type and the DocumentService.engineType field are
the custom server.EngineType type, so the assignment and struct literal failed
to compile and blocked the server from building. Declare engineType as
server.EngineType directly.
@Haruko386 Haruko386 added the ci Continue Integration label Jun 16, 2026
@Haruko386
Haruko386 marked this pull request as draft June 16, 2026 08:32
@Haruko386
Haruko386 marked this pull request as ready for review June 16, 2026 08:32
@dosubot dosubot Bot added the 💞 feature Feature request, pull request that fullfill a new feature. label Jun 16, 2026
…to fix CI build (infiniflow#15672)

The merge with main left internal/service/document.go uncompilable:

- Imported ragflow/internal/cache (which does not exist on this branch and is
  not referenced — the body uses engine/redis via redis.Get()), causing the CI
  'package ragflow/internal/cache is not in std' build error.
- Imported github.com/google/uuid without using it.
- Declared a nil-guarded engineType but the struct literal still assigned
  cfg.DocEngine.Type, leaving engineType declared-and-unused and re-introducing
  the nil dereference.

Remove the two unused imports and assign the guarded engineType.
infiniflow#15672)

After the merge with main, utility.FilenameType returns the custom utility.FileType
type, but entity.File.Type is a plain string. UploadFile was already updated to
cast (Type: string(fileType)), but the UploadFromURL path added by this PR still
assigned the raw fileType, breaking the internal/service build:
  internal/service/file.go:1078: cannot use fileType (utility.FileType) as string

Cast it to string to match the sibling UploadFile call site.
@codecov

codecov Bot commented Jun 16, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15672   +/-   ##
=======================================
  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.

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. size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Subtask]: Implement remaining Document/metadata APIs in Go

3 participants