⚡ perf(webdav): 偏移写入分片并取消整文件落盘合并
This commit is contained in:
1 parent
6d825e5fbc
commit
32298bfdeb
12 files changed
+690
-53
No files matched your search
+11
-1
@@ -1050,7 +1050,10 @@ class OpenDALFileStorage(FileStorageInterface):
|
||||
return False
|
||||
|
||||
|
||||
class WebDAVFileStorage(FileStorageInterface):
|
||||
from core.webdav_chunks import WebDAVOffsetMixin
|
||||
|
||||
|
||||
class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface):
|
||||
_instance: Optional["WebDAVFileStorage"] = None
|
||||
|
||||
def __init__(self):
|
||||
@@ -1255,6 +1258,9 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
|
||||
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
|
||||
"""保存分片到 WebDAV"""
|
||||
info = await self._offset_session(upload_id)
|
||||
if info is not None:
|
||||
return await self.save_offset_chunk(info, chunk_index, chunk_data)
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
chunk_path = f"{chunk_dir}/{chunk_index}.part"
|
||||
|
||||
@@ -1276,6 +1282,8 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
合并 WebDAV 上的分片文件
|
||||
使用临时文件避免内存问题
|
||||
"""
|
||||
if chunk_info.storage_mode == "webdav-offset":
|
||||
return await self.finish_offset_upload(chunk_info, save_path)
|
||||
file_sha256 = hashlib.sha256()
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
|
||||
@@ -1346,6 +1354,8 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
:param upload_id: 上传会话ID
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
if await self._offset_session(upload_id) is not None:
|
||||
return await self.clean_offset_upload(upload_id, save_path)
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
chunk_dir_url = self._build_url(chunk_dir)
|
||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
||||
|
||||
+16
-20
@@ -17,6 +17,7 @@ from apps.base.models import (
|
||||
from apps.admin.services import FileService
|
||||
from apps.base.utils import ip_limit, get_chunk_file_path_name
|
||||
from core.config import refresh_settings
|
||||
from apps.base.upload_sessions import upload_lock
|
||||
from core.logger import logger
|
||||
from apps.admin.trash_management import automatic_trash_reason
|
||||
from core.settings import settings, data_root
|
||||
@@ -65,6 +66,19 @@ async def delete_expire_files():
|
||||
await asyncio.sleep(600)
|
||||
|
||||
|
||||
async def clean_expired_chunk_session(upload_id, expire_time):
|
||||
async with upload_lock(upload_id):
|
||||
session = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1, created_at__lt=expire_time).first()
|
||||
if session is None:
|
||||
return
|
||||
save_path = session.save_path
|
||||
if not save_path:
|
||||
_, _, _, _, save_path = await get_chunk_file_path_name(session.file_name, session.upload_id)
|
||||
await storages[settings.file_storage]().clean_chunks(upload_id, save_path)
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await StorageReservation.filter(token=f"chunk:{upload_id}").delete()
|
||||
|
||||
|
||||
async def clean_incomplete_uploads():
|
||||
while True:
|
||||
try:
|
||||
@@ -79,27 +93,9 @@ async def clean_incomplete_uploads():
|
||||
|
||||
for session in expired_sessions:
|
||||
try:
|
||||
save_path = session.save_path
|
||||
if not save_path:
|
||||
_, _, _, _, save_path = await get_chunk_file_path_name(
|
||||
session.file_name, session.upload_id
|
||||
)
|
||||
await file_storage.clean_chunks(session.upload_id, save_path)
|
||||
await clean_expired_chunk_session(session.upload_id, expire_time)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"清理分片文件失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
|
||||
try:
|
||||
await UploadChunk.filter(upload_id=session.upload_id).delete()
|
||||
await StorageReservation.filter(
|
||||
token=f"chunk:{session.upload_id}"
|
||||
).delete()
|
||||
logger.info(f"已清理过期上传会话 upload_id={session.upload_id}")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"删除分片记录失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
logger.error(f"清理分片失败,保留会话等待重试 upload_id={session.upload_id}: {e}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"清理未完成上传任务异常: {e}")
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""WebDAV offset writes: one remote staging object, no local whole-file merge."""
|
||||
import hashlib
|
||||
import asyncio
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
import aiohttp
|
||||
from fastapi import HTTPException
|
||||
|
||||
from apps.base.models import FileCodes, UploadChunk
|
||||
|
||||
OFFSET_MODE = 'webdav-offset'
|
||||
# Total verification time scales with file size; only stalled I/O is bounded.
|
||||
OFFSET_TIMEOUT = aiohttp.ClientTimeout(total=None, connect=30, sock_read=120)
|
||||
|
||||
|
||||
class WebDAVOffsetMixin:
|
||||
def _offset_path(self, upload_id, save_path):
|
||||
return str(PurePosixPath(save_path).parent / 'chunks' / upload_id / 'upload.bin')
|
||||
|
||||
async def chunk_upload_mode(self):
|
||||
async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client:
|
||||
async with client.options(self.base_url) as response:
|
||||
if response.status not in (200,204):
|
||||
raise HTTPException(503, '无法确认 WebDAV 分片能力,请重试')
|
||||
return OFFSET_MODE if 'sabredav-partialupdate' in response.headers.get('DAV','').lower() else 'legacy'
|
||||
|
||||
async def _offset_session(self, upload_id):
|
||||
return await UploadChunk.filter(upload_id=upload_id, chunk_index=-1, storage_mode=OFFSET_MODE).first()
|
||||
|
||||
async def save_offset_chunk(self, info, index, data):
|
||||
expected = min(info.chunk_size, info.file_size-index*info.chunk_size)
|
||||
if len(data) != expected:
|
||||
raise HTTPException(400, '分片大小与声明值不一致')
|
||||
previous = await UploadChunk.filter(upload_id=info.upload_id, completed=True, chunk_index__lt=index).count()
|
||||
if previous != index:
|
||||
raise HTTPException(409, '请先上传前面的分片,再重试当前分片')
|
||||
path = self._offset_path(info.upload_id, info.save_path)
|
||||
await self._mkdir_p(str(PurePosixPath(path).parent))
|
||||
url = self._build_url(path)
|
||||
async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client:
|
||||
if index == 0:
|
||||
# A lost first-PUT response must not truncate a previously written object.
|
||||
async with client.put(url, data=data, headers={'If-None-Match':'*'}) as response:
|
||||
if response.status in (200,201,204):
|
||||
return
|
||||
if response.status != 412:
|
||||
raise HTTPException(503, 'WebDAV 分片写入失败,请重试')
|
||||
start = index*info.chunk_size
|
||||
async with client.patch(url, data=data, headers={
|
||||
'Content-Type':'application/x-sabredav-partialupdate',
|
||||
'X-Update-Range':f'bytes={start}-{start+len(data)-1}',
|
||||
}) as response:
|
||||
if response.status not in (200,204):
|
||||
raise HTTPException(503, 'WebDAV 偏移写入失败,请重试')
|
||||
|
||||
async def _verify_offset_file(self, client, path, info, records):
|
||||
full = hashlib.sha256(); chunk_hash = hashlib.sha256()
|
||||
total = 0; index = 0; in_chunk = 0
|
||||
async with client.get(self._build_url(path)) as response:
|
||||
if response.status == 404:
|
||||
return None
|
||||
if response.status != 200:
|
||||
raise HTTPException(503, 'WebDAV 文件校验读取失败,请重试')
|
||||
async for data in response.content.iter_chunked(65536):
|
||||
if total + len(data) > info.file_size:
|
||||
raise ValueError('WebDAV 文件大小与声明值不一致')
|
||||
total += len(data); full.update(data)
|
||||
offset = 0
|
||||
while offset < len(data):
|
||||
boundary = min(info.chunk_size, info.file_size-index*info.chunk_size)
|
||||
amount = min(boundary-in_chunk, len(data)-offset)
|
||||
chunk_hash.update(data[offset:offset+amount]); in_chunk += amount; offset += amount
|
||||
if in_chunk == boundary:
|
||||
if index >= len(records) or chunk_hash.hexdigest() != records[index].chunk_hash:
|
||||
raise ValueError('WebDAV 分片内容校验失败,请取消后重新上传')
|
||||
index += 1; in_chunk = 0; chunk_hash = hashlib.sha256()
|
||||
if total != info.file_size or index != info.total_chunks:
|
||||
raise ValueError('WebDAV 文件大小与声明值不一致')
|
||||
# Session chunk_hash is a resumability fingerprint (large clients hash
|
||||
# first/last segments), not the full-file digest. Per-chunk SHA-256
|
||||
# above proves contents; the SHA-256 stored on FileCodes covers all bytes.
|
||||
return full.hexdigest()
|
||||
|
||||
async def _publish_offset(self, client, staging, save_path):
|
||||
async with client.request('MOVE', self._build_url(staging), headers={
|
||||
'Destination':self._build_url(save_path), 'Overwrite':'F',
|
||||
}) as response:
|
||||
if response.status not in (201,204):
|
||||
raise HTTPException(503, 'WebDAV 文件发布失败,请重试完成上传')
|
||||
|
||||
async def finish_offset_upload(self, info, save_path):
|
||||
records = await UploadChunk.filter(upload_id=info.upload_id, completed=True).order_by('chunk_index')
|
||||
if [r.chunk_index for r in records] != list(range(info.total_chunks)):
|
||||
raise ValueError('分片不完整')
|
||||
staging = self._offset_path(info.upload_id, save_path)
|
||||
async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client:
|
||||
digest = await self._verify_offset_file(client, staging, info, records)
|
||||
if digest is None:
|
||||
# MOVE may have completed even when its response/DB write was lost.
|
||||
digest = await self._verify_offset_file(client, save_path, info, records)
|
||||
if digest is None:
|
||||
raise ValueError('上传临时文件不存在,请取消后重新上传')
|
||||
return save_path, digest
|
||||
await self._mkdir_p(str(PurePosixPath(save_path).parent))
|
||||
# Disconnecting our request does not cancel the server-side MOVE.
|
||||
# Wait for the remote commit to settle before cancellation can clean it.
|
||||
move = asyncio.create_task(self._publish_offset(client, staging, save_path))
|
||||
try:
|
||||
await asyncio.shield(move)
|
||||
except asyncio.CancelledError:
|
||||
await move
|
||||
raise
|
||||
return save_path, digest
|
||||
|
||||
async def clean_offset_upload(self, upload_id, save_path):
|
||||
directory = str(PurePosixPath(self._offset_path(upload_id,save_path)).parent)
|
||||
paths = [directory]
|
||||
if not await FileCodes.filter(upload_id=upload_id).exists():
|
||||
paths.append(save_path)
|
||||
async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client:
|
||||
for path in paths:
|
||||
async with client.delete(self._build_url(path)) as response:
|
||||
if response.status not in (200,204,404):
|
||||
raise HTTPException(503, 'WebDAV 上传清理失败,请重试')
|
||||
Reference in new issue
Block a user