⚡ fix(webdav): 改用独立分片流式合并并隔离测试协议

This commit is contained in:
orion committed 2026-09-18 15:38:45 +08:00
1 parent 9a489297f4
commit 90089f793e
7 files changed
+255 -64

No files matched your search

+36 -52
View File
@@ -1051,9 +1051,10 @@ class OpenDALFileStorage(FileStorageInterface):
from core.webdav_chunks import WebDAVOffsetMixin
from core.webdav_stream import WebDAVStreamMixin
class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface):
class WebDAVFileStorage(WebDAVStreamMixin, WebDAVOffsetMixin, FileStorageInterface):
_instance: Optional["WebDAVFileStorage"] = None
def __init__(self):
@@ -1202,62 +1203,41 @@ class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface):
return await get_file_url(file_code.code)
async def get_file_response(self, file_code: FileCodes):
"""获取文件响应(代理模式)"""
"""Validate the upstream response before starting the downstream stream."""
filename = file_code.prefix + file_code.suffix
url = self._build_url(await file_code.get_file_path())
session = aiohttp.ClientSession(auth=self.auth, timeout=aiohttp.ClientTimeout(total=None, connect=30, sock_read=120))
try:
filename = file_code.prefix + file_code.suffix
url = self._build_url(await file_code.get_file_path())
content_length = None # 初始化为 None,表示未知大小
# 创建ClientSession并复用(包含认证头)
session = aiohttp.ClientSession(headers={
"Authorization": f"Basic {base64.b64encode(f'{settings.webdav_username}:{settings.webdav_password}'.encode()).decode()}"
})
# 尝试发送HEAD请求获取Content-Length
upstream = await session.get(url)
if upstream.status == 404:
await session.close()
raise HTTPException(404, "文件在 WebDAV 中不存在或已被移动")
if upstream.status != 200:
status_code = upstream.status
await session.close()
raise HTTPException(502, f"WebDAV 文件读取失败(上游 {status_code}),请稍后重试")
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
await session.close()
raise HTTPException(503, "WebDAV 连接失败,请稍后重试") from exc
async def stream_generator():
try:
async with session.head(url) as resp:
if resp.status == 200 and 'Content-Length' in resp.headers:
content_length = int(resp.headers['Content-Length'])
except Exception:
# 如果HEAD请求失败,则不提供 Content-Length
pass
async def stream_generator():
try:
async with session.get(url) as resp:
if resp.status != 200:
raise HTTPException(
status_code=resp.status,
detail=f"文件获取失败{resp.status}: {await resp.text()}",
)
chunk_size = 65536
while True:
chunk = await resp.content.read(chunk_size)
if not chunk:
break
yield chunk
finally:
await session.close()
encoded_filename = quote(filename, safe='')
headers = {
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
}
if content_length is not None:
headers["Content-Length"] = str(content_length)
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
)
except aiohttp.ClientError as e:
raise HTTPException(
status_code=503, detail=f"WebDAV连接异常: {str(e)}")
async for chunk in upstream.content.iter_chunked(65536):
yield chunk
finally:
upstream.release()
await session.close()
headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename, safe='')}"}
if upstream.content_length is not None:
headers["Content-Length"] = str(upstream.content_length)
return StreamingResponse(stream_generator(), media_type="application/octet-stream", headers=headers, background=BackgroundTask(session.close))
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
"""保存分片到 WebDAV"""
stream = await self._stream_session(upload_id)
if stream is not None:
return await self.save_stream_chunk(stream, chunk_index, chunk_data, chunk_hash)
info = await self._offset_session(upload_id)
if info is not None:
return await self.save_offset_chunk(info, chunk_index, chunk_data)
@@ -1282,6 +1262,8 @@ class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface):
合并 WebDAV 上的分片文件
使用临时文件避免内存问题
"""
if chunk_info.storage_mode == "webdav-stream":
return await self.finish_stream_upload(chunk_info, save_path)
if chunk_info.storage_mode == "webdav-offset":
return await self.finish_offset_upload(chunk_info, save_path)
file_sha256 = hashlib.sha256()
@@ -1354,6 +1336,8 @@ class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface):
:param upload_id: 上传会话ID
:param save_path: 文件保存路径
"""
if await self._stream_session(upload_id) is not None:
return await self.clean_stream_upload(upload_id, 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)
+3
View File
@@ -18,6 +18,9 @@ class WebDAVOffsetMixin:
return str(PurePosixPath(save_path).parent / 'chunks' / upload_id / 'upload.bin')
async def chunk_upload_mode(self):
return "webdav-stream"
async def offset_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):
+102
View File
@@ -0,0 +1,102 @@
"""Immutable remote parts and streamed assembly for cloud-backed WebDAV."""
import asyncio
import hashlib
from pathlib import PurePosixPath
import aiohttp
from fastapi import HTTPException
from apps.base.models import UploadChunk
from core.webdav_chunks import OFFSET_TIMEOUT
STREAM_MODE = 'webdav-stream'
class WebDAVStreamMixin:
async def _stream_session(self, upload_id):
return await UploadChunk.filter(upload_id=upload_id, chunk_index=-1, storage_mode=STREAM_MODE).first()
def _stream_part_path(self, info, index):
return str(PurePosixPath(info.save_path).parent / 'chunks' / info.upload_id / f'{index}.part')
async def save_stream_chunk(self, info, index, data, expected_hash):
expected = min(info.chunk_size, info.file_size-index*info.chunk_size)
if len(data) != expected:
raise HTTPException(400, '分片大小与声明值不一致')
path = self._stream_part_path(info,index)
await self._mkdir_p(str(PurePosixPath(path).parent))
async with aiohttp.ClientSession(auth=self.auth,timeout=OFFSET_TIMEOUT) as client:
url=self._build_url(path)
# Never PATCH an object already synchronizing to the cloud.
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,f'WebDAV 分片上传失败(上游 {response.status}),请重试')
digest=hashlib.sha256();length=0
async with client.get(url) as response:
if response.status != 200:
raise HTTPException(503,'WebDAV 分片状态暂时无法确认,请重试')
async for block in response.content.iter_chunked(65536):
digest.update(block);length+=len(block)
if length==len(data) and digest.hexdigest()==expected_hash:return
# A failed first PUT can leave a partial object; delete before replacing.
async with client.delete(url) as response:
if response.status not in (200,204,404):raise HTTPException(503,'WebDAV 分片重试清理失败')
async with client.put(url,data=data,headers={'If-None-Match':'*'}) as response:
if response.status not in (200,201,204):raise HTTPException(503,'WebDAV 分片重传失败,请重试')
async def finish_stream_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('分片不完整')
directory=str(PurePosixPath(self._stream_part_path(info,0)).parent)
staging=directory+'/assembled.bin'
async with aiohttp.ClientSession(auth=self.auth,timeout=OFFSET_TIMEOUT) as client:
# Recover a completed MOVE whose response/database acknowledgement was lost.
digest=await self._verify_offset_file(client,save_path,info,records)
if digest is not None:return save_path,digest
async with client.delete(self._build_url(staging)) as response:
if response.status not in (200,204,404):raise HTTPException(503,'WebDAV 合并临时文件清理失败')
verified=0
async def stream_parts():
nonlocal verified
for index,record in enumerate(records):
digest=hashlib.sha256();length=0
expected=min(info.chunk_size,info.file_size-index*info.chunk_size)
async with client.get(self._build_url(self._stream_part_path(info,index))) as response:
if response.status!=200:raise ValueError('远端分片缺失,请重新上传')
async for block in response.content.iter_chunked(65536):
length+=len(block)
if length>expected:raise ValueError('远端分片大小异常')
digest.update(block);yield block
if length!=expected or digest.hexdigest()!=record.chunk_hash:raise ValueError('远端分片校验失败,请重新上传')
verified+=1
async def assemble():
try:
async with client.put(self._build_url(staging),data=stream_parts(),headers={'Content-Length':str(info.file_size),'If-None-Match':'*'}) as response:
if response.status not in (200,201,204):raise HTTPException(503,f'WebDAV 流式合并失败(上游 {response.status})')
except aiohttp.ClientError as exc:
raise HTTPException(503,'WebDAV 流式合并中断,请重试完成上传') from exc
task=asyncio.create_task(assemble())
try:await asyncio.shield(task)
except asyncio.CancelledError:
await task
raise
if verified!=len(records):raise ValueError('分片校验未完成,请重新上传')
digest=await self._verify_offset_file(client,staging,info,records)
if digest is None:raise ValueError('合并后的文件不存在')
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_stream_upload(self, upload_id, save_path):
info = await self._stream_session(upload_id)
if info is None:
return
directory = str(PurePosixPath(self._stream_part_path(info, 0)).parent)
async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client:
async with client.delete(self._build_url(directory)) as response:
if response.status not in (200, 204, 404):
raise HTTPException(503, 'WebDAV 分片清理失败,请重试')