✨ feat(backend): 完善上传取消与历史文件生命周期状态
This commit is contained in:
1 parent
dd905c5c90
commit
dfb392545a
7 files changed
+203
-25
No files matched your search
+72
-18
@@ -1,5 +1,6 @@
|
||||
import datetime
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
import os
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
@@ -658,6 +659,31 @@ async def upload_chunk(
|
||||
return APIResponse(detail={"chunk_hash": chunk_hash})
|
||||
|
||||
|
||||
@chunk_api.post("/upload/raw/{upload_id}/{chunk_index}", dependencies=[Depends(share_required_login)])
|
||||
async def upload_raw_chunk(upload_id: str, chunk_index: int, request: Request):
|
||||
info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if info is None:
|
||||
raise HTTPException(404, "上传会话不存在")
|
||||
if not 0 <= chunk_index < info.total_chunks:
|
||||
raise HTTPException(400, "无效的分片索引")
|
||||
maximum = min(info.chunk_size, info.file_size - chunk_index * info.chunk_size, 100 * 1024 * 1024)
|
||||
content_length = request.headers.get("content-length")
|
||||
if content_length:
|
||||
try:
|
||||
if int(content_length) > maximum: raise HTTPException(413, "分片超过声明大小")
|
||||
except ValueError: raise HTTPException(400, "无效的请求大小")
|
||||
buffer = BytesIO()
|
||||
try:
|
||||
async for block in request.stream():
|
||||
if buffer.tell() + len(block) > maximum:
|
||||
raise HTTPException(413, "分片超过声明大小")
|
||||
buffer.write(block)
|
||||
buffer.seek(0)
|
||||
return await upload_chunk(upload_id, chunk_index, UploadFile(file=buffer, filename=info.file_name))
|
||||
finally:
|
||||
buffer.close()
|
||||
|
||||
|
||||
@chunk_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||
async def cancel_upload(upload_id: str):
|
||||
if is_cancelling(upload_id):
|
||||
@@ -673,9 +699,16 @@ async def cancel_upload(upload_id: str):
|
||||
@serialize_upload
|
||||
async def _cancel_upload(upload_id):
|
||||
"""取消上传并清理临时文件"""
|
||||
published = await FileCodes.filter(upload_id=upload_id).first()
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if published:
|
||||
if chunk_info and chunk_info.save_path:
|
||||
await storages[settings.file_storage]().clean_chunks(upload_id, chunk_info.save_path)
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
return APIResponse(detail={"completed":True, "code":published.code, "name":published.prefix+published.suffix})
|
||||
if not chunk_info:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
|
||||
return APIResponse(detail={"cancelled":True, "message":"上传会话已结束"})
|
||||
|
||||
save_path = chunk_info.save_path
|
||||
|
||||
@@ -693,7 +726,7 @@ async def _cancel_upload(upload_id):
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
|
||||
return APIResponse(detail={"message": "上传已取消"})
|
||||
return APIResponse(detail={"cancelled":True,"message": "上传已取消"})
|
||||
|
||||
|
||||
@chunk_api.get(
|
||||
@@ -866,6 +899,8 @@ async def _get_valid_session(
|
||||
session = await PresignUploadSession.filter(upload_id=upload_id).first()
|
||||
if not session:
|
||||
raise HTTPException(404, "上传会话不存在")
|
||||
if session.mode == "cancelled":
|
||||
raise HTTPException(409, "上传已取消,等待后台清理")
|
||||
if await session.is_expired():
|
||||
await session.delete()
|
||||
await release_storage(f"presign:{upload_id}")
|
||||
@@ -936,6 +971,7 @@ async def presign_upload_init(
|
||||
@presign_api.put(
|
||||
"/upload/proxy/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
@serialize_upload
|
||||
async def presign_upload_proxy(
|
||||
upload_id: str, file: UploadFile = File(...), ip: str = Depends(ip_limit["upload"])
|
||||
):
|
||||
@@ -958,6 +994,8 @@ async def presign_upload_proxy(
|
||||
except Exception as e:
|
||||
raise HTTPException(500, f"文件保存失败: {str(e)}")
|
||||
|
||||
if is_cancelling(upload_id):
|
||||
raise HTTPException(409, "上传正在取消")
|
||||
try:
|
||||
code = await FileUploadService.create_file_record(
|
||||
session.file_name,
|
||||
@@ -966,6 +1004,7 @@ async def presign_upload_proxy(
|
||||
session.expire_value,
|
||||
session.expire_style,
|
||||
ip=ip,
|
||||
upload_id=upload_id,
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
@@ -989,6 +1028,7 @@ async def presign_upload_proxy(
|
||||
@presign_api.post(
|
||||
"/upload/confirm/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
@serialize_upload
|
||||
async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upload"])):
|
||||
"""直传确认,客户端完成S3直传后调用获取分享码"""
|
||||
session = await _get_valid_session(upload_id, expected_mode="direct")
|
||||
@@ -1017,6 +1057,8 @@ async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upl
|
||||
if not await storage.file_exists(session.save_path):
|
||||
raise HTTPException(404, "文件未上传或上传失败")
|
||||
|
||||
if is_cancelling(upload_id):
|
||||
raise HTTPException(409, "上传正在取消")
|
||||
try:
|
||||
code = await FileUploadService.create_file_record(
|
||||
session.file_name,
|
||||
@@ -1025,6 +1067,7 @@ async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upl
|
||||
session.expire_value,
|
||||
session.expire_style,
|
||||
ip=ip,
|
||||
upload_id=upload_id,
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
@@ -1069,23 +1112,34 @@ async def presign_upload_status(upload_id: str):
|
||||
|
||||
@presign_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||
async def presign_upload_cancel(upload_id: str):
|
||||
"""取消上传会话"""
|
||||
if is_cancelling(upload_id):
|
||||
raise HTTPException(409, "上传正在取消,请稍后重试")
|
||||
begin_cancel(upload_id)
|
||||
try:
|
||||
return await _presign_upload_cancel(upload_id)
|
||||
finally:
|
||||
end_cancel(upload_id)
|
||||
|
||||
|
||||
@serialize_upload
|
||||
async def _presign_upload_cancel(upload_id):
|
||||
session = await PresignUploadSession.filter(upload_id=upload_id).first()
|
||||
published = await FileCodes.filter(upload_id=upload_id).first()
|
||||
if published:
|
||||
if session: await session.delete()
|
||||
await release_storage(f"presign:{upload_id}")
|
||||
return APIResponse(detail={"completed":True,"code":published.code,"name":published.prefix+published.suffix})
|
||||
if not session:
|
||||
raise HTTPException(404, "上传会话不存在")
|
||||
|
||||
if session.mode == "direct":
|
||||
storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
try:
|
||||
if await storage.file_exists(session.save_path):
|
||||
temp_file_code = FileCodes(
|
||||
file_path=os.path.dirname(session.save_path),
|
||||
uuid_file_name=os.path.basename(session.save_path),
|
||||
)
|
||||
await storage.delete_file(temp_file_code)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return APIResponse(detail={"cancelled":True})
|
||||
storage = storages[settings.file_storage]()
|
||||
if session.mode in {"direct", "cancelled"}:
|
||||
# Browser abort cannot revoke a pre-signed PUT already committing remotely.
|
||||
# Keep a durable tombstone and quota until the signed URL expires.
|
||||
session.mode = "cancelled"
|
||||
await session.save(update_fields=["mode"])
|
||||
return APIResponse(detail={"cancelled":True,"cleanup_pending":True,"message":"传输已中断,临时文件将在上传授权到期后自动清理"})
|
||||
if await storage.file_exists(session.save_path):
|
||||
await storage.delete_file(FileCodes(file_path=os.path.dirname(session.save_path),uuid_file_name=os.path.basename(session.save_path)))
|
||||
await session.delete()
|
||||
await release_storage(f"presign:{upload_id}")
|
||||
return APIResponse(detail={"message": "上传会话已取消"})
|
||||
return APIResponse(detail={"cancelled":True,"message":"上传已取消"})
|
||||
Reference in new issue
Block a user