🔀 merge: 合并 WebDAV 无落盘合并与可靠续传
This commit is contained in:
commit
9a489297f4
12 files changed
+690
-53
No files matched your search
@@ -1 +1 @@
|
|||||||
e8c12af8348076125f6f0748c0c42bbfa63aae9f
|
da54bf40c9f3f7bb18ac5890b4e89e2a01724bd2
|
||||||
+21
@@ -89,3 +89,24 @@ docker build -f Dockerfile.upgrade \
|
|||||||
用户可先把服务器已有文件放入该目录,或自行将 NAS 挂载到容器 `/app/data/local`。
|
用户可先把服务器已有文件放入该目录,或自行将 NAS 挂载到容器 `/app/data/local`。
|
||||||
本次不迁移 WebDAV 文件、不新增宿主机目录挂载。分享期间应保持原文件路径可读;
|
本次不迁移 WebDAV 文件、不新增宿主机目录挂载。分享期间应保持原文件路径可读;
|
||||||
移动、删除或修改原件会影响下载。此页面没有删除原件操作,删除分享不会删除原件。
|
移动、删除或修改原件会影响下载。此页面没有删除原件操作,删除分享不会删除原件。
|
||||||
|
|
||||||
|
## WebDAV 偏移分片上传
|
||||||
|
|
||||||
|
新上传先通过 OPTIONS 检查 `sabredav-partialupdate`;支持时在远端创建单一
|
||||||
|
`chunks/<upload_id>/upload.bin` 暂存对象,首片使用条件 PUT,后续按明确
|
||||||
|
`X-Update-Range: bytes=start-end` PATCH。不使用实测异常的 `append`。
|
||||||
|
|
||||||
|
完成阶段流式读取远端对象,逐片验证 SHA-256、总长度并计算完整 SHA-256,
|
||||||
|
随后 WebDAV MOVE 发布到最终路径。不在 FileCodeBox 写完整临时文件,也不再
|
||||||
|
PUT 一次完整文件;仍会读取完整文件做校验。CloudDrive 的本地缓存/上传到网盘
|
||||||
|
由 CloudDrive 管理,不代表整个链路完全没有磁盘写入;HTTP 分片仍可能被框架缓冲。
|
||||||
|
|
||||||
|
`uploadchunk.storage_mode` 通过迁移 010 保存协议;旧会话及不支持偏移写入的
|
||||||
|
WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配额和定时清理。
|
||||||
|
同一上传写入/完成/清理在单 worker 内串行;取消期间禁止轮询重启,远端 MOVE
|
||||||
|
收尾后才能清理。完成接口返回 `code=202` 表示后台校验,前端每秒轮询;只有
|
||||||
|
校验及文件记录持久化完成才返回取件码,避免反代请求超时。进程退出会终止校验,
|
||||||
|
再次完成上传可从远端暂存对象重试;数据库及远端文件保留可恢复状态。
|
||||||
|
|
||||||
|
部署按新前端+后端同镜像进行。回滚旧镜像前应完成或取消新模式会话,旧代码
|
||||||
|
不认识偏移暂存对象;不得在活动新会话存在时直接恢复旧数据库。
|
||||||
@@ -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)
|
save_path = fields.CharField(max_length=512, null=True)
|
||||||
created_at = fields.DatetimeField(auto_now_add=True)
|
created_at = fields.DatetimeField(auto_now_add=True)
|
||||||
completed = fields.BooleanField(default=False)
|
completed = fields.BooleanField(default=False)
|
||||||
|
storage_mode = fields.CharField(max_length=32, default="legacy")
|
||||||
|
|
||||||
|
|
||||||
class TransferStats(models.Model):
|
class TransferStats(models.Model):
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from pydantic import BaseModel
|
from pydantic import BaseModel, Field
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
@@ -8,8 +8,8 @@ class SelectFileModel(BaseModel):
|
|||||||
|
|
||||||
class InitChunkUploadModel(BaseModel):
|
class InitChunkUploadModel(BaseModel):
|
||||||
file_name: str
|
file_name: str
|
||||||
chunk_size: int = 5 * 1024 * 1024
|
chunk_size: int = Field(default=5 * 1024 * 1024, gt=0)
|
||||||
file_size: int
|
file_size: int = Field(gt=0)
|
||||||
file_hash: str
|
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.admin.dependencies import share_required_login
|
||||||
from apps.base.models import FileCodes, UploadChunk, PresignUploadSession, TransferStats
|
from apps.base.models import FileCodes, UploadChunk, PresignUploadSession, TransferStats
|
||||||
from apps.base.quota import release_storage, reserve_storage
|
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 (
|
from apps.base.schemas import (
|
||||||
SelectFileModel,
|
SelectFileModel,
|
||||||
@@ -442,7 +443,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
|||||||
validate_file_type(safe_file_name)
|
validate_file_type(safe_file_name)
|
||||||
# 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量
|
# 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量
|
||||||
total_chunks = (data.file_size + data.chunk_size - 1) // data.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:
|
if max_possible_size > settings.uploadSize:
|
||||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
@@ -473,30 +474,41 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
|||||||
).first()
|
).first()
|
||||||
|
|
||||||
if existing_session:
|
if existing_session:
|
||||||
if not existing_session.save_path:
|
task = completion_task(existing_session.upload_id)
|
||||||
await UploadChunk.filter(upload_id=existing_session.upload_id).delete()
|
if task is not None and not task.done():
|
||||||
await release_storage(f"chunk:{existing_session.upload_id}")
|
return APIResponse(detail={
|
||||||
else:
|
"existed":False,"upload_id":existing_session.upload_id,
|
||||||
await reserve_storage(
|
"chunk_size":existing_session.chunk_size,"total_chunks":existing_session.total_chunks,
|
||||||
f"chunk:{existing_session.upload_id}",
|
"uploaded_chunks":list(range(existing_session.total_chunks)),"processing":True,
|
||||||
existing_session.file_size,
|
})
|
||||||
ttl_seconds=max(
|
async with upload_lock(existing_session.upload_id):
|
||||||
1, int(getattr(settings, "chunk_expire_hours", 24))
|
existing_session = await UploadChunk.filter(upload_id=existing_session.upload_id, chunk_index=-1).first()
|
||||||
)
|
if existing_session:
|
||||||
* 3600,
|
if not existing_session.save_path:
|
||||||
)
|
await UploadChunk.filter(upload_id=existing_session.upload_id).delete()
|
||||||
uploaded_chunks = await UploadChunk.filter(
|
await release_storage(f"chunk:{existing_session.upload_id}")
|
||||||
upload_id=existing_session.upload_id, completed=True
|
else:
|
||||||
).values_list("chunk_index", flat=True)
|
await reserve_storage(
|
||||||
return APIResponse(
|
f"chunk:{existing_session.upload_id}",
|
||||||
detail={
|
existing_session.file_size,
|
||||||
"existed": False,
|
ttl_seconds=max(
|
||||||
"upload_id": existing_session.upload_id,
|
1, int(getattr(settings, "chunk_expire_hours", 24))
|
||||||
"chunk_size": existing_session.chunk_size,
|
)
|
||||||
"total_chunks": existing_session.total_chunks,
|
* 3600,
|
||||||
"uploaded_chunks": list(uploaded_chunks),
|
)
|
||||||
}
|
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
|
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
|
data.file_name, upload_id
|
||||||
)
|
)
|
||||||
try:
|
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(
|
await UploadChunk.create(
|
||||||
upload_id=upload_id,
|
upload_id=upload_id,
|
||||||
|
storage_mode=storage_mode,
|
||||||
chunk_index=-1,
|
chunk_index=-1,
|
||||||
total_chunks=total_chunks,
|
total_chunks=total_chunks,
|
||||||
file_size=data.file_size,
|
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}",
|
"/upload/chunk/{upload_id}/{chunk_index}",
|
||||||
dependencies=[Depends(share_required_login)],
|
dependencies=[Depends(share_required_login)],
|
||||||
)
|
)
|
||||||
|
@serialize_upload
|
||||||
async def upload_chunk(
|
async def upload_chunk(
|
||||||
upload_id: str,
|
upload_id: str,
|
||||||
chunk_index: int,
|
chunk_index: int,
|
||||||
@@ -560,7 +579,7 @@ async def upload_chunk(
|
|||||||
existing_chunk = await UploadChunk.filter(
|
existing_chunk = await UploadChunk.filter(
|
||||||
upload_id=upload_id, chunk_index=chunk_index, completed=True
|
upload_id=upload_id, chunk_index=chunk_index, completed=True
|
||||||
).first()
|
).first()
|
||||||
if existing_chunk:
|
if existing_chunk and chunk_info.storage_mode != "webdav-offset":
|
||||||
return APIResponse(
|
return APIResponse(
|
||||||
detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True}
|
detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True}
|
||||||
)
|
)
|
||||||
@@ -583,7 +602,7 @@ async def upload_chunk(
|
|||||||
upload_id=upload_id, completed=True
|
upload_id=upload_id, completed=True
|
||||||
).count()
|
).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:
|
if max_uploaded_size > settings.uploadSize:
|
||||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
@@ -591,6 +610,15 @@ async def upload_chunk(
|
|||||||
)
|
)
|
||||||
|
|
||||||
chunk_hash = hashlib.sha256(chunk_data).hexdigest()
|
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
|
save_path = chunk_info.save_path
|
||||||
|
|
||||||
@@ -600,6 +628,8 @@ async def upload_chunk(
|
|||||||
await storage.save_chunk(
|
await storage.save_chunk(
|
||||||
upload_id, chunk_index, chunk_data, chunk_hash, save_path
|
upload_id, chunk_index, chunk_data, chunk_hash, save_path
|
||||||
)
|
)
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"分片保存失败: {str(e)}"
|
status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"分片保存失败: {str(e)}"
|
||||||
@@ -619,11 +649,24 @@ async def upload_chunk(
|
|||||||
"save_path": chunk_info.save_path,
|
"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})
|
return APIResponse(detail={"chunk_hash": chunk_hash})
|
||||||
|
|
||||||
|
|
||||||
@chunk_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
@chunk_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||||
async def cancel_upload(upload_id: str):
|
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()
|
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||||
if not chunk_info:
|
if not chunk_info:
|
||||||
@@ -637,6 +680,8 @@ async def cancel_upload(upload_id: str):
|
|||||||
try:
|
try:
|
||||||
await storage.clean_chunks(upload_id, save_path)
|
await storage.clean_chunks(upload_id, save_path)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
if chunk_info.storage_mode == "webdav-offset":
|
||||||
|
raise
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 清理数据库记录
|
# 清理数据库记录
|
||||||
@@ -681,6 +726,32 @@ async def complete_upload(
|
|||||||
data: CompleteUploadModel = Depends(parse_complete_upload),
|
data: CompleteUploadModel = Depends(parse_complete_upload),
|
||||||
ip: str = Depends(ip_limit["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()
|
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||||
if not chunk_info:
|
if not chunk_info:
|
||||||
@@ -701,13 +772,15 @@ async def complete_upload(
|
|||||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整")
|
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整")
|
||||||
|
|
||||||
# 用分片数 * chunk_size 校验最大可能大小
|
# 用分片数 * 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:
|
if max_total_size > settings.uploadSize:
|
||||||
save_path = chunk_info.save_path
|
save_path = chunk_info.save_path
|
||||||
if save_path:
|
if save_path:
|
||||||
try:
|
try:
|
||||||
await storage.clean_chunks(upload_id, save_path)
|
await storage.clean_chunks(upload_id, save_path)
|
||||||
except Exception:
|
except Exception:
|
||||||
|
if chunk_info.storage_mode == "webdav-offset":
|
||||||
|
raise
|
||||||
pass
|
pass
|
||||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||||
await release_storage(f"chunk:{upload_id}")
|
await release_storage(f"chunk:{upload_id}")
|
||||||
@@ -752,7 +825,11 @@ async def complete_upload(
|
|||||||
return APIResponse(detail={"code": code, "name": safe_file_name})
|
return APIResponse(detail={"code": code, "name": safe_file_name})
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=str(e))
|
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
if chunk_info.storage_mode == "webdav-offset":
|
||||||
|
raise HTTPException(500, "上传完成状态保存失败,请重试完成上传") from e
|
||||||
# 合并失败时清理临时文件
|
# 合并失败时清理临时文件
|
||||||
try:
|
try:
|
||||||
await storage.clean_chunks(upload_id, save_path)
|
await storage.clean_chunks(upload_id, save_path)
|
||||||
|
|||||||
+11
-1
@@ -1050,7 +1050,10 @@ class OpenDALFileStorage(FileStorageInterface):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
class WebDAVFileStorage(FileStorageInterface):
|
from core.webdav_chunks import WebDAVOffsetMixin
|
||||||
|
|
||||||
|
|
||||||
|
class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface):
|
||||||
_instance: Optional["WebDAVFileStorage"] = None
|
_instance: Optional["WebDAVFileStorage"] = None
|
||||||
|
|
||||||
def __init__(self):
|
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):
|
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
|
||||||
"""保存分片到 WebDAV"""
|
"""保存分片到 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_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||||
chunk_path = f"{chunk_dir}/{chunk_index}.part"
|
chunk_path = f"{chunk_dir}/{chunk_index}.part"
|
||||||
|
|
||||||
@@ -1276,6 +1282,8 @@ class WebDAVFileStorage(FileStorageInterface):
|
|||||||
合并 WebDAV 上的分片文件
|
合并 WebDAV 上的分片文件
|
||||||
使用临时文件避免内存问题
|
使用临时文件避免内存问题
|
||||||
"""
|
"""
|
||||||
|
if chunk_info.storage_mode == "webdav-offset":
|
||||||
|
return await self.finish_offset_upload(chunk_info, save_path)
|
||||||
file_sha256 = hashlib.sha256()
|
file_sha256 = hashlib.sha256()
|
||||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||||
|
|
||||||
@@ -1346,6 +1354,8 @@ class WebDAVFileStorage(FileStorageInterface):
|
|||||||
:param upload_id: 上传会话ID
|
:param upload_id: 上传会话ID
|
||||||
:param save_path: 文件保存路径
|
: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 = str(Path(save_path).parent / "chunks" / upload_id)
|
||||||
chunk_dir_url = self._build_url(chunk_dir)
|
chunk_dir_url = self._build_url(chunk_dir)
|
||||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
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.admin.services import FileService
|
||||||
from apps.base.utils import ip_limit, get_chunk_file_path_name
|
from apps.base.utils import ip_limit, get_chunk_file_path_name
|
||||||
from core.config import refresh_settings
|
from core.config import refresh_settings
|
||||||
|
from apps.base.upload_sessions import upload_lock
|
||||||
from core.logger import logger
|
from core.logger import logger
|
||||||
from apps.admin.trash_management import automatic_trash_reason
|
from apps.admin.trash_management import automatic_trash_reason
|
||||||
from core.settings import settings, data_root
|
from core.settings import settings, data_root
|
||||||
@@ -65,6 +66,19 @@ async def delete_expire_files():
|
|||||||
await asyncio.sleep(600)
|
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():
|
async def clean_incomplete_uploads():
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
@@ -79,27 +93,9 @@ async def clean_incomplete_uploads():
|
|||||||
|
|
||||||
for session in expired_sessions:
|
for session in expired_sessions:
|
||||||
try:
|
try:
|
||||||
save_path = session.save_path
|
await clean_expired_chunk_session(session.upload_id, expire_time)
|
||||||
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)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(
|
logger.error(f"清理分片失败,保留会话等待重试 upload_id={session.upload_id}: {e}")
|
||||||
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}"
|
|
||||||
)
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"清理未完成上传任务异常: {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 上传清理失败,请重试')
|
||||||
@@ -39,6 +39,7 @@ from core.tasks import (
|
|||||||
delete_expire_files,
|
delete_expire_files,
|
||||||
)
|
)
|
||||||
from core.version import APP_VERSION
|
from core.version import APP_VERSION
|
||||||
|
from apps.base.upload_sessions import shutdown_completions
|
||||||
|
|
||||||
|
|
||||||
def normalize_public_flag(value) -> int:
|
def normalize_public_flag(value) -> int:
|
||||||
@@ -750,6 +751,7 @@ async def lifespan(app: FastAPI):
|
|||||||
presign_cleanup_task,
|
presign_cleanup_task,
|
||||||
return_exceptions=True,
|
return_exceptions=True,
|
||||||
)
|
)
|
||||||
|
await shutdown_completions()
|
||||||
await Tortoise.close_connections()
|
await Tortoise.close_connections()
|
||||||
logger.info("应用已关闭")
|
logger.info("应用已关闭")
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,321 @@
|
|||||||
|
"""Real HTTP WebDAV fixture + FastAPI/SQLite journey; no customer storage."""
|
||||||
|
import asyncio
|
||||||
|
import hashlib
|
||||||
|
import unittest
|
||||||
|
from urllib.parse import urlsplit, unquote
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from aiohttp import web
|
||||||
|
from fastapi import FastAPI
|
||||||
|
|
||||||
|
from apps.base.views import chunk_api
|
||||||
|
from apps.base.models import FileCodes, UploadChunk, StorageReservation
|
||||||
|
from core.settings import settings
|
||||||
|
from tests.helpers import init_memory_db, close_db
|
||||||
|
|
||||||
|
|
||||||
|
class WebDAVOffsetTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
self.original = dict(settings.user_config)
|
||||||
|
await init_memory_db()
|
||||||
|
self.files = {}; self.calls = []; self.fail_patch = False; self.bad_offset = False; self.fail_delete = False; self.fail_move_reply = False
|
||||||
|
self.supported = True
|
||||||
|
self.block_get = None
|
||||||
|
app = web.Application(); app.router.add_route('*', '/{path:.*}', self.dav)
|
||||||
|
self.runner = web.AppRunner(app); 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 = {'file_storage':'webdav','webdav_url':f'http://127.0.0.1:{port}/dav',
|
||||||
|
'webdav_username':'test','webdav_password':'test','openUpload':1,'enableChunk':1,
|
||||||
|
'uploadSize':100,'storageLimit':100,'expireStyle':['day','count','forever']}
|
||||||
|
api = FastAPI(); api.include_router(chunk_api)
|
||||||
|
self.client = httpx.AsyncClient(transport=httpx.ASGITransport(app=api),base_url='http://test')
|
||||||
|
self.payload = b'abcdefghijklmnopqr'
|
||||||
|
|
||||||
|
async def asyncTearDown(self):
|
||||||
|
from apps.base.upload_sessions import shutdown_completions
|
||||||
|
await shutdown_completions()
|
||||||
|
await self.client.aclose(); await self.runner.cleanup()
|
||||||
|
settings.user_config = self.original
|
||||||
|
await close_db()
|
||||||
|
|
||||||
|
async def dav(self, request):
|
||||||
|
method,path=request.method,unquote(request.path)
|
||||||
|
body=await request.read(); self.calls.append((method,path,request.headers.get('X-Update-Range'),len(body)))
|
||||||
|
if method=='OPTIONS': return web.Response(headers={'DAV':'1,2,sabredav-partialupdate' if self.supported else '1,2'})
|
||||||
|
if method=='MKCOL': return web.Response(status=201)
|
||||||
|
if method=='HEAD': return web.Response(status=200,headers={'Content-Length':str(len(self.files[path]))}) if path in self.files else web.Response(status=404)
|
||||||
|
if method=='PUT':
|
||||||
|
if request.headers.get('If-None-Match')=='*' and path in self.files:return web.Response(status=412)
|
||||||
|
self.files[path]=body; return web.Response(status=201)
|
||||||
|
if method=='PATCH':
|
||||||
|
if self.fail_patch:self.fail_patch=False;return web.Response(status=503)
|
||||||
|
if path not in self.files:return web.Response(status=404)
|
||||||
|
start,end=map(int,request.headers['X-Update-Range'].removeprefix('bytes=').split('-'))
|
||||||
|
if self.bad_offset:start=0
|
||||||
|
data=bytearray(self.files[path]); data.extend(b'\0'*max(0,start+len(body)-len(data)));data[start:start+len(body)]=body
|
||||||
|
self.files[path]=bytes(data);return web.Response(status=204)
|
||||||
|
if method=='GET':
|
||||||
|
if self.block_get is not None: await self.block_get.wait()
|
||||||
|
return web.Response(body=self.files[path]) if path in self.files else web.Response(status=404)
|
||||||
|
if method=='MOVE':
|
||||||
|
if hasattr(self,'move_started'):
|
||||||
|
self.move_started.set();await self.allow_move.wait()
|
||||||
|
dest=unquote(urlsplit(request.headers['Destination']).path)
|
||||||
|
if path not in self.files:return web.Response(status=404)
|
||||||
|
if dest in self.files:return web.Response(status=412)
|
||||||
|
self.files[dest]=self.files.pop(path)
|
||||||
|
if self.fail_move_reply:self.fail_move_reply=False;return web.Response(status=503)
|
||||||
|
return web.Response(status=201)
|
||||||
|
if method=='DELETE':
|
||||||
|
if self.fail_delete:return web.Response(status=503)
|
||||||
|
for key in list(self.files):
|
||||||
|
if key==path or key.startswith(path.rstrip('/')+'/'):self.files.pop(key)
|
||||||
|
return web.Response(status=204)
|
||||||
|
if method=='PROPFIND':return web.Response(status=404)
|
||||||
|
return web.Response(status=405)
|
||||||
|
|
||||||
|
async def init(self):
|
||||||
|
response=await self.client.post('/chunk/upload/init/',json={'file_name':'sample.txt','file_size':len(self.payload),'chunk_size':8,'file_hash':hashlib.md5(self.payload).hexdigest()})
|
||||||
|
self.assertEqual(response.status_code,200,response.text)
|
||||||
|
return response.json()['detail']['upload_id']
|
||||||
|
|
||||||
|
async def chunk(self,uid,index,data=None):
|
||||||
|
return await self.client.post(f'/chunk/upload/chunk/{uid}/{index}',files={'chunk':('sample.txt',data if data is not None else self.payload[index*8:(index+1)*8])})
|
||||||
|
|
||||||
|
async def complete(self,uid):
|
||||||
|
for _ in range(100):
|
||||||
|
r = await self.client.post(f'/chunk/upload/complete/{uid}',json={'expire_value':1,'expire_style':'day'})
|
||||||
|
if r.status_code != 200 or r.json().get('code') != 202: return r
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
self.fail('verification did not finish')
|
||||||
|
|
||||||
|
async def upload_all(self):
|
||||||
|
uid=await self.init()
|
||||||
|
for i in range(3):self.assertEqual((await self.chunk(uid,i)).status_code,200)
|
||||||
|
return uid
|
||||||
|
|
||||||
|
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')
|
||||||
|
self.assertEqual((await self.chunk(uid,0)).status_code,200)
|
||||||
|
self.fail_patch=True
|
||||||
|
self.assertEqual((await self.chunk(uid,1)).status_code,503)
|
||||||
|
self.assertFalse(await UploadChunk.filter(upload_id=uid,chunk_index=1).exists())
|
||||||
|
self.assertEqual(await self.init(),uid)
|
||||||
|
self.assertEqual((await self.client.get(f'/chunk/upload/status/{uid}')).json()['detail']['uploaded_chunks'],[0])
|
||||||
|
self.assertEqual((await self.chunk(uid,1)).status_code,200)
|
||||||
|
self.assertEqual((await self.chunk(uid,1)).status_code,200)
|
||||||
|
self.assertEqual((await self.chunk(uid,2)).status_code,200)
|
||||||
|
before=list(self.calls)
|
||||||
|
with patch('core.storage.tempfile.NamedTemporaryFile',side_effect=AssertionError('full file local spooling forbidden')):
|
||||||
|
done=await self.complete(uid)
|
||||||
|
self.assertEqual(done.status_code,200,done.text)
|
||||||
|
record=await FileCodes.get(code=done.json()['detail']['code'])
|
||||||
|
self.assertEqual(record.file_hash,hashlib.sha256(self.payload).hexdigest())
|
||||||
|
self.assertEqual(list(self.files.values()),[self.payload])
|
||||||
|
self.assertEqual([c[2] for c in before if c[0]=='PATCH'],['bytes=8-15','bytes=8-15','bytes=16-17'])
|
||||||
|
self.assertFalse(any(c[0] in ['PUT','PATCH'] for c in self.calls[len(before):]))
|
||||||
|
self.assertFalse(await UploadChunk.filter(upload_id=uid).exists())
|
||||||
|
self.assertFalse(await StorageReservation.filter(token=f'chunk:{uid}').exists())
|
||||||
|
again=await self.complete(uid)
|
||||||
|
self.assertEqual(again.json()['detail']['code'],record.code)
|
||||||
|
await self.client.delete(f'/chunk/upload/{uid}')
|
||||||
|
self.assertEqual(list(self.files.values()),[self.payload])
|
||||||
|
|
||||||
|
async def test_corruption_is_rejected_without_publishing(self):
|
||||||
|
self.bad_offset=True
|
||||||
|
uid=await self.upload_all();response=await self.complete(uid)
|
||||||
|
self.assertEqual(response.status_code,400,response.text)
|
||||||
|
self.assertEqual(await FileCodes.all().count(),0)
|
||||||
|
self.assertTrue(await UploadChunk.filter(upload_id=uid).exists())
|
||||||
|
self.assertEqual((await self.client.delete(f'/chunk/upload/{uid}')).status_code,200)
|
||||||
|
self.assertFalse(self.files)
|
||||||
|
|
||||||
|
async def test_missing_short_or_out_of_order_chunks_rejected(self):
|
||||||
|
uid=await self.init()
|
||||||
|
self.assertEqual((await self.chunk(uid,1)).status_code,409)
|
||||||
|
self.assertEqual((await self.chunk(uid,0,b'a')).status_code,400)
|
||||||
|
self.assertFalse(self.files)
|
||||||
|
self.assertEqual((await self.chunk(uid,0)).status_code,200)
|
||||||
|
self.assertEqual((await self.complete(uid)).status_code,400)
|
||||||
|
self.assertEqual((await self.client.delete(f'/chunk/upload/{uid}')).status_code,200)
|
||||||
|
self.assertFalse(self.files)
|
||||||
|
|
||||||
|
async def test_completed_chunk_retry_with_changed_bytes_is_rejected(self):
|
||||||
|
uid=await self.init();await self.chunk(uid,0)
|
||||||
|
self.assertEqual((await self.chunk(uid,0,b'XXXXXXXX')).status_code,409)
|
||||||
|
|
||||||
|
async def test_failed_cleanup_keeps_session_and_reservation_for_retry(self):
|
||||||
|
uid=await self.init();await self.chunk(uid,0);self.fail_delete=True
|
||||||
|
response=await self.client.delete(f'/chunk/upload/{uid}')
|
||||||
|
self.assertEqual(response.status_code,503,response.text)
|
||||||
|
self.assertTrue(await UploadChunk.filter(upload_id=uid).exists())
|
||||||
|
self.assertTrue(await StorageReservation.filter(token=f'chunk:{uid}').exists())
|
||||||
|
self.fail_delete=False;self.assertEqual((await self.client.delete(f'/chunk/upload/{uid}')).status_code,200)
|
||||||
|
self.assertFalse(self.files)
|
||||||
|
|
||||||
|
async def test_move_response_loss_recovers_without_uploading_file_again(self):
|
||||||
|
uid=await self.upload_all();self.fail_move_reply=True
|
||||||
|
first=await self.complete(uid);self.assertEqual(first.status_code,503,first.text)
|
||||||
|
self.assertEqual(list(self.files.values()),[self.payload])
|
||||||
|
second=await self.complete(uid);self.assertEqual(second.status_code,200,second.text)
|
||||||
|
self.assertEqual(await FileCodes.all().count(),1)
|
||||||
|
|
||||||
|
async def test_non_partial_webdav_keeps_legacy_upload_protocol(self):
|
||||||
|
self.supported=False;uid=await self.init()
|
||||||
|
self.assertEqual((await UploadChunk.get(upload_id=uid,chunk_index=-1)).storage_mode,'legacy')
|
||||||
|
self.assertEqual((await self.chunk(uid,0)).status_code,200)
|
||||||
|
self.assertTrue(any(c[0]=='PUT' and c[1].endswith('0.part') for c in self.calls))
|
||||||
|
|
||||||
|
async def test_concurrent_duplicate_completion_publishes_one_record(self):
|
||||||
|
uid=await self.upload_all()
|
||||||
|
first,second=await asyncio.gather(self.complete(uid),self.complete(uid))
|
||||||
|
self.assertEqual(first.status_code,200,first.text);self.assertEqual(second.status_code,200,second.text)
|
||||||
|
self.assertEqual(first.json()['detail']['code'],second.json()['detail']['code'])
|
||||||
|
self.assertEqual(await FileCodes.all().count(),1)
|
||||||
|
|
||||||
|
async def test_remote_write_succeeded_but_database_ack_lost_retries_same_offset(self):
|
||||||
|
uid=await self.init()
|
||||||
|
await self.chunk(uid,0);await self.chunk(uid,1)
|
||||||
|
await UploadChunk.filter(upload_id=uid,chunk_index=1).delete()
|
||||||
|
self.assertEqual((await self.chunk(uid,1)).status_code,200)
|
||||||
|
await self.chunk(uid,2)
|
||||||
|
done=await self.complete(uid);self.assertEqual(done.status_code,200,done.text)
|
||||||
|
self.assertEqual(list(self.files.values()),[self.payload])
|
||||||
|
|
||||||
|
async def test_final_partial_chunk_can_fill_quota_exactly(self):
|
||||||
|
settings.uploadSize=len(self.payload);settings.storageLimit=len(self.payload)
|
||||||
|
uid=await self.upload_all();done=await self.complete(uid)
|
||||||
|
self.assertEqual(done.status_code,200,done.text)
|
||||||
|
|
||||||
|
async def test_expired_cleanup_retries_and_keeps_published_object(self):
|
||||||
|
import datetime
|
||||||
|
from core.tasks import clean_expired_chunk_session
|
||||||
|
from core.utils import get_now
|
||||||
|
uid=await self.init();await self.chunk(uid,0)
|
||||||
|
cutoff=await get_now()-datetime.timedelta(hours=24)
|
||||||
|
await UploadChunk.filter(upload_id=uid,chunk_index=-1).update(created_at=cutoff-datetime.timedelta(seconds=1))
|
||||||
|
self.fail_delete=True
|
||||||
|
with self.assertRaises(Exception):await clean_expired_chunk_session(uid,cutoff)
|
||||||
|
self.assertTrue(await UploadChunk.filter(upload_id=uid).exists())
|
||||||
|
self.fail_delete=False
|
||||||
|
await clean_expired_chunk_session(uid,cutoff)
|
||||||
|
self.assertFalse(await UploadChunk.filter(upload_id=uid).exists());self.assertFalse(self.files)
|
||||||
|
|
||||||
|
async def test_migration_preserves_legacy_session_and_is_repeatable(self):
|
||||||
|
from tortoise import connections
|
||||||
|
from apps.base.migrations.migrations_010_webdav_offset_upload import migrate
|
||||||
|
self.supported=False;uid=await self.init()
|
||||||
|
conn=connections.get('default')
|
||||||
|
await conn.execute_script('ALTER TABLE uploadchunk DROP COLUMN storage_mode;')
|
||||||
|
await migrate();await migrate()
|
||||||
|
self.assertEqual((await UploadChunk.get(upload_id=uid,chunk_index=-1)).storage_mode,'legacy')
|
||||||
|
|
||||||
|
async def test_completion_returns_processing_without_waiting_for_remote_read(self):
|
||||||
|
uid=await self.upload_all();self.block_get=asyncio.Event()
|
||||||
|
try:
|
||||||
|
response=await asyncio.wait_for(self.client.post(f'/chunk/upload/complete/{uid}',json={'expire_value':1,'expire_style':'day'}),0.3)
|
||||||
|
self.assertEqual(response.json()['code'],202)
|
||||||
|
self.assertEqual(await FileCodes.all().count(),0)
|
||||||
|
finally:self.block_get.set()
|
||||||
|
done=await self.complete(uid);self.assertEqual(done.status_code,200,done.text)
|
||||||
|
|
||||||
|
async def test_cancel_during_verification_removes_only_unpublished_staging(self):
|
||||||
|
uid=await self.upload_all();self.block_get=asyncio.Event()
|
||||||
|
pending=await self.client.post(f'/chunk/upload/complete/{uid}',json={'expire_value':1,'expire_style':'day'})
|
||||||
|
self.assertEqual(pending.json()['code'],202)
|
||||||
|
await asyncio.sleep(0.03)
|
||||||
|
try:
|
||||||
|
cancel=await asyncio.wait_for(self.client.delete(f'/chunk/upload/{uid}'),1)
|
||||||
|
self.assertEqual(cancel.status_code,200,cancel.text)
|
||||||
|
self.assertFalse(self.files);self.assertEqual(await FileCodes.all().count(),0)
|
||||||
|
self.assertFalse(await UploadChunk.filter(upload_id=uid).exists())
|
||||||
|
finally:self.block_get.set()
|
||||||
|
|
||||||
|
async def test_old_partial_session_uses_legacy_protocol_after_upgrade(self):
|
||||||
|
self.supported=False;uid=await self.init();await self.chunk(uid,0)
|
||||||
|
self.supported=True;self.assertEqual(await self.init(),uid)
|
||||||
|
await self.chunk(uid,1)
|
||||||
|
self.assertFalse(any(c[0]=='PATCH' for c in self.calls))
|
||||||
|
self.assertTrue(any(c[1].endswith('1.part') for c in self.calls))
|
||||||
|
|
||||||
|
async def test_legacy_limit_is_rejected_before_transferring_any_content(self):
|
||||||
|
self.supported=False;settings.uploadSize=len(self.payload)
|
||||||
|
response=await self.client.post('/chunk/upload/init/',json={'file_name':'sample.txt','file_size':len(self.payload),'chunk_size':8,'file_hash':hashlib.md5(self.payload).hexdigest()})
|
||||||
|
self.assertEqual(response.status_code,403)
|
||||||
|
self.assertEqual(await StorageReservation.all().count(),0)
|
||||||
|
self.assertEqual(await UploadChunk.all().count(),0)
|
||||||
|
self.assertFalse(self.files)
|
||||||
|
|
||||||
|
async def test_init_waiting_for_cancel_returns_a_new_live_session(self):
|
||||||
|
from apps.base.upload_sessions import upload_lock
|
||||||
|
from apps.base import views
|
||||||
|
uid=await self.init()
|
||||||
|
reached=asyncio.Event();original=views.upload_lock
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
@asynccontextmanager
|
||||||
|
async def tracked(upload_id):
|
||||||
|
reached.set()
|
||||||
|
async with original(upload_id):yield
|
||||||
|
async with upload_lock(uid):
|
||||||
|
with patch('apps.base.views.upload_lock',tracked):
|
||||||
|
pending=asyncio.create_task(self.init())
|
||||||
|
await asyncio.wait_for(reached.wait(),1)
|
||||||
|
await UploadChunk.filter(upload_id=uid).delete()
|
||||||
|
await StorageReservation.filter(token=f'chunk:{uid}').delete()
|
||||||
|
replacement=await pending
|
||||||
|
self.assertNotEqual(replacement,uid)
|
||||||
|
self.assertTrue(await UploadChunk.filter(upload_id=replacement).exists())
|
||||||
|
self.assertFalse(await StorageReservation.filter(token=f'chunk:{uid}').exists())
|
||||||
|
|
||||||
|
async def test_resume_init_is_responsive_while_completion_reads_remote_file(self):
|
||||||
|
uid=await self.upload_all();self.block_get=asyncio.Event()
|
||||||
|
await self.client.post(f'/chunk/upload/complete/{uid}',json={'expire_value':1,'expire_style':'day'})
|
||||||
|
await asyncio.sleep(0.03)
|
||||||
|
try:self.assertEqual(await asyncio.wait_for(self.init(),0.3),uid)
|
||||||
|
finally:self.block_get.set()
|
||||||
|
self.assertEqual((await self.complete(uid)).status_code,200)
|
||||||
|
|
||||||
|
async def test_reduced_limit_cleanup_failure_preserves_retry_state(self):
|
||||||
|
uid=await self.upload_all();settings.uploadSize=17;self.fail_delete=True
|
||||||
|
response=await self.complete(uid)
|
||||||
|
self.assertEqual(response.status_code,503,response.text)
|
||||||
|
self.assertTrue(await UploadChunk.filter(upload_id=uid).exists())
|
||||||
|
self.assertTrue(await StorageReservation.filter(token=f'chunk:{uid}').exists())
|
||||||
|
self.fail_delete=False
|
||||||
|
self.assertEqual((await self.client.delete(f'/chunk/upload/{uid}')).status_code,200)
|
||||||
|
|
||||||
|
async def test_polling_cannot_restart_completion_while_cancel_is_running(self):
|
||||||
|
from apps.base import views
|
||||||
|
uid=await self.upload_all();self.block_get=asyncio.Event()
|
||||||
|
await self.client.post(f'/chunk/upload/complete/{uid}',json={'expire_value':1,'expire_style':'day'})
|
||||||
|
started=asyncio.Event();release=asyncio.Event();original=views.cancel_completion
|
||||||
|
async def pause_cancel(upload_id):
|
||||||
|
await original(upload_id);started.set();await release.wait()
|
||||||
|
with patch('apps.base.views.cancel_completion',pause_cancel):
|
||||||
|
cancel=asyncio.create_task(self.client.delete(f'/chunk/upload/{uid}'))
|
||||||
|
await asyncio.wait_for(started.wait(),1)
|
||||||
|
poll=await self.client.post(f'/chunk/upload/complete/{uid}',json={'expire_value':1,'expire_style':'day'})
|
||||||
|
self.assertEqual(poll.status_code,409)
|
||||||
|
release.set();self.assertEqual((await cancel).status_code,200)
|
||||||
|
self.block_get.set();self.assertFalse(self.files);self.assertEqual(await FileCodes.all().count(),0)
|
||||||
|
|
||||||
|
async def test_cancel_waits_for_remote_move_before_removing_final_file(self):
|
||||||
|
uid=await self.upload_all()
|
||||||
|
self.move_started=asyncio.Event();self.allow_move=asyncio.Event()
|
||||||
|
await self.client.post(f'/chunk/upload/complete/{uid}',json={'expire_value':1,'expire_style':'day'})
|
||||||
|
await asyncio.wait_for(self.move_started.wait(),1)
|
||||||
|
cancel=asyncio.create_task(self.client.delete(f'/chunk/upload/{uid}'))
|
||||||
|
await asyncio.sleep(0.05);self.assertFalse(cancel.done())
|
||||||
|
self.allow_move.set();response=await cancel
|
||||||
|
self.assertEqual(response.status_code,200,response.text)
|
||||||
|
self.assertFalse(self.files);self.assertEqual(await FileCodes.all().count(),0)
|
||||||
|
|
||||||
|
async def test_client_resume_fingerprint_is_not_treated_as_whole_file_hash(self):
|
||||||
|
uid=await self.upload_all()
|
||||||
|
await UploadChunk.filter(upload_id=uid,chunk_index=-1).update(chunk_hash='0'*64)
|
||||||
|
done=await self.complete(uid)
|
||||||
|
self.assertEqual(done.status_code,200,done.text)
|
||||||
|
self.assertEqual((await FileCodes.get(code=done.json()['detail']['code'])).file_hash,hashlib.sha256(self.payload).hexdigest())
|
||||||
Reference in new issue
Block a user