Files
filecodebox/core/webdav_stream.py
T

96 lines
5.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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):
await self.clean_offset_upload(upload_id, save_path)