feat: optimize item content retrieval to reduce redundant database queries
Co-authored-by: aider (openai/andrew/openrouter/qwen/qwen3-coder) <aider@aider.chat>
This commit is contained in:
@@ -168,6 +168,7 @@ pub async fn handle_get_item_latest_content(
|
|||||||
|
|
||||||
let item_service = AsyncItemService::new(state.data_dir.clone(), state.db.clone());
|
let item_service = AsyncItemService::new(state.data_dir.clone(), state.db.clone());
|
||||||
|
|
||||||
|
// First get the item metadata to check if it's binary and get MIME type
|
||||||
let item_with_meta = item_service
|
let item_with_meta = item_service
|
||||||
.find_item(vec![], tags, HashMap::new())
|
.find_item(vec![], tags, HashMap::new())
|
||||||
.await;
|
.await;
|
||||||
@@ -175,8 +176,37 @@ pub async fn handle_get_item_latest_content(
|
|||||||
match item_with_meta {
|
match item_with_meta {
|
||||||
Ok(item) => {
|
Ok(item) => {
|
||||||
let item_id = item.item.id.unwrap();
|
let item_id = item.item.id.unwrap();
|
||||||
match item_service.stream_item_content_by_id(item_id, params.allow_binary, params.offset, params.length).await {
|
let metadata = item.meta_as_map();
|
||||||
Ok((stream, mime_type)) => {
|
let mime_type = metadata
|
||||||
|
.get("mime_type")
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.unwrap_or_else(|| "application/octet-stream".to_string());
|
||||||
|
|
||||||
|
// Check if content is binary when allow_binary is false
|
||||||
|
if !params.allow_binary {
|
||||||
|
let is_content_binary = if let Some(binary_val) = metadata.get("binary") {
|
||||||
|
binary_val == "true"
|
||||||
|
} else {
|
||||||
|
// For the binary check, we need to read a sample of the content
|
||||||
|
match item_service.get_item_content(item_id).await {
|
||||||
|
Ok(item_with_content) => {
|
||||||
|
crate::common::is_binary::is_binary(&item_with_content.content)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!("Failed to get content for binary check for item {}: {}", item_id, e);
|
||||||
|
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if is_content_binary {
|
||||||
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now stream the content with the specified offset and length
|
||||||
|
match item_service.stream_item_content_by_id(item_id, true, params.offset, params.length).await {
|
||||||
|
Ok((stream, _)) => {
|
||||||
let body = axum::body::Body::from_stream(stream);
|
let body = axum::body::Body::from_stream(stream);
|
||||||
let response = Response::builder()
|
let response = Response::builder()
|
||||||
.header(header::CONTENT_TYPE, mime_type)
|
.header(header::CONTENT_TYPE, mime_type)
|
||||||
|
|||||||
Reference in New Issue
Block a user