Skip to content

Refa: migrate document preview/download to RESTful API - #14633

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
buua436:b038
May 8, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
buua436:b038

Conversation

@buua436

@buua436 buua436 commented May 7, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

migrate document preview/download to RESTful API

Type of change

  • Refactoring

@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR moves document preview and download to new RESTful endpoints, adds deprecated backward-compatibility forwarders, updates frontend URL usage and API mappings, adjusts tests/fixtures/helpers to load the new module, and updates API documentation.

Changes

Document API Migration

Layer / File(s) Summary
Backend RESTful Routes
api/apps/restful_apis/document_api.py
New GET /documents/<doc_id>/preview and GET /documents/<doc_id>/download endpoints; imports for File2DocumentService, CONTENT_TYPE_MAP, and safe response header utilities.
Legacy document_app handlers
api/apps/document_app.py
Legacy Quart handlers for document retrieval/download present in fallback; functionality migrated to RESTful handlers.
Backward Compatibility
api/apps/backward_compat.py
Deprecated /api/v1/document/get/<doc_id> and /api/v1/document/download/<doc_id> routes added, forwarding to document_api.get and document_api.download_attachment with deprecation logs.
API Documentation
docs/references/http_api_reference.md
Added GET /api/v1/documents/{doc_id}/download documentation and deprecated the old GET /v1/document/download/{attachment_id} entry; examples updated.
Test Utilities
test/testcases/test_web_api/test_common.py
document_metadata_summary changed to datasets-based GET; added document_get and document_download helpers.
Test Fixtures
test/testcases/test_web_api/test_document_app/conftest.py
document_app_module fixture now loads api/apps/restful_apis/document_api.py and stubs api.apps.services.document_api_service before exec.
Test Calls
test/testcases/test_web_api/test_document_app/test_document_metadata.py
download_attachment unit test updated to call with keyword attachment_id.
Frontend API Paths
web/src/utils/api.ts
getDocumentFile and getDocumentFileDownload switched from webAPI /document/... to restAPIv1 /documents/.../download.
Frontend URL Hooks
web/src/hooks/use-document-request.ts
useGetDocumentUrl now consistently returns ${restAPIv1}/documents/${id}/preview; removed auth-based branch.
Frontend Components
web/src/components/document-preview/hooks.ts, web/src/pages/document-viewer/index.tsx
Components updated to use restAPIv1 preview endpoint and adjusted imports.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#14348: Modifies api/apps/restful_apis/document_api.py to add/migrate document-related HTTP routes under /api/v1/documents/....
  • infiniflow/ragflow#14427: Modifies api/apps/backward_compat.py to add/register deprecated forwarder routes.
  • infiniflow/ragflow#14031: Related changes consolidating metadata-summary handling and tests toward RESTful document APIs.

Suggested labels

☯️ refactor, 🐖api, 🌈 python, 🧰 typescript, 🧪 test

Suggested reviewers

  • wangq8
  • yuzhichang
  • yingfeng

Poem

🐰 I hopped from old routes to RESTful tracks,

Deprecation sign in paw, I carried the flasks.
Frontend and tests followed my hop,
Bytes wrapped safe, headers set on top,
A tiny rabbit cheer for endpoints that last.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% 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 summarizes the main change: migrating document preview/download functionality to RESTful API endpoints, which is the primary objective reflected throughout the changeset.
Description check ✅ Passed The description includes the required sections (problem statement and type of change) from the template, though the problem statement is minimal and largely repeats the title without elaboration.
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 and usage tips.

@buua436
buua436 requested a review from wangq8 May 7, 2026 09:24
@buua436 buua436 added the ci Continue Integration label May 7, 2026
@buua436
buua436 marked this pull request as ready for review May 7, 2026 09:24
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 7, 2026
@buua436 buua436 changed the title Refa: Refa: migrate document preview/download to RESTful API May 7, 2026

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

🧹 Nitpick comments (2)
api/apps/restful_apis/document_api.py (1)

1861-1897: ⚡ Quick win

Add flow-level logs for the new preview/download endpoints.

