Repository navigation
Refa: migrate document preview/download to RESTful API - #14633
Conversation
📝 WalkthroughWalkthroughThis 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. ChangesDocument API Migration
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
api/apps/restful_apis/document_api.py (1)
1861-1897: ⚡ Quick winAdd 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 winAdd 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
📒 Files selected for processing (11)
api/apps/backward_compat.pyapi/apps/document_app.pyapi/apps/restful_apis/document_api.pydocs/references/http_api_reference.mdtest/testcases/test_web_api/test_common.pytest/testcases/test_web_api/test_document_app/conftest.pytest/testcases/test_web_api/test_document_app/test_document_metadata.pyweb/src/components/document-preview/hooks.tsweb/src/hooks/use-document-request.tsweb/src/pages/document-viewer/index.tsxweb/src/utils/api.ts
💤 Files with no reviewable changes (1)
- api/apps/document_app.py
| @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) |
There was a problem hiding this comment.
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.
| if not dataset_id: | ||
| return {"code": 101, "message": "KB ID is required"} | ||
| params = {} |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| queryKey: [ | ||
| DocumentApiAction.FetchDocumentFilter, | ||
| debouncedSearchString, | ||
| knowledgeId, | ||
| ], | ||
| queryFn: async () => { | ||
| const { data } = await documentFilter(knowledgeId || id); | ||
| if (!datasetId) { | ||
| return; | ||
| } | ||
| const { data } = await documentFilter(datasetId); |
There was a problem hiding this comment.
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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
api/apps/restful_apis/document_api.py (1)
1859-1880: ⚡ Quick winMissing logging for new flows — coding guideline violation.
Neither
get(preview) nordownload_attachmentlogs anything before, during, or on success. The only observability comes from the bare exception swallowed byserver_error_response. Add at least an entry-levellogging.info(orlogging.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_idAs 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
📒 Files selected for processing (1)
api/apps/restful_apis/document_api.py
| data = await thread_pool_exec(settings.STORAGE_IMPL.get, tenant_id, doc_id) | ||
| response = await make_response(data) |
There was a problem hiding this comment.
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:
- The wrong object will be read from storage (or an exception will be thrown and swallowed).
make_response(data)on aNoneresult 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.
|
|
||
| @manager.route("/document/get/<doc_id>", methods=["GET"]) | ||
| @login_required | ||
| async def deprecated_document_get(doc_id): |
| return await document_api.get(doc_id) | ||
|
|
||
|
|
||
| @manager.route("/document/download/<doc_id>", methods=["GET"]) |
There was a problem hiding this comment.
/v1/document/download/{attachment_id}
not /api/v1
What problem does this PR solve?
migrate document preview/download to RESTful API
Type of change