✨ feat: 整合 2.8.5 后端存储、安全与运行优化
* 禁用 OSS 非必需校验尾部,改用精确会话前缀逐对象清理 * 保护上传终态与分享事务,清理失败保留会话并支持安全重试 * 统一下载响应头,兼容旧下载器并防止文件名注入 * 限流改用单调时钟并限制 IP 记录,缓存模板与静态资源策略 * 统一 ORM 初始化与异常处理,新增查询索引及 SQLite 性能参数 * 固定 uvloop/httptools,统一 Docker keep-alive 与内存回收配置 * 同步版本与升级文档,补充 OSS、清理、缓存及数据库回归验证
This commit is contained in:
1 parent
b2a9aeddb3
commit
41519afb6a
29 files changed
+1033
-132
No files matched your search
+51
-31
@@ -1,3 +1,6 @@
|
||||
from core.logger import logger
|
||||
from tortoise.transactions import in_transaction
|
||||
from core.storage import build_attachment_headers
|
||||
import datetime
|
||||
import asyncio
|
||||
import hashlib
|
||||
@@ -301,7 +304,7 @@ async def build_download_response(file_code: FileCodes, file_storage: FileStorag
|
||||
return Response(
|
||||
content=file_code.text,
|
||||
media_type="text/plain",
|
||||
headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename, safe='')}"},
|
||||
headers=build_attachment_headers(filename),
|
||||
)
|
||||
if is_local_ref(file_code):
|
||||
return build_local_ref_download(file_code)
|
||||
@@ -471,6 +474,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
existing_session = await UploadChunk.filter(
|
||||
chunk_hash=data.file_hash,
|
||||
chunk_index=-1,
|
||||
completed=False,
|
||||
file_size=data.file_size,
|
||||
file_name=safe_file_name,
|
||||
).first()
|
||||
@@ -488,7 +492,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
"uploaded_chunks":list(range(existing_session.total_chunks)),"processing":True,
|
||||
})
|
||||
async with upload_lock(existing_session.upload_id):
|
||||
existing_session = await UploadChunk.filter(upload_id=existing_session.upload_id, chunk_index=-1).first()
|
||||
existing_session = await UploadChunk.filter(upload_id=existing_session.upload_id, chunk_index=-1, completed=False).first()
|
||||
if existing_session:
|
||||
if not existing_session.save_path:
|
||||
await UploadChunk.filter(upload_id=existing_session.upload_id).delete()
|
||||
@@ -504,7 +508,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
)
|
||||
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
|
||||
upload_id=existing_session.upload_id, completed=True, chunk_index__gte=0
|
||||
).values_list("chunk_index", flat=True)
|
||||
return APIResponse(
|
||||
detail={
|
||||
@@ -567,6 +571,8 @@ async def upload_chunk(
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if not chunk_info:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
|
||||
if chunk_info.completed:
|
||||
raise HTTPException(409, "上传会话已完成,仅待清理")
|
||||
await reserve_storage(
|
||||
f"chunk:{upload_id}",
|
||||
chunk_info.file_size,
|
||||
@@ -601,7 +607,7 @@ async def upload_chunk(
|
||||
|
||||
# 计算已上传分片数,校验累计大小不超限(用分片数 * chunk_size 估算)
|
||||
uploaded_count = await UploadChunk.filter(
|
||||
upload_id=upload_id, completed=True
|
||||
upload_id=upload_id, completed=True, chunk_index__gte=0
|
||||
).count()
|
||||
# 已上传分片的最大可能大小 + 当前分片
|
||||
max_uploaded_size = chunk_info.file_size
|
||||
@@ -714,9 +720,8 @@ async def _cancel_upload(upload_id):
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception as e:
|
||||
if chunk_info.storage_mode in {"webdav-offset", "webdav-stream", "clouddrive-native"}:
|
||||
raise
|
||||
pass
|
||||
logger.warning("取消上传清理失败,保留会话: %s", upload_id, exc_info=True)
|
||||
raise HTTPException(503, "分片清理失败,请稍后重试") from e
|
||||
|
||||
# 清理数据库记录
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
@@ -736,7 +741,7 @@ async def get_upload_status(upload_id: str):
|
||||
|
||||
# 获取已上传的分片列表
|
||||
uploaded_chunks = await UploadChunk.filter(
|
||||
upload_id=upload_id, completed=True
|
||||
upload_id=upload_id, completed=True, chunk_index__gte=0
|
||||
).values_list("chunk_index", flat=True)
|
||||
|
||||
return APIResponse(
|
||||
@@ -782,14 +787,20 @@ 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()
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, await published.get_file_path())
|
||||
except Exception:
|
||||
logger.warning("已发布上传清理失败,保留会话: %s", upload_id, exc_info=True)
|
||||
else:
|
||||
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()
|
||||
if not chunk_info:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
|
||||
if chunk_info.completed:
|
||||
raise HTTPException(409, "上传会话已完成,仅待清理")
|
||||
validate_expire_style(data.expire_style)
|
||||
await reserve_storage(
|
||||
f"chunk:{upload_id}",
|
||||
@@ -800,7 +811,7 @@ async def _complete_upload(upload_id, data, ip):
|
||||
storage = storages[settings.file_storage]()
|
||||
# 验证所有分片
|
||||
completed_chunks_list = await UploadChunk.filter(
|
||||
upload_id=upload_id, completed=True
|
||||
upload_id=upload_id, completed=True, chunk_index__gte=0
|
||||
).all()
|
||||
if len(completed_chunks_list) != chunk_info.total_chunks:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整")
|
||||
@@ -809,14 +820,17 @@ async def _complete_upload(upload_id, data, ip):
|
||||
max_total_size = chunk_info.file_size
|
||||
if max_total_size > settings.uploadSize:
|
||||
save_path = chunk_info.save_path
|
||||
cleanup_ok = True
|
||||
if save_path:
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception:
|
||||
if chunk_info.storage_mode in {"webdav-offset", "webdav-stream", "clouddrive-native"}:
|
||||
raise
|
||||
pass
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
cleanup_ok = False
|
||||
logger.warning("超限上传清理失败,保留会话: %s", upload_id, exc_info=True)
|
||||
if cleanup_ok:
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
@@ -835,25 +849,31 @@ async def _complete_upload(upload_id, data, ip):
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
data.expire_value, data.expire_style
|
||||
)
|
||||
file_code = await FileCodes.create(
|
||||
code=code,
|
||||
file_hash=file_hash, # 使用合并后计算的哈希
|
||||
is_chunked=True,
|
||||
upload_id=upload_id,
|
||||
size=chunk_info.file_size,
|
||||
expired_at=expired_at,
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
file_path=path,
|
||||
uuid_file_name=safe_file_name,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
)
|
||||
async with in_transaction() as connection:
|
||||
file_code = await FileCodes.create(
|
||||
using_db=connection,
|
||||
code=code,
|
||||
file_hash=file_hash, # 使用合并后计算的哈希
|
||||
is_chunked=True,
|
||||
upload_id=upload_id,
|
||||
size=chunk_info.file_size,
|
||||
expired_at=expired_at,
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
file_path=path,
|
||||
uuid_file_name=safe_file_name,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
)
|
||||
chunk_info.completed = True
|
||||
await chunk_info.save(using_db=connection, update_fields=["completed"])
|
||||
await record_transfer_stat("upload", file_code, chunk_info.file_size, ip)
|
||||
# 清理临时文件
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
# 清理数据库中的分片记录
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception:
|
||||
logger.warning("上传已发布,临时分片等待重试清理: %s", upload_id, exc_info=True)
|
||||
else:
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code, "name": safe_file_name})
|
||||
|
||||
Reference in new issue
Block a user