These are new request flows and currently have no success-path logging, which makes tracing adoption and failures harder.

As per coding guidelines, "**/*.py: Add logging for new flows".

🤖 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 `@api/apps/restful_apis/document_api.py` around lines 1861 - 1897, Missing
success-path logs for the new preview/download flows: add informative INFO-level
logging in get (async def get) and download_attachment (async def
download_attachment) after response creation to record key flow details (e.g.,
doc_id, tenant_id where applicable, doc.name or File2DocumentService result,
ext, content_type, and data size or bytes length) and log at error level inside
the except blocks where server_error_response is returned; specifically, in get,
log after make_response/data retrieval and before
apply_safe_file_response_headers using identifiers from
DocumentService.get_by_id and File2DocumentService.get_storage_address, and in
download_attachment log after thread_pool_exec(settings.STORAGE_IMPL.get) using
tenant_id/doc_id and the chosen ext/content_type so successes and payload sizes
are traceable.
test/testcases/test_web_api/test_common.py (1)

405-430: ⚡ Quick win

Add debug logging for the new document metadata/preview/download flows

The new helper flows (document_metadata_summary, document_get, document_download) don’t emit the existing HTTP debug log path, which makes test failures harder to triage.

As per coding guidelines, "**/*.py: Add logging for new flows".

🤖 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 `@test/testcases/test_web_api/test_common.py` around lines 405 - 430, Add the
same HTTP debug logging used elsewhere to the three new helpers so failures are
easier to triage: in document_metadata_summary, document_get, and
document_download log the outgoing request (method, full URL including params,
and headers) immediately before calling requests.get and log the response
(status_code and short body or response.text) after the call using the project's
existing HTTP debug logger (the same logger used by other test helpers) at debug
level.
🤖 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 `@api/apps/restful_apis/document_api.py`:
- Around line 1859-1897: Both preview handler (get) and download_attachment must
enforce document-level authorization before calling storage; fetch the document
via DocumentService.get_by_id (and/or use an existing auth helper) and validate
the current user/tenant has permission for doc_id, returning the appropriate
data/auth error early if not authorized, and only then call
File2DocumentService.get_storage_address or settings.STORAGE_IMPL.get; update
get (the preview route) and download_attachment to perform this check
immediately after obtaining DocumentService.get_by_id (and before
thread_pool_exec/storage reads) and reuse existing helper logic (or tenant_id
from add_tenant_id_to_kwargs) to compare ownership/permissions.

In `@test/testcases/test_web_api/test_common.py`:
- Around line 411-413: The code assumes doc_ids is a list and blindly does
",".join(doc_ids) before calling requests.get (the params dict used for the GET
to f"{HOST_ADDRESS}{DATASETS_URL}/{dataset_id}/metadata/summary"); guard the
type of doc_ids in that block: if doc_ids is a list/tuple/set join with ","; if
it's already a string assign it directly to params["doc_ids"]; otherwise coerce
to a string or raise a clear error so you don't end up splitting a string into
characters when building the request parameters.
- Around line 408-410: The helper currently returns a synthetic error dict when
dataset_id is falsy (return {"code": 101, "message": "KB ID is required"}),
which hides real API behavior; replace that return with raising an exception
(e.g., raise ValueError("KB ID is required")) so tests fail fast and exercise
the actual API path, and update any callers/tests to expect/handle the exception
instead of a fake server response; locate the check using the dataset_id
variable in this helper and swap the return for an exception throw.

In `@web/src/hooks/use-document-request.ts`:
- Around line 218-227: The queryKey for the
DocumentApiAction.FetchDocumentFilter query omits datasetId while the queryFn
calls documentFilter(datasetId), causing stale cache hits when id/datasetId
changes; update the queryKey in use-document-request.ts (the useQuery call that
currently lists DocumentApiAction.FetchDocumentFilter, debouncedSearchString,
knowledgeId) to include datasetId (or the computed knowledgeId || id value)
alongside debouncedSearchString and knowledgeId so the cache is partitioned by
dataset and documentFilter(datasetId) always returns the correct
dataset-specific result.

