🐛 fix: 合并上传收尾恢复修复并固定正式前端
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s
Create release / release-please (push) Canceled after 0s
Build and push Docker image / buildx (push) Canceled after 0s

* 校验传输中断时有限重试并复用已经合并的完整文件
* 保留损坏文件重建及完整哈希校验,补充恢复场景测试
* 固定正式前端并记录测试站上传下载和浏览器验证
This commit is contained in:
orion committed 2026-10-06 02:07:15 +08:00
commit 2ba7bace02
4 files changed
+103 -3

No files matched your search

+1 -1
View File
@@ -1 +1 @@
6a872fa8b0229b44e2a5b02393e9af01b18d268f
b67d36d8a0d1f337983b5fba2eb45bde7ab7200a
+22
View File
@@ -287,3 +287,25 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配
- 修复 f7bae99 先推送测试分支,再构建部署测试站,浏览器复验空文件选择/拖拽零请求、非空上传正常。
前端正式 main 合并为 6a872fa8b0229b44e2a5b02393e9af01b18d268f,生产从正式提交独立构建。
测试升级备份:/root/backups/filecodebox-test-upload-20261006-005513。
## 上传收尾重试修复(2026-10-06)
- 公网 WebDAV 对 312.55 MiB 合并 PUT 返回 413;生产已备份配置并切换到
同 Docker 网络内的 CloudDrive DAV,避免大文件绕公网代理。
- 完整校验读取遇到传输中断时最多重试三次;持续失败保留合并对象,
下次完成上传先验证已有对象,成功后发布,避免再次读取所有分片并 PUT。
损坏或不完整的合并对象仍会重建;逐分片与完整文件 SHA-256 校验保持不变。
- 前端完成轮询不再因 202 重置失败次数,避免 202/503 交替导致无限重试。
- 前端 79 项测试、覆盖率检查、类型/架构检查与构建通过;
后端 177 项单元及 HTTP DAV/FastAPI 集成测试通过,总覆盖率 62%,
流式上传模块覆盖率 86%。Node 原生覆盖率不计 Vite SSR 动态加载模块。
- 现有 BNApp64.apk 合并对象曾完整读取并核对本地 SHA-256 一致;
发布与生产恢复结果另以部署验收记录为准。
- 测试站真实 4 MiB+9 字节三分片上传、合并、取件下载 SHA-256 一致,
临时文件已回收并彻底清理;完成到下载耗时 0.62 秒,仅代表此次小文件验收。
- 浏览器模拟 202/503 交替响应,第四次失败后停止轮询,不产生无限重试。
- 测试站也切换到同 Docker 网络内 CloudDrive DAV,配置及数据库备份
`/root/backups/filecodebox-test-upload-20261006-020407`。
- 正式前端合并提交 `b67d36d8a0d1f337983b5fba2eb45bde7ab7200a`;
后端合入 master 并推送后独立构建正式镜像,不复用测试镜像标签。
+25 -2
View File
@@ -45,6 +45,17 @@ class WebDAVStreamMixin:
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 _verify_stream_file(self, client, path, info, records):
# Cloud-backed reads can disconnect while the object is synchronizing.
# Retry only transport failures, retaining the assembled object.
for attempt in range(3):
try:
return await self._verify_offset_file(client, path, info, records)
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
if attempt == 2:
raise HTTPException(503, 'WebDAV 校验读取中断,已保留合并文件,请重试完成上传') from exc
await asyncio.sleep(attempt + 1)
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('分片不完整')
@@ -52,8 +63,20 @@ class WebDAVStreamMixin:
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)
digest=await self._verify_stream_file(client,save_path,info,records)
if digest is not None:return save_path,digest
try:
digest=await self._verify_stream_file(client,staging,info,records)
except ValueError:
# An interrupted PUT may leave a partial/corrupt staging object.
digest=None
if digest is not None:
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 with client.delete(self._build_url(staging)) as response:
if response.status not in (200,204,404):raise HTTPException(503,'WebDAV 合并临时文件清理失败')
verified=0
@@ -82,7 +105,7 @@ class WebDAVStreamMixin:
await task
raise
if verified!=len(records):raise ValueError('分片校验未完成,请重新上传')
digest=await self._verify_offset_file(client,staging,info,records)
digest=await self._verify_stream_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)
+55
View File
@@ -1,6 +1,7 @@
"""Independent immutable DAV parts; one streaming assembly, never PATCH/tempfile."""
import hashlib
from unittest.mock import patch
from urllib.parse import unquote, urlsplit
from tests.test_webdav_offset_upload import WebDAVFixture
@@ -106,3 +107,57 @@ class WebDAVStreamTests(WebDAVFixture):
await clean_expired_presign_session('published-stale',now)
self.assertEqual(self.files['/dav/old.txt'],b'keep')
self.assertFalse(await PresignUploadSession.filter(upload_id='published-stale').exists())
async def test_transient_staging_read_failure_retries_without_reassembling(self):
import aiohttp
from core.storage import WebDAVFileStorage
original=WebDAVFileStorage._verify_offset_file
reads=0
async def flaky(storage,client,path,info,records):
nonlocal reads
if path.endswith('assembled.bin') and unquote(urlsplit(storage._build_url(path)).path) in self.files:
reads+=1
if reads==1:raise aiohttp.ClientPayloadError('truncated response')
return await original(storage,client,path,info,records)
uid=await self.upload_all();before=len(self.calls)
from apps.base.views import _complete_upload
from apps.base.schemas import CompleteUploadModel
with patch.object(WebDAVFileStorage,'_verify_offset_file',flaky):
done=await _complete_upload(uid,CompleteUploadModel(expire_value=1,expire_style='day'),'127.0.0.1')
self.assertEqual(done.code,200)
self.assertEqual(reads,2)
self.assertEqual(len([c for c in self.calls[before:] if c[0]=='PUT']),1)
from apps.base.models import FileCodes
record=await FileCodes.get(code=done.detail['code'])
self.assertEqual(record.file_hash,hashlib.sha256(self.payload).hexdigest())
async def test_persistent_read_failure_preserves_staging_for_manual_retry(self):
import aiohttp
from core.storage import WebDAVFileStorage
original=WebDAVFileStorage._verify_offset_file
async def disconnected(storage,client,path,info,records):
if path.endswith('assembled.bin') and unquote(urlsplit(storage._build_url(path)).path) in self.files:
raise aiohttp.ClientPayloadError('truncated response')
return await original(storage,client,path,info,records)
uid=await self.upload_all()
with patch.object(WebDAVFileStorage,'_verify_offset_file',disconnected):
# Bypass fixture's one-second polling deadline for bounded I/O retries.
from apps.base.views import _complete_upload
from apps.base.schemas import CompleteUploadModel
from fastapi import HTTPException
with self.assertRaises(HTTPException) as raised:
await _complete_upload(uid,CompleteUploadModel(expire_value=1,expire_style='day'),'127.0.0.1')
self.assertEqual(raised.exception.status_code,503)
self.assertTrue(any(k.endswith('assembled.bin') for k in self.files))
before=len(self.calls);done=await self.complete(uid)
self.assertEqual(done.status_code,200,done.text)
self.assertFalse(any(c[0] in ('PUT','DELETE') and c[1].endswith('assembled.bin') for c in self.calls[before:]))
self.assertEqual(list(self.files.values()),[self.payload])
async def test_corrupt_existing_staging_is_rebuilt_and_fully_verified(self):
uid=await self.upload_all()
part=next(k for k in self.files if k.endswith('/0.part'))
self.files[part.rsplit('/',1)[0]+'/assembled.bin']=b'broken'
done=await self.complete(uid)
self.assertEqual(done.status_code,200,done.text)
self.assertEqual(list(self.files.values()),[self.payload])