diff --git a/apps/base/views.py b/apps/base/views.py index 751c419..dcefda0 100644 --- a/apps/base/views.py +++ b/apps/base/views.py @@ -465,6 +465,9 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun # "name": f'{existing.prefix}{existing.suffix}' # }) + preferred_mode = "legacy" + if settings.file_storage == "webdav": + preferred_mode = await storages["webdav"]().chunk_upload_mode() # 断点续传:检查是否存在相同文件的未完成上传会话 existing_session = await UploadChunk.filter( chunk_hash=data.file_hash, @@ -473,6 +476,10 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun file_name=safe_file_name, ).first() + if existing_session and existing_session.storage_mode == "webdav-offset" and preferred_mode == "webdav-stream": + # Restart the failed mutable-object protocol instead of extending it again. + await cancel_upload(existing_session.upload_id) + existing_session = None if existing_session: task = completion_task(existing_session.upload_id) if task is not None and not task.done(): @@ -521,9 +528,7 @@ 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() + storage_mode = preferred_mode if storage_mode == "legacy" and total_chunks * data.chunk_size > settings.uploadSize: raise HTTPException(403, "文件分片大小超过上传限制") await UploadChunk.create( @@ -579,7 +584,7 @@ async def upload_chunk( existing_chunk = await UploadChunk.filter( upload_id=upload_id, chunk_index=chunk_index, completed=True ).first() - if existing_chunk and chunk_info.storage_mode != "webdav-offset": + if existing_chunk and chunk_info.storage_mode not in {"webdav-offset", "webdav-stream"}: return APIResponse( detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True} ) @@ -602,7 +607,7 @@ async def upload_chunk( upload_id=upload_id, completed=True ).count() # 已上传分片的最大可能大小 + 当前分片 - max_uploaded_size = chunk_info.file_size if chunk_info.storage_mode == "webdav-offset" else uploaded_count * chunk_info.chunk_size + chunk_size + max_uploaded_size = chunk_info.file_size if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"} else uploaded_count * chunk_info.chunk_size + chunk_size if max_uploaded_size > settings.uploadSize: max_size_mb = settings.uploadSize / (1024 * 1024) raise HTTPException( @@ -610,7 +615,7 @@ async def upload_chunk( ) chunk_hash = hashlib.sha256(chunk_data).hexdigest() - if chunk_info.storage_mode == "webdav-offset": + if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: 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, "分片大小与声明值不一致") @@ -680,7 +685,7 @@ async def _cancel_upload(upload_id): try: await storage.clean_chunks(upload_id, save_path) except Exception as e: - if chunk_info.storage_mode == "webdav-offset": + if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: raise pass @@ -733,7 +738,7 @@ async def complete_upload( 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": + if info is None or info.storage_mode not in {"webdav-offset", "webdav-stream"}: return await _complete_upload(upload_id, data, ip) task = completion_task(upload_id) if task is None: @@ -772,14 +777,14 @@ async def _complete_upload(upload_id, data, ip): raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整") # 用分片数 * 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 + max_total_size = chunk_info.file_size if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"} 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": + if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: raise pass await UploadChunk.filter(upload_id=upload_id).delete() @@ -828,7 +833,7 @@ async def _complete_upload(upload_id, data, ip): except HTTPException: raise except Exception as e: - if chunk_info.storage_mode == "webdav-offset": + if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: raise HTTPException(500, "上传完成状态保存失败,请重试完成上传") from e # 合并失败时清理临时文件 try: diff --git a/core/storage.py b/core/storage.py index c80a882..a4d877b 100644 --- a/core/storage.py +++ b/core/storage.py @@ -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) diff --git a/core/webdav_chunks.py b/core/webdav_chunks.py index 582c86d..9e44781 100644 --- a/core/webdav_chunks.py +++ b/core/webdav_chunks.py @@ -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): diff --git a/core/webdav_stream.py b/core/webdav_stream.py new file mode 100644 index 0000000..355793c --- /dev/null +++ b/core/webdav_stream.py @@ -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 分片清理失败,请重试') diff --git a/tests/test_webdav_download.py b/tests/test_webdav_download.py new file mode 100644 index 0000000..30ba60c --- /dev/null +++ b/tests/test_webdav_download.py @@ -0,0 +1,43 @@ +import unittest +from types import SimpleNamespace +from aiohttp import web +from fastapi import FastAPI +import httpx +from core.settings import settings +from core.storage import WebDAVFileStorage + + +class WebDAVDownloadTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self): + self.original=dict(settings.user_config);self.status=200;self.data=b'old file bytes' + upstream=web.Application();upstream.router.add_route('*','/dav/{path:.*}',self.handle) + self.runner=web.AppRunner(upstream);await self.runner.setup();site=web.TCPSite(self.runner,'127.0.0.1',0);await site.start() + port=site._server.sockets[0].getsockname()[1] + settings.user_config={'webdav_url':f'http://127.0.0.1:{port}/dav','webdav_username':'test','webdav_password':'test'} + app=FastAPI() + @app.get('/download') + async def download(): + async def path():return 'share/data/2026/05/18/old-id/old.apk' + return await WebDAVFileStorage().get_file_response(SimpleNamespace(prefix='历史文件',suffix='.apk',get_file_path=path)) + self.client=httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url='http://test') + + async def asyncTearDown(self): + await self.client.aclose();await self.runner.cleanup();settings.user_config=self.original + + async def handle(self,request): + # Some DAV servers answer HEAD but cannot fetch the backing cloud object. + if request.method=='HEAD':return web.Response(headers={'Content-Length':str(len(self.data))}) + return web.Response(status=self.status,body=self.data if self.status==200 else b'upstream-error') + + async def test_missing_upstream_is_404_before_stream_headers_start(self): + self.status=404;r=await self.client.get('/download') + self.assertEqual(r.status_code,404,r.text);self.assertIn('文件',r.json()['detail']) + + async def test_upstream_range_error_is_readable_gateway_error(self): + self.status=416;r=await self.client.get('/download') + self.assertEqual(r.status_code,502,r.text);self.assertIn('WebDAV',r.json()['detail']) + + async def test_existing_legacy_file_streams_bytes_and_filename(self): + r=await self.client.get('/download');self.assertEqual(r.status_code,200) + self.assertEqual(r.content,self.data);self.assertEqual(r.headers['content-length'],str(len(self.data))) + self.assertIn("filename*=UTF-8''",r.headers['content-disposition']) diff --git a/tests/test_webdav_offset_upload.py b/tests/test_webdav_offset_upload.py index ea36b6d..91019c7 100644 --- a/tests/test_webdav_offset_upload.py +++ b/tests/test_webdav_offset_upload.py @@ -15,7 +15,7 @@ from core.settings import settings from tests.helpers import init_memory_db, close_db -class WebDAVOffsetTests(unittest.IsolatedAsyncioTestCase): +class WebDAVFixture(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): self.original = dict(settings.user_config) await init_memory_db() @@ -96,6 +96,17 @@ class WebDAVOffsetTests(unittest.IsolatedAsyncioTestCase): for i in range(3):self.assertEqual((await self.chunk(uid,i)).status_code,200) return uid +class WebDAVOffsetTests(WebDAVFixture): + async def asyncSetUp(self): + await super().asyncSetUp() + from core.storage import WebDAVFileStorage + self.mode_patch = patch.object(WebDAVFileStorage, 'chunk_upload_mode', WebDAVFileStorage.offset_upload_mode) + self.mode_patch.start() + + async def asyncTearDown(self): + self.mode_patch.stop() + await super().asyncTearDown() + async def test_offset_upload_resume_retry_and_no_local_merge(self): uid=await self.init() self.assertEqual((await UploadChunk.get(upload_id=uid,chunk_index=-1)).storage_mode,'webdav-offset') diff --git a/tests/test_webdav_stream_upload.py b/tests/test_webdav_stream_upload.py new file mode 100644 index 0000000..c8e4bb3 --- /dev/null +++ b/tests/test_webdav_stream_upload.py @@ -0,0 +1,43 @@ +"""Independent immutable DAV parts; one streaming assembly, never PATCH/tempfile.""" +import hashlib +from unittest.mock import patch +from tests.test_webdav_offset_upload import WebDAVFixture + + +class WebDAVStreamTests(WebDAVFixture): + async def asyncSetUp(self): + await super().asyncSetUp() + from core.storage import WebDAVFileStorage + self.mode_patch = patch.object(WebDAVFileStorage, 'chunk_upload_mode', return_value='webdav-stream') + self.mode_patch.start() + + async def asyncTearDown(self): + self.mode_patch.stop() + await super().asyncTearDown() + + async def test_stream_upload_has_only_immutable_parts_and_one_final_put(self): + uid=await self.upload_all() + before=len(self.calls) + with patch('core.storage.tempfile.NamedTemporaryFile',side_effect=AssertionError('no local whole-file temporary')): + done=await self.complete(uid) + self.assertEqual(done.status_code,200,done.text) + self.assertEqual(list(self.files.values()),[self.payload]) + self.assertFalse(any(c[0]=='PATCH' for c in self.calls)) + puts=[c for c in self.calls[before:] if c[0]=='PUT'] + self.assertEqual(len(puts),1);self.assertEqual(puts[0][3],len(self.payload)) + + async def test_bad_remote_part_is_not_published(self): + uid=await self.upload_all() + part=next(k for k in self.files if k.endswith('/1.part')) + self.files[part]=b'XXXXXXXX' + done=await self.complete(uid);self.assertIn(done.status_code,(400,503)) + from apps.base.models import FileCodes + self.assertEqual(await FileCodes.all().count(),0) + await self.client.delete(f'/chunk/upload/{uid}');self.assertFalse(self.files) + + async def test_failed_part_put_retries_without_mutating_existing_cloud_object(self): + uid=await self.init();await self.chunk(uid,0) + from apps.base.models import UploadChunk + await UploadChunk.filter(upload_id=uid,chunk_index=0).delete() + self.assertEqual((await self.chunk(uid,0)).status_code,200) + self.assertFalse(any(c[0]=='PATCH' for c in self.calls))