---

Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1861-1897: Missing success-path logs for the new preview/download
flows: add informative INFO-level logging in get (async def get) and
download_attachment (async def download_attachment) after response creation to
record key flow details (e.g., doc_id, tenant_id where applicable, doc.name or
File2DocumentService result, ext, content_type, and data size or bytes length)
and log at error level inside the except blocks where server_error_response is
returned; specifically, in get, log after make_response/data retrieval and
before apply_safe_file_response_headers using identifiers from
DocumentService.get_by_id and File2DocumentService.get_storage_address, and in
download_attachment log after thread_pool_exec(settings.STORAGE_IMPL.get) using
tenant_id/doc_id and the chosen ext/content_type so successes and payload sizes
are traceable.

In `@test/testcases/test_web_api/test_common.py`:
- Around line 405-430: Add the same HTTP debug logging used elsewhere to the
three new helpers so failures are easier to triage: in
document_metadata_summary, document_get, and document_download log the outgoing
request (method, full URL including params, and headers) immediately before
calling requests.get and log the response (status_code and short body or
response.text) after the call using the project's existing HTTP debug logger
(the same logger used by other test helpers) at debug level.
🪄 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: 0f515faf-e635-474d-a9e4-5f9fe20d8e96

📥 Commits

Reviewing files that changed from the base of the PR and between 94324af and 78d72db.

📒 Files selected for processing (11)
  • api/apps/backward_compat.py
  • api/apps/document_app.py
  • api/apps/restful_apis/document_api.py
  • docs/references/http_api_reference.md
  • test/testcases/test_web_api/test_common.py
  • test/testcases/test_web_api/test_document_app/conftest.py
  • test/testcases/test_web_api/test_document_app/test_document_metadata.py
  • web/src/components/document-preview/hooks.ts
  • web/src/hooks/use-document-request.ts
  • web/src/pages/document-viewer/index.tsx
  • web/src/utils/api.ts
💤 Files with no reviewable changes (1)
  • api/apps/document_app.py

Comment on lines +1859 to +1897
@manager.route("/documents/<doc_id>/preview", methods=["GET"]) # noqa: F821
@login_required
async def get(doc_id):
try:
e, doc = DocumentService.get_by_id(doc_id)
if not e:
return get_data_error_result(message="Document not found!")

b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
data = await thread_pool_exec(settings.STORAGE_IMPL.get, b, n)
response = await make_response(data)

ext = re.search(r"\.([^.]+)$", doc.name.lower())
ext = ext.group(1) if ext else None
content_type = None
if ext:
fallback_prefix = "image" if doc.type == FileType.VISUAL.value else "application"
content_type = CONTENT_TYPE_MAP.get(ext, f"{fallback_prefix}/{ext}")
apply_safe_file_response_headers(response, content_type, ext)
return response
except Exception as e:
return server_error_response(e)


@manager.route("/documents/<doc_id>/download", methods=["GET"]) # noqa: F821
@login_required
@add_tenant_id_to_kwargs
async def download_attachment(tenant_id, doc_id):
try:
ext = request.args.get("ext", "markdown")
data = await thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, doc_id)
response = await make_response(data)
content_type = CONTENT_TYPE_MAP.get(ext, f"application/{ext}")
apply_safe_file_response_headers(response, content_type, ext)

return response

except Exception as e:
return server_error_response(e)

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Enforce document-level authorization before serving preview/download.

Both new handlers should verify the caller can access doc_id (and return a data/auth error early) before reading storage; currently they can be hit with arbitrary IDs and skip ownership validation in the endpoint itself.

🔒 Suggested hardening
 `@manager.route`("/documents/<doc_id>/preview", methods=["GET"])  # noqa: F821
 `@login_required`
+@add_tenant_id_to_kwargs
-async def get(doc_id):
+async def get(doc_id, tenant_id):
     try:
         e, doc = DocumentService.get_by_id(doc_id)
         if not e:
             return get_data_error_result(message="Document not found!")
