⚡ perf(webdav): 偏移写入分片并取消整文件落盘合并
This commit is contained in:
1 parent
6d825e5fbc
commit
32298bfdeb
12 files changed
+690
-53
No files matched your search
@@ -0,0 +1,8 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get('default')
|
||||
columns = await conn.execute_query_dict('PRAGMA table_info(uploadchunk)')
|
||||
if not any(column['name']=='storage_mode' for column in columns):
|
||||
await conn.execute_script("ALTER TABLE uploadchunk ADD COLUMN storage_mode VARCHAR(32) NOT NULL DEFAULT 'legacy';")
|
||||
@@ -71,6 +71,7 @@ class UploadChunk(models.Model):
|
||||
save_path = fields.CharField(max_length=512, null=True)
|
||||
created_at = fields.DatetimeField(auto_now_add=True)
|
||||
completed = fields.BooleanField(default=False)
|
||||
storage_mode = fields.CharField(max_length=32, default="legacy")
|
||||
|
||||
|
||||
class TransferStats(models.Model):
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@@ -8,8 +8,8 @@ class SelectFileModel(BaseModel):
|
||||
|
||||
class InitChunkUploadModel(BaseModel):
|
||||
file_name: str
|
||||
chunk_size: int = 5 * 1024 * 1024
|
||||
file_size: int
|
||||
chunk_size: int = Field(default=5 * 1024 * 1024, gt=0)
|
||||
file_size: int = Field(gt=0)
|
||||
file_hash: str
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Serialize each upload's writes/finalization/cleanup in single-worker deployments."""
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from functools import wraps
|
||||
from weakref import WeakValueDictionary
|
||||
|
||||
_locks = WeakValueDictionary()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def upload_lock(upload_id):
|
||||
lock = _locks.get(upload_id)
|
||||
if lock is None:
|
||||
lock = asyncio.Lock()
|
||||
_locks[upload_id] = lock
|
||||
async with lock:
|
||||
yield
|
||||
|
||||
|
||||
def serialize_upload(function):
|
||||
@wraps(function)
|
||||
async def wrapped(*args, **kwargs):
|
||||
upload_id = kwargs.get('upload_id') if 'upload_id' in kwargs else args[0]
|
||||
async with upload_lock(upload_id):
|
||||
return await function(*args, **kwargs)
|
||||
return wrapped
|
||||
|
||||
|
||||
_completion_tasks = {}
|
||||
_cancelling = set()
|
||||
|
||||
|
||||
def is_cancelling(upload_id):
|
||||
return upload_id in _cancelling
|
||||
|
||||
|
||||
def begin_cancel(upload_id):
|
||||
_cancelling.add(upload_id)
|
||||
|
||||
|
||||
def end_cancel(upload_id):
|
||||
_cancelling.discard(upload_id)
|
||||
|
||||
|
||||
def completion_task(upload_id):
|
||||
return _completion_tasks.get(upload_id)
|
||||
|
||||
|
||||
def start_completion(upload_id, coroutine):
|
||||
task = asyncio.create_task(coroutine, name=f'upload-completion-{upload_id}')
|
||||
_completion_tasks[upload_id] = task
|
||||
def completed(done):
|
||||
if not done.cancelled():
|
||||
done.exception() # Observe failures even if the browser disconnects.
|
||||
def expire():
|
||||
if _completion_tasks.get(upload_id) is done:
|
||||
_completion_tasks.pop(upload_id, None)
|
||||
asyncio.get_running_loop().call_later(300, expire)
|
||||
task.add_done_callback(completed)
|
||||
return task
|
||||
|
||||
|
||||
def take_completion(upload_id):
|
||||
return _completion_tasks.pop(upload_id)
|
||||
|
||||
|
||||
async def cancel_completion(upload_id):
|
||||
task = _completion_tasks.pop(upload_id, None)
|
||||
if task is not None:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
|
||||
|
||||
async def shutdown_completions():
|
||||
for upload_id in list(_completion_tasks):
|
||||
await cancel_completion(upload_id)
|
||||
+105
-28
@@ -16,6 +16,7 @@ from tortoise.expressions import Case, F, Q, When
|
||||
from apps.admin.dependencies import share_required_login
|
||||
from apps.base.models import FileCodes, UploadChunk, PresignUploadSession, TransferStats
|
||||
from apps.base.quota import release_storage, reserve_storage
|
||||
from apps.base.upload_sessions import (serialize_upload, upload_lock, completion_task, start_completion, take_completion, cancel_completion, is_cancelling, begin_cancel, end_cancel)
|
||||
|
||||
from apps.base.schemas import (
|
||||
SelectFileModel,
|
||||
@@ -442,7 +443,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
validate_file_type(safe_file_name)
|
||||
# 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量
|
||||
total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size
|
||||
max_possible_size = total_chunks * data.chunk_size
|
||||
max_possible_size = data.file_size
|
||||
if max_possible_size > settings.uploadSize:
|
||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
@@ -473,30 +474,41 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
).first()
|
||||
|
||||
if existing_session:
|
||||
if not existing_session.save_path:
|
||||
await UploadChunk.filter(upload_id=existing_session.upload_id).delete()
|
||||
await release_storage(f"chunk:{existing_session.upload_id}")
|
||||
else:
|
||||
await reserve_storage(
|
||||
f"chunk:{existing_session.upload_id}",
|
||||
existing_session.file_size,
|
||||
ttl_seconds=max(
|
||||
1, int(getattr(settings, "chunk_expire_hours", 24))
|
||||
)
|
||||
* 3600,
|
||||
)
|
||||
uploaded_chunks = await UploadChunk.filter(
|
||||
upload_id=existing_session.upload_id, completed=True
|
||||
).values_list("chunk_index", flat=True)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"existed": False,
|
||||
"upload_id": existing_session.upload_id,
|
||||
"chunk_size": existing_session.chunk_size,
|
||||
"total_chunks": existing_session.total_chunks,
|
||||
"uploaded_chunks": list(uploaded_chunks),
|
||||
}
|
||||
)
|
||||
task = completion_task(existing_session.upload_id)
|
||||
if task is not None and not task.done():
|
||||
return APIResponse(detail={
|
||||
"existed":False,"upload_id":existing_session.upload_id,
|
||||
"chunk_size":existing_session.chunk_size,"total_chunks":existing_session.total_chunks,
|
||||
"uploaded_chunks":list(range(existing_session.total_chunks)),"processing":True,
|
||||
})
|
||||
async with upload_lock(existing_session.upload_id):
|
||||
existing_session = await UploadChunk.filter(upload_id=existing_session.upload_id, chunk_index=-1).first()
|
||||
if existing_session:
|
||||
if not existing_session.save_path:
|
||||
await UploadChunk.filter(upload_id=existing_session.upload_id).delete()
|
||||
await release_storage(f"chunk:{existing_session.upload_id}")
|
||||
else:
|
||||
await reserve_storage(
|
||||
f"chunk:{existing_session.upload_id}",
|
||||
existing_session.file_size,
|
||||
ttl_seconds=max(
|
||||
1, int(getattr(settings, "chunk_expire_hours", 24))
|
||||
)
|
||||
* 3600,
|
||||
)
|
||||
await UploadChunk.filter(id=existing_session.id).update(created_at=await get_now())
|
||||
uploaded_chunks = await UploadChunk.filter(
|
||||
upload_id=existing_session.upload_id, completed=True
|
||||
).values_list("chunk_index", flat=True)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"existed": False,
|
||||
"upload_id": existing_session.upload_id,
|
||||
"chunk_size": existing_session.chunk_size,
|
||||
"total_chunks": existing_session.total_chunks,
|
||||
"uploaded_chunks": list(uploaded_chunks),
|
||||
}
|
||||
)
|
||||
|
||||
# 创建新的上传会话
|
||||
upload_id = uuid.uuid4().hex
|
||||
@@ -509,8 +521,14 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
data.file_name, upload_id
|
||||
)
|
||||
try:
|
||||
storage_mode = "legacy"
|
||||
if settings.file_storage == "webdav":
|
||||
storage_mode = await storages["webdav"]().chunk_upload_mode()
|
||||
if storage_mode == "legacy" and total_chunks * data.chunk_size > settings.uploadSize:
|
||||
raise HTTPException(403, "文件分片大小超过上传限制")
|
||||
await UploadChunk.create(
|
||||
upload_id=upload_id,
|
||||
storage_mode=storage_mode,
|
||||
chunk_index=-1,
|
||||
total_chunks=total_chunks,
|
||||
file_size=data.file_size,
|
||||
@@ -537,6 +555,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
"/upload/chunk/{upload_id}/{chunk_index}",
|
||||
dependencies=[Depends(share_required_login)],
|
||||
)
|
||||
@serialize_upload
|
||||
async def upload_chunk(
|
||||
upload_id: str,
|
||||
chunk_index: int,
|
||||
@@ -560,7 +579,7 @@ async def upload_chunk(
|
||||
existing_chunk = await UploadChunk.filter(
|
||||
upload_id=upload_id, chunk_index=chunk_index, completed=True
|
||||
).first()
|
||||
if existing_chunk:
|
||||
if existing_chunk and chunk_info.storage_mode != "webdav-offset":
|
||||
return APIResponse(
|
||||
detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True}
|
||||
)
|
||||
@@ -583,7 +602,7 @@ async def upload_chunk(
|
||||
upload_id=upload_id, completed=True
|
||||
).count()
|
||||
# 已上传分片的最大可能大小 + 当前分片
|
||||
max_uploaded_size = uploaded_count * chunk_info.chunk_size + chunk_size
|
||||
max_uploaded_size = chunk_info.file_size if chunk_info.storage_mode == "webdav-offset" else uploaded_count * chunk_info.chunk_size + chunk_size
|
||||
if max_uploaded_size > settings.uploadSize:
|
||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
@@ -591,6 +610,15 @@ async def upload_chunk(
|
||||
)
|
||||
|
||||
chunk_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if chunk_info.storage_mode == "webdav-offset":
|
||||
expected_size = min(chunk_info.chunk_size, chunk_info.file_size-chunk_index*chunk_info.chunk_size)
|
||||
if chunk_size != expected_size:
|
||||
raise HTTPException(400, "分片大小与声明值不一致")
|
||||
if existing_chunk:
|
||||
if existing_chunk.chunk_hash != chunk_hash:
|
||||
raise HTTPException(409, "重传分片内容不一致")
|
||||
return APIResponse(detail={"chunk_hash":chunk_hash,"skipped":True})
|
||||
|
||||
|
||||
save_path = chunk_info.save_path
|
||||
|
||||
@@ -600,6 +628,8 @@ async def upload_chunk(
|
||||
await storage.save_chunk(
|
||||
upload_id, chunk_index, chunk_data, chunk_hash, save_path
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"分片保存失败: {str(e)}"
|
||||
@@ -619,11 +649,24 @@ async def upload_chunk(
|
||||
"save_path": chunk_info.save_path,
|
||||
},
|
||||
)
|
||||
await UploadChunk.filter(id=chunk_info.id).update(created_at=await get_now())
|
||||
return APIResponse(detail={"chunk_hash": chunk_hash})
|
||||
|
||||
|
||||
@chunk_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||
async def cancel_upload(upload_id: str):
|
||||
if is_cancelling(upload_id):
|
||||
raise HTTPException(409, "上传正在取消,请稍后重试")
|
||||
begin_cancel(upload_id)
|
||||
try:
|
||||
await cancel_completion(upload_id)
|
||||
return await _cancel_upload(upload_id)
|
||||
finally:
|
||||
end_cancel(upload_id)
|
||||
|
||||
|
||||
@serialize_upload
|
||||
async def _cancel_upload(upload_id):
|
||||
"""取消上传并清理临时文件"""
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if not chunk_info:
|
||||
@@ -637,6 +680,8 @@ async def cancel_upload(upload_id: str):
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception as e:
|
||||
if chunk_info.storage_mode == "webdav-offset":
|
||||
raise
|
||||
pass
|
||||
|
||||
# 清理数据库记录
|
||||
@@ -681,6 +726,32 @@ async def complete_upload(
|
||||
data: CompleteUploadModel = Depends(parse_complete_upload),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
if is_cancelling(upload_id):
|
||||
raise HTTPException(409, "上传正在取消")
|
||||
task = completion_task(upload_id)
|
||||
if task is None:
|
||||
info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if is_cancelling(upload_id):
|
||||
raise HTTPException(409, "上传正在取消")
|
||||
if info is None or info.storage_mode != "webdav-offset":
|
||||
return await _complete_upload(upload_id, data, ip)
|
||||
task = completion_task(upload_id)
|
||||
if task is None:
|
||||
task = start_completion(upload_id, _complete_upload(upload_id, data, ip))
|
||||
if not task.done():
|
||||
return APIResponse(code=202, detail={"upload_id":upload_id,"processing":True})
|
||||
return take_completion(upload_id).result()
|
||||
|
||||
|
||||
@serialize_upload
|
||||
async def _complete_upload(upload_id, data, ip):
|
||||
published = await FileCodes.filter(upload_id=upload_id, is_trashed=False).first()
|
||||
if published:
|
||||
storage = storages[settings.file_storage]()
|
||||
await storage.clean_chunks(upload_id, await published.get_file_path())
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
return APIResponse(detail={"code":published.code,"name":published.prefix+published.suffix})
|
||||
# 获取上传基本信息
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if not chunk_info:
|
||||
@@ -701,13 +772,15 @@ async def complete_upload(
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整")
|
||||
|
||||
# 用分片数 * chunk_size 校验最大可能大小
|
||||
max_total_size = len(completed_chunks_list) * chunk_info.chunk_size
|
||||
max_total_size = chunk_info.file_size if chunk_info.storage_mode == "webdav-offset" else len(completed_chunks_list) * chunk_info.chunk_size
|
||||
if max_total_size > settings.uploadSize:
|
||||
save_path = chunk_info.save_path
|
||||
if save_path:
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception:
|
||||
if chunk_info.storage_mode == "webdav-offset":
|
||||
raise
|
||||
pass
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
@@ -752,7 +825,11 @@ async def complete_upload(
|
||||
return APIResponse(detail={"code": code, "name": safe_file_name})
|
||||
except ValueError as e:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
if chunk_info.storage_mode == "webdav-offset":
|
||||
raise HTTPException(500, "上传完成状态保存失败,请重试完成上传") from e
|
||||
# 合并失败时清理临时文件
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
|
||||
Reference in new issue
Block a user