✨ feat(backend): 完善上传取消与历史文件生命周期状态
This commit is contained in:
1 parent
dd905c5c90
commit
dfb392545a
7 files changed
+203
-25
No files matched your search
@@ -1 +1 @@
|
||||
a962f7aec7c222b1545ecb3774e95d534b1219e9
|
||||
e7918e9317ee56d0460e5d93c113594d054da0f9
|
||||
+18
@@ -110,3 +110,21 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配
|
||||
|
||||
部署按新前端+后端同镜像进行。回滚旧镜像前应完成或取消新模式会话,旧代码
|
||||
不认识偏移暂存对象;不得在活动新会话存在时直接恢复旧数据库。
|
||||
|
||||
## 测试版:中断上传、100MB 与历史状态
|
||||
|
||||
后续修复只推 `test/custom-admin-ui` 并部署测试容器;用户验收后才能更新正式分支和生产。
|
||||
发送页新增中断上传:终止客户端传输/轮询,清理远端临时会话并释放配额;请求晚于
|
||||
文件发布时返回原取件码而不误删已发布文件。清理失败保留会话供重试。S3 直传取消
|
||||
保留取消记录至签名到期,后台清理可能迟到的 PUT,期间禁止确认发布。
|
||||
|
||||
分片最大为 100 MiB (`104857600` 字节),实际最后一片可小于此值;新增原始请求体
|
||||
`/chunk/upload/raw/{upload_id}/{chunk_index}`,兼容旧 multipart 端点。测试站反代上限
|
||||
128m;CloudDrive `/dav/` 取消请求大小上限并关闭请求缓冲,因为流式合并的 PUT
|
||||
是完整文件大小。生产 FileCodeBox 配置保持不变。测试站的 Cloudflare 边缘限制
|
||||
通过实际 100 MiB 请求验证,Nginx 调高不代表 CDN 限制自动改变。
|
||||
|
||||
历史文件状态以数据库当前回收站字段为准,不再把审计保留记录计为“现存”。可恢复
|
||||
记录使用回收站相同原因标签;已清理显示“已清理”;有恢复事件的现存文件显示
|
||||
“现存,已从回收站恢复”;从未回收的文件显示“现存”。恢复后再次回收以当前原因
|
||||
为准,旧永久删除记录保留“已删除”。恢复事件查询独立于分析日期范围。
|
||||
+23
-5
@@ -248,6 +248,7 @@ async def analytics(start: str = "", end: str = ""):
|
||||
|
||||
files = await FileCodes.all()
|
||||
file_map = {item.code: item for item in files}
|
||||
restored_ids = set(await TransferStats.filter(action="restore",file_code_id__isnull=False).values_list("file_code_id",flat=True))
|
||||
|
||||
day_map = {}
|
||||
cursor = start_day
|
||||
@@ -371,6 +372,15 @@ async def analytics(start: str = "", end: str = ""):
|
||||
uploaded_at = file_item.created_at if file_item else data.get("uploaded_at")
|
||||
expired_at = file_item.expired_at if file_item else data.get("expired_at")
|
||||
size = int(file_item.size or 0) if file_item else data.get("size") or 0
|
||||
trashed = bool(file_item and file_item.is_trashed)
|
||||
purged = bool(file_item and file_item.trash_purged_at is not None)
|
||||
expired = current_file_expired(file_item)
|
||||
current = bool(file_item) and not trashed and not purged
|
||||
state = (
|
||||
"purged" if purged else "trashed" if trashed else
|
||||
"expired" if current and expired else "active" if current else
|
||||
"deleted" if data.get("deleted") else "history"
|
||||
)
|
||||
return {
|
||||
"code": code,
|
||||
"name": current_name or data.get("name") or code,
|
||||
@@ -379,13 +389,21 @@ async def analytics(start: str = "", end: str = ""):
|
||||
"download_traffic": str(data.get("downloadTraffic") or 0),
|
||||
"upload_count": data.get("uploads") or 0,
|
||||
"upload_traffic": str(data.get("uploadTraffic") or 0),
|
||||
"current": bool(file_item),
|
||||
"expired": current_file_expired(file_item),
|
||||
"deleted": bool(data.get("deleted")) and not bool(file_item),
|
||||
"current": current,
|
||||
"expired": expired,
|
||||
"deleted": purged or (bool(data.get("deleted")) and not bool(file_item)),
|
||||
"status": state,
|
||||
"is_trashed": trashed,
|
||||
"trash_reason": file_item.trash_reason if file_item else None,
|
||||
"was_restored": bool(file_item and file_item.id in restored_ids),
|
||||
"is_purged": purged,
|
||||
"can_download": current and not expired,
|
||||
"trashed_at": iso(file_item.trashed_at) if file_item else "",
|
||||
"purged_at": iso(file_item.trash_purged_at) if file_item else "",
|
||||
"created_at": iso(uploaded_at),
|
||||
"uploaded_at": iso(uploaded_at),
|
||||
"expired_at": iso(expired_at),
|
||||
"deleted_at": iso(data.get("deleted_at")),
|
||||
"deleted_at": iso(file_item.trash_purged_at or file_item.trashed_at) if trashed or purged else iso(data.get("deleted_at")),
|
||||
}
|
||||
|
||||
def sort_time(value) -> float:
|
||||
@@ -422,7 +440,7 @@ async def analytics(start: str = "", end: str = ""):
|
||||
sum(row["downloadTraffic"] for row in daily_rows)
|
||||
),
|
||||
"historicalFiles": len(file_stats),
|
||||
"currentFiles": len(files),
|
||||
"currentFiles": sum(not item.is_trashed and item.trash_purged_at is None for item in files),
|
||||
"totalUploads": sum(row["uploads"] for row in daily_rows),
|
||||
"uploadTraffic": str(
|
||||
sum(row["uploadTraffic"] for row in daily_rows)
|
||||
|
||||
+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":"上传已取消"})
|
||||
+2
-1
@@ -113,7 +113,7 @@ async def clean_expired_presign_sessions():
|
||||
expires_at__lt=now
|
||||
).all()
|
||||
for session in expired_sessions:
|
||||
if session.mode == "direct":
|
||||
if session.mode in {"direct", "cancelled"}:
|
||||
try:
|
||||
if await storage.file_exists(session.save_path):
|
||||
await storage.delete_file(
|
||||
@@ -127,6 +127,7 @@ async def clean_expired_presign_sessions():
|
||||
"清理过期直传文件失败 "
|
||||
f"upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
continue
|
||||
await StorageReservation.filter(
|
||||
token=f"presign:{session.upload_id}"
|
||||
).delete()
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import datetime
|
||||
import unittest
|
||||
import httpx
|
||||
from fastapi import FastAPI
|
||||
from apps.admin.views import admin_api
|
||||
from apps.admin.dependencies import admin_required
|
||||
from apps.admin.services import FileService
|
||||
from apps.base.models import FileCodes,TransferStats
|
||||
from core.utils import get_now
|
||||
from tests.helpers import init_memory_db,close_db
|
||||
|
||||
class HistoryStatusTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
await init_memory_db()
|
||||
app=FastAPI();app.include_router(admin_api)
|
||||
app.dependency_overrides[admin_required]=lambda:None
|
||||
self.client=httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url='http://test')
|
||||
self.service=FileService()
|
||||
self.item=await FileCodes.create(code='HISTORY1',prefix='test',suffix='.txt',text='history',expired_count=-1)
|
||||
async def asyncTearDown(self):
|
||||
await self.client.aclose();await close_db()
|
||||
async def row(self,**params):
|
||||
response=await self.client.get('/admin/analytics',params=params);self.assertEqual(response.status_code,200,response.text)
|
||||
data=response.json()['detail'];return next(x for x in data['historyFiles'] if x['code']=='HISTORY1'),data['totals']
|
||||
async def test_live_trash_restore_purge_state_and_counts(self):
|
||||
row,totals=await self.row();self.assertEqual(row['status'],'active');self.assertTrue(row['can_download']);self.assertEqual(totals['currentFiles'],1)
|
||||
await self.service.move_to_trash(self.item,reason='manual')
|
||||
row,totals=await self.row();self.assertEqual(row['status'],'trashed');self.assertFalse(row['current']);self.assertFalse(row['can_download']);self.assertIsNotNone(row['trashed_at']);self.assertEqual(totals['currentFiles'],0)
|
||||
self.item=await self.service.restore_from_trash(self.item.id)
|
||||
row,totals=await self.row();self.assertEqual(row['status'],'active');self.assertTrue(row['was_restored']);self.assertTrue(row['current']);self.assertFalse(row['deleted']);self.assertEqual(totals['currentFiles'],1)
|
||||
await self.service.move_to_trash(self.item,reason='manual');await self.service.purge_trashed_file(self.item)
|
||||
row,totals=await self.row();self.assertEqual(row['status'],'purged');self.assertTrue(row['deleted']);self.assertFalse(row['can_download']);self.assertEqual(totals['currentFiles'],0)
|
||||
async def test_current_state_is_not_lost_outside_selected_activity_date_range(self):
|
||||
await self.service.move_to_trash(self.item,reason='expired_time')
|
||||
row,_=await self.row(start='2020-01-01',end='2020-01-02');self.assertEqual(row['status'],'trashed');self.assertEqual(row['trash_reason'],'expired_time')
|
||||
async def test_expired_restored_item_stays_expired_until_policy_changes(self):
|
||||
self.item.expired_at=await get_now()-datetime.timedelta(days=1);await self.item.save()
|
||||
await self.service.move_to_trash(self.item,reason='expired_time');await self.service.restore_from_trash(self.item.id)
|
||||
row,_=await self.row();self.assertEqual(row['status'],'expired');self.assertFalse(row['can_download'])
|
||||
async def test_hard_deleted_historical_record_keeps_deleted_status(self):
|
||||
await TransferStats.create(action='delete',code=self.item.code,file_code_id=self.item.id,name='test.txt',deleted_at=await get_now())
|
||||
await self.item.delete();row,totals=await self.row();self.assertEqual(row['status'],'deleted');self.assertFalse(row['can_download']);self.assertEqual(totals['currentFiles'],0)
|
||||
@@ -48,3 +48,48 @@ class WebDAVStreamTests(WebDAVFixture):
|
||||
self.assertIn(self.payload,self.files.values())
|
||||
cancel=await self.client.delete(f'/chunk/upload/{uid}')
|
||||
self.assertEqual(cancel.status_code,200);self.assertFalse(self.files)
|
||||
|
||||
async def test_raw_chunk_upload_has_no_form_overhead_and_rejects_oversize(self):
|
||||
uid=await self.init()
|
||||
good=await self.client.post(f'/chunk/upload/raw/{uid}/0',content=self.payload[:8],headers={'Content-Type':'application/octet-stream'})
|
||||
self.assertEqual(good.status_code,200,good.text)
|
||||
bad=await self.client.post(f'/chunk/upload/raw/{uid}/1',content=b'x'*9,headers={'Content-Type':'application/octet-stream'})
|
||||
self.assertEqual(bad.status_code,413,bad.text)
|
||||
|
||||
async def test_cancel_is_idempotent_and_preserves_already_completed_file(self):
|
||||
uid=await self.init();await self.chunk(uid,0)
|
||||
first=await self.client.delete(f'/chunk/upload/{uid}');self.assertEqual(first.status_code,200)
|
||||
again=await self.client.delete(f'/chunk/upload/{uid}');self.assertEqual(again.status_code,200)
|
||||
uid=await self.upload_all();done=await self.complete(uid);code=done.json()['detail']['code']
|
||||
late=await self.client.delete(f'/chunk/upload/{uid}')
|
||||
self.assertEqual(late.status_code,200,late.text);self.assertEqual(late.json()['detail']['code'],code)
|
||||
self.assertTrue(late.json()['detail']['completed']);self.assertIn(self.payload,self.files.values())
|
||||
|
||||
async def test_cancel_preserves_completed_file_even_with_residual_session(self):
|
||||
from apps.base.models import FileCodes
|
||||
uid=await self.upload_all()
|
||||
info=await __import__('apps.base.models',fromlist=['UploadChunk']).UploadChunk.get(upload_id=uid,chunk_index=-1)
|
||||
from core.storage import WebDAVFileStorage
|
||||
await WebDAVFileStorage().finish_stream_upload(info,info.save_path)
|
||||
await FileCodes.create(code='DONE0001',upload_id=uid,prefix='sample',suffix='.txt',file_path=info.save_path.rsplit('/',1)[0],uuid_file_name='sample.txt',expired_count=-1)
|
||||
cancel=await self.client.delete(f'/chunk/upload/{uid}')
|
||||
self.assertTrue(cancel.json()['detail']['completed']);self.assertEqual(cancel.json()['detail']['code'],'DONE0001')
|
||||
self.assertEqual(list(self.files.values()),[self.payload])
|
||||
|
||||
async def test_presign_cancel_preserves_published_file_and_deferred_direct_cleanup(self):
|
||||
from apps.base.models import FileCodes,PresignUploadSession,StorageReservation
|
||||
from apps.base.views import presign_upload_cancel,_get_valid_session
|
||||
from core.utils import get_now
|
||||
from fastapi import HTTPException
|
||||
import datetime
|
||||
deadline=await get_now()+datetime.timedelta(minutes=15)
|
||||
await PresignUploadSession.create(upload_id='published',file_name='old.txt',file_size=4,save_path='old.txt',mode='proxy',expire_value=1,expire_style='day',expires_at=deadline)
|
||||
await FileCodes.create(code='PRESIGN1',upload_id='published',prefix='old',suffix='.txt',file_path='',uuid_file_name='old.txt',expired_count=-1)
|
||||
self.files['/dav/old.txt']=b'keep'
|
||||
result=await presign_upload_cancel('published');self.assertTrue(result.detail['completed']);self.assertEqual(self.files['/dav/old.txt'],b'keep')
|
||||
await PresignUploadSession.create(upload_id='direct',file_name='new.txt',file_size=4,save_path='new.txt',mode='direct',expire_value=1,expire_style='day',expires_at=deadline)
|
||||
await StorageReservation.create(token='presign:direct',size=4,expires_at=deadline)
|
||||
result=await presign_upload_cancel('direct');self.assertTrue(result.detail['cleanup_pending'])
|
||||
self.assertEqual((await PresignUploadSession.get(upload_id='direct')).mode,'cancelled')
|
||||
self.assertTrue(await StorageReservation.filter(token='presign:direct').exists())
|
||||
with self.assertRaises(HTTPException):await _get_valid_session('direct')
|
||||
Reference in new issue
Block a user