+        if not DocumentService.accessible(doc_id, tenant_id):
+            return get_error_data_result(message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
@@
 `@manager.route`("/documents/<doc_id>/download", methods=["GET"])  # noqa: F821
 `@login_required`
 `@add_tenant_id_to_kwargs`
 async def download_attachment(tenant_id, doc_id):
     try:
+        if not DocumentService.accessible(doc_id, tenant_id):
+            return get_error_data_result(message="No authorization.", code=RetCode.AUTHENTICATION_ERROR)
         ext = request.args.get("ext", "markdown")
🤖 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 `@api/apps/restful_apis/document_api.py` around lines 1859 - 1897, Both preview
handler (get) and download_attachment must enforce document-level authorization
before calling storage; fetch the document via DocumentService.get_by_id (and/or
use an existing auth helper) and validate the current user/tenant has permission
for doc_id, returning the appropriate data/auth error early if not authorized,
and only then call File2DocumentService.get_storage_address or
settings.STORAGE_IMPL.get; update get (the preview route) and
download_attachment to perform this check immediately after obtaining
DocumentService.get_by_id (and before thread_pool_exec/storage reads) and reuse
existing helper logic (or tenant_id from add_tenant_id_to_kwargs) to compare
ownership/permissions.

Comment on lines +408 to +410
if not dataset_id:
return {"code": 101, "message": "KB ID is required"}
params = {}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid synthetic API responses in test HTTP helpers

Line 409 returns a hardcoded error payload instead of exercising the API path; this can mask regressions in endpoint validation and response shape. Fail fast locally (e.g., ValueError) so tests don’t treat a client-side stub as a server response.

Proposed fix
 def document_metadata_summary(auth, payload=None, *, headers=HEADERS, data=None):
     dataset_id = (payload or {}).get("kb_id")
     doc_ids = (payload or {}).get("doc_ids")
     if not dataset_id:
-        return {"code": 101, "message": "KB ID is required"}
+        raise ValueError("kb_id is required")
🤖 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 `@test/testcases/test_web_api/test_common.py` around lines 408 - 410, The
helper currently returns a synthetic error dict when dataset_id is falsy (return
{"code": 101, "message": "KB ID is required"}), which hides real API behavior;
replace that return with raising an exception (e.g., raise ValueError("KB ID is
required")) so tests fail fast and exercise the actual API path, and update any
callers/tests to expect/handle the exception instead of a fake server response;
locate the check using the dataset_id variable in this helper and swap the
return for an exception throw.

Comment on lines +411 to +413
if doc_ids:
params["doc_ids"] = ",".join(doc_ids)
res = requests.get(url=f"{HOST_ADDRESS}{DATASETS_URL}/{dataset_id}/metadata/summary", headers=headers, auth=auth, params=params, data=data)

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Guard doc_ids type before joining

Line 412 assumes doc_ids is a list-like. If a string is passed, the query becomes character-split (a,b,c) and sends an incorrect request.

Proposed fix
     params = {}
     if doc_ids:
-        params["doc_ids"] = ",".join(doc_ids)
+        if isinstance(doc_ids, (list, tuple, set)):
+            params["doc_ids"] = ",".join(doc_ids)
+        else:
+            params["doc_ids"] = str(doc_ids)
🤖 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 `@test/testcases/test_web_api/test_common.py` around lines 411 - 413, The code
assumes doc_ids is a list and blindly does ",".join(doc_ids) before calling
requests.get (the params dict used for the GET to
f"{HOST_ADDRESS}{DATASETS_URL}/{dataset_id}/metadata/summary"); guard the type
of doc_ids in that block: if doc_ids is a list/tuple/set join with ","; if it's
already a string assign it directly to params["doc_ids"]; otherwise coerce to a
string or raise a clear error so you don't end up splitting a string into
characters when building the request parameters.

Comment on lines 218 to +227
queryKey: [
DocumentApiAction.FetchDocumentFilter,
debouncedSearchString,
knowledgeId,
],
queryFn: async () => {
const { data } = await documentFilter(knowledgeId || id);
if (!datasetId) {
return;
}
const { data } = await documentFilter(datasetId);

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Include datasetId in the React Query key to avoid stale filter cache

Line 218–223 keys by knowledgeId, but Line 227 fetches by datasetId (knowledgeId || id). When id changes, the cache key can stay the same and return filters from the wrong dataset.

Suggested fix
   const { data } = useQuery({
     queryKey: [
       DocumentApiAction.FetchDocumentFilter,
       debouncedSearchString,
-      knowledgeId,
+      datasetId,
     ],
📝 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
queryKey: [
DocumentApiAction.FetchDocumentFilter,
debouncedSearchString,
knowledgeId,
],
queryFn: async () => {
const { data } = await documentFilter(knowledgeId || id);
if (!datasetId) {
return;
}
const { data } = await documentFilter(datasetId);
queryKey: [
DocumentApiAction.FetchDocumentFilter,
debouncedSearchString,
datasetId,
],
queryFn: async () => {
if (!datasetId) {
return;
}
const { data } = await documentFilter(datasetId);
🤖 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 `@web/src/hooks/use-document-request.ts` around lines 218 - 227, The queryKey
for the DocumentApiAction.FetchDocumentFilter query omits datasetId while the
queryFn calls documentFilter(datasetId), causing stale cache hits when
id/datasetId changes; update the queryKey in use-document-request.ts (the
useQuery call that currently lists DocumentApiAction.FetchDocumentFilter,
debouncedSearchString, knowledgeId) to include datasetId (or the computed
knowledgeId || id value) alongside debouncedSearchString and knowledgeId so the
cache is partitioned by dataset and documentFilter(datasetId) always returns the
correct dataset-specific result.

@codecov

codecov Bot commented May 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (59c3510) to head (2840624).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14633      +/-   ##
==========================================
- Coverage   95.59%   94.16%   -1.43%     
==========================================
  Files          10       10              
  Lines         703      703              
  Branches      112      112              
==========================================
- Hits          672      662      -10     
- Misses         21       25       +4     
- Partials       10       16       +6     

☔ View full report in Codecov by Sentry.
📢 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.

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

🧹 Nitpick comments (1)
api/apps/restful_apis/document_api.py (1)

1859-1880: ⚡ Quick win

Missing logging for new flows — coding guideline violation.

Neither get (preview) nor download_attachment logs anything before, during, or on success. The only observability comes from the bare exception swallowed by server_error_response. Add at least an entry-level logging.info (or logging.debug) for each new code path.

📋 Suggested additions
 `@manager.route`("/documents/<doc_id>/preview", methods=["GET"])  # noqa: F821
 `@login_required`
 async def get(doc_id):
     try:
+        logging.info("document preview requested doc_id=%s", doc_id)
         e, doc = DocumentService.get_by_id(doc_id)
 `@manager.route`("/documents/<doc_id>/download", methods=["GET"])  # noqa: F821
 `@login_required`
 `@add_tenant_id_to_kwargs`
 async def download_attachment(tenant_id=None, doc_id=None, attachment_id=None):
     try:
+        logging.info("document download requested tenant_id=%s doc_id=%s", tenant_id, doc_id)
         doc_id = doc_id or attachment_id

As per coding guidelines: "Add logging for new flows".

Also applies to: 1883-1900

🤖 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 `@api/apps/restful_apis/document_api.py` around lines 1859 - 1880, The get
(preview) handler and the download_attachment flow lack any logging; add
entry-level logging calls to trace the flow: log an info/debug when the handler
starts (include doc_id), log after DocumentService.get_by_id with the result
(found/missing), log the storage lookup via
File2DocumentService.get_storage_address (bucket/name), and log a success just
before returning the response (include content_type and ext); also log the
exception with context before calling server_error_response. Use the same
pattern for download_attachment (mirror the same log points) and reference the
functions DocumentService.get_by_id, File2DocumentService.get_storage_address,
apply_safe_file_response_headers, and the route handlers get and
download_attachment when inserting these logs.
🤖 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 `@api/apps/restful_apis/document_api.py`:
- Around line 1892-1893: download_attachment is using
settings.STORAGE_IMPL.get(tenant_id, doc_id) which misinterprets tenant_id as
bucket and doc_id as key; fix by first loading the document via
DocumentService.get_by_id(doc_id) to validate existence, then compute the
storage address with File2DocumentService.get_storage_address(doc_id=doc_id)
(returns bucket, key) and call settings.STORAGE_IMPL.get(bucket, key) inside
thread_pool_exec; if the get returns None or document not found, return an
appropriate error/404 instead of passing None into make_response.

---

Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 1859-1880: The get (preview) handler and the download_attachment
flow lack any logging; add entry-level logging calls to trace the flow: log an
info/debug when the handler starts (include doc_id), log after
DocumentService.get_by_id with the result (found/missing), log the storage
lookup via File2DocumentService.get_storage_address (bucket/name), and log a
success just before returning the response (include content_type and ext); also
log the exception with context before calling server_error_response. Use the
same pattern for download_attachment (mirror the same log points) and reference
the functions DocumentService.get_by_id,
File2DocumentService.get_storage_address, apply_safe_file_response_headers, and
the route handlers get and download_attachment when inserting these logs.
🪄 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: f699336b-b0bc-4080-a532-6959432100a3

📥 Commits

Reviewing files that changed from the base of the PR and between 93a035d and 2840624.

📒 Files selected for processing (1)
  • api/apps/restful_apis/document_api.py

Comment on lines +1892 to +1893
data = await thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, doc_id)
response = await make_response(data)

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Wrong storage address — download_attachment will always read from the wrong location.

settings.STORAGE_IMPL.get(tenant_id, doc_id) treats tenant_id as the bucket and doc_id as the object key. Documents are not stored that way: every other write/read in this file uses the dataset/KB id as bucket and the document's location field as key (e.g., line 495: put(dataset_id, location, blob)). The preview handler on line 1867–1868 shows the correct pattern:

b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
data = await thread_pool_exec(settings.STORAGE_IMPL.get, b, n)

As a result:

  1. The wrong object will be read from storage (or an exception will be thrown and swallowed).
  2. make_response(data) on a None result produces an empty/broken response with no error message surfaced to the caller.

Additionally, unlike the preview handler, download_attachment never calls DocumentService.get_by_id(doc_id) first, so an invalid doc_id returns an opaque 500 instead of a useful "Document not found" response.

🐛 Proposed fix
 async def download_attachment(tenant_id=None, doc_id=None, attachment_id=None):
     try:
         doc_id = doc_id or attachment_id
+        e, doc = DocumentService.get_by_id(doc_id)
+        if not e:
+            return get_data_error_result(message="Document not found!")
         ext = request.args.get("ext", "markdown")
-        data = await thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, doc_id)
+        b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
+        data = await thread_pool_exec(settings.STORAGE_IMPL.get, b, n)
+        if not data:
+            return get_data_error_result(message="Document content not found!")
         response = await make_response(data)
🤖 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 `@api/apps/restful_apis/document_api.py` around lines 1892 - 1893,
download_attachment is using settings.STORAGE_IMPL.get(tenant_id, doc_id) which
misinterprets tenant_id as bucket and doc_id as key; fix by first loading the
document via DocumentService.get_by_id(doc_id) to validate existence, then
compute the storage address with
File2DocumentService.get_storage_address(doc_id=doc_id) (returns bucket, key)
and call settings.STORAGE_IMPL.get(bucket, key) inside thread_pool_exec; if the
get returns None or document not found, return an appropriate error/404 instead
of passing None into make_response.

@wangq8
wangq8 merged commit f703169 into infiniflow:main May 8, 2026
1 check passed

@manager.route("/document/get/<doc_id>", methods=["GET"])
@login_required
async def deprecated_document_get(doc_id):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

no need

return await document_api.get(doc_id)


@manager.route("/document/download/<doc_id>", methods=["GET"])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

/v1/document/download/{attachment_id}
not /api/v1

pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
)

### What problem does this PR solve?

migrate document preview/download to RESTful API

### Type of change
- [x] Refactoring
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
)

### What problem does this PR solve?

migrate document preview/download to RESTful API

### Type of change
- [x] Refactoring
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants