🔧 chore: 同步完整后端运行模块

This commit is contained in:
orion committed 2026-09-11 17:13:03 +08:00
1 parent d104b9fc8b
commit 2d44699eec
20 files changed
+1465 -235

No files matched your search

+103 -86
View File
@@ -25,6 +25,7 @@ from core.settings import data_root, settings
from apps.base.models import FileCodes, UploadChunk
from core.utils import get_file_url, sanitize_filename
from fastapi.responses import FileResponse, StreamingResponse
from starlette.background import BackgroundTask
class FileStorageInterface:
@@ -115,6 +116,19 @@ class SystemFileStorage(FileStorageInterface):
self.chunk_size = 256 * 1024
self.root_path = data_root
def _resolve_safe_path(self, relative_path: str) -> Path:
"""将相对路径解析到数据根目录内,阻止路径穿越。"""
root = self.root_path.resolve()
raw = str(relative_path or "").replace("\\", "/").lstrip("/")
if any(part == ".." for part in raw.split("/")):
raise ValueError("非法文件路径")
candidate = (root / raw).resolve()
try:
candidate.relative_to(root)
except ValueError as exc:
raise ValueError("非法文件路径") from exc
return candidate
def _save(self, file, save_path):
with open(save_path, "wb") as f:
chunk = file.read(self.chunk_size)
@@ -123,19 +137,19 @@ class SystemFileStorage(FileStorageInterface):
chunk = file.read(self.chunk_size)
async def save_file(self, file: UploadFile, save_path: str):
path_obj = Path(save_path)
directory = str(path_obj.parent)
path_obj = Path(str(save_path).replace("\\", "/"))
directory = str(path_obj.parent).replace("\\", "/").lstrip("/")
# 提取原始文件名并进行清理
filename = await sanitize_filename(path_obj.name)
# 构建安全的完整保存路径
safe_save_path = self.root_path / directory / filename
safe_save_path = self._resolve_safe_path(f"{directory}/{filename}" if directory not in {"", "."} else filename)
# 确保目录存在
if not safe_save_path.parent.exists():
safe_save_path.parent.mkdir(parents=True)
await asyncio.to_thread(self._save, file.file, safe_save_path)
async def delete_file(self, file_code: FileCodes):
save_path = self.root_path / await file_code.get_file_path()
save_path = self._resolve_safe_path(await file_code.get_file_path())
if save_path.exists():
save_path.unlink()
@@ -151,7 +165,7 @@ class SystemFileStorage(FileStorageInterface):
return await get_file_url(file_code.code)
async def get_file_response(self, file_code: FileCodes):
file_path = self.root_path / await file_code.get_file_path()
file_path = self._resolve_safe_path(await file_code.get_file_path())
if not file_path.exists():
return APIResponse(code=404, detail="文件已过期删除")
filename = f"{file_code.prefix}{file_code.suffix}"
@@ -183,8 +197,11 @@ class SystemFileStorage(FileStorageInterface):
:param chunk_hash: 分片哈希值
:param save_path: 文件保存路径
"""
chunk_dir = self.root_path / save_path
chunk_path = chunk_dir.parent / 'chunks' / upload_id / f"{chunk_index}.part"
# 先校验目标文件路径合法,再将分片落到同级 chunks 目录。
self._resolve_safe_path(save_path)
chunk_path = self._resolve_safe_path(
str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
)
if not chunk_path.parent.exists():
chunk_path.parent.mkdir(parents=True, exist_ok=True)
# 使用临时文件写入,确保原子性
@@ -207,9 +224,11 @@ class SystemFileStorage(FileStorageInterface):
:param save_path: 文件保存路径
:return: (文件路径, 文件哈希值)
"""
output_path = self.root_path / save_path
output_path = self._resolve_safe_path(save_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
chunk_base_dir = output_path.parent / 'chunks' / upload_id
chunk_base_dir = self._resolve_safe_path(
str(Path(save_path).parent / "chunks" / upload_id)
)
file_sha256 = hashlib.sha256()
# 使用临时文件写入,确保原子性
@@ -245,19 +264,21 @@ class SystemFileStorage(FileStorageInterface):
:param upload_id: 上传会话ID
:param save_path: 文件保存路径
"""
chunk_dir = (self.root_path / save_path).parent / 'chunks' / upload_id
chunk_dir = self._resolve_safe_path(
str(Path(save_path).parent / "chunks" / upload_id)
)
if chunk_dir.exists():
try:
shutil.rmtree(chunk_dir)
except Exception as e:
logger.info(f"清理本地分片目录失败: {e}")
logger.warning(f"清理本地分片目录失败: {e}")
# 清理父级 chunks 目录(如果为空)
chunks_parent = chunk_dir.parent
if chunks_parent.exists() and not any(chunks_parent.iterdir()):
try:
chunks_parent.rmdir()
except Exception as e:
logger.info(f"清理 chunks 父目录失败: {e}")
logger.warning(f"清理 chunks 父目录失败: {e}")
async def file_exists(self, save_path: str) -> bool:
"""
@@ -265,7 +286,10 @@ class SystemFileStorage(FileStorageInterface):
:param save_path: 文件路径
:return: 文件是否存在
"""
file_path = self.root_path / save_path
try:
file_path = self._resolve_safe_path(save_path)
except ValueError:
return False
return file_path.exists()
@@ -279,6 +303,7 @@ class S3FileStorage(FileStorageInterface):
self.signature_version = settings.s3_signature_version
self.endpoint_url = settings.s3_endpoint_url or f"https://{self.s3_hostname}"
self.aws_session_token = settings.aws_session_token
self.addressing_style = str(settings.s3_addressing_style or "auto").lower()
self.proxy = settings.s3_proxy
self.session = aioboto3.Session(
aws_access_key_id=self.access_key_id,
@@ -290,14 +315,26 @@ class S3FileStorage(FileStorageInterface):
# 如果提供了 s3_endpoint_url,则优先使用它
self.endpoint_url = settings.s3_endpoint_url
def _client_config(self) -> Config:
config = {"signature_version": self.signature_version}
s3_config = {}
if self.addressing_style in {"path", "virtual", "auto"}:
s3_config["addressing_style"] = self.addressing_style
if s3_config:
config["s3"] = s3_config
return Config(**config)
def _client(self):
return self.session.client(
"s3",
endpoint_url=self.endpoint_url,
aws_session_token=self.aws_session_token,
region_name=self.region_name,
config=self._client_config(),
)
async def save_file(self, file: UploadFile, save_path: str):
async with self.session.client(
"s3",
endpoint_url=self.endpoint_url,
aws_session_token=self.aws_session_token,
region_name=self.region_name,
config=Config(signature_version=self.signature_version),
) as s3:
async with self._client() as s3:
# 使用 upload_fileobj 流式上传,避免将整个文件加载到内存
await s3.upload_fileobj(
file.file,
@@ -307,12 +344,7 @@ class S3FileStorage(FileStorageInterface):
)
async def delete_file(self, file_code: FileCodes):
async with self.session.client(
"s3",
endpoint_url=self.endpoint_url,
region_name=self.region_name,
config=Config(signature_version=self.signature_version),
) as s3:
async with self._client() as s3:
await s3.delete_object(
Bucket=self.bucket_name, Key=await file_code.get_file_path()
)
@@ -322,12 +354,7 @@ class S3FileStorage(FileStorageInterface):
filename = file_code.prefix + file_code.suffix
content_length = None # 初始化为 None,表示未知大小
async with self.session.client(
"s3",
endpoint_url=self.endpoint_url,
region_name=self.region_name,
config=Config(signature_version=self.signature_version),
) as s3:
async with self._client() as s3:
# 尝试获取文件大小(HEAD请求)
try:
head_response = await s3.head_object(
@@ -383,7 +410,9 @@ class S3FileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
)
except HTTPException:
raise
@@ -396,12 +425,7 @@ class S3FileStorage(FileStorageInterface):
if self.proxy:
return await get_file_url(file_code.code)
else:
async with self.session.client(
"s3",
endpoint_url=self.endpoint_url,
region_name=self.region_name,
config=Config(signature_version=self.signature_version),
) as s3:
async with self._client() as s3:
result = await s3.generate_presigned_url(
"get_object",
Params={
@@ -418,13 +442,7 @@ class S3FileStorage(FileStorageInterface):
注意:这里不使用 S3 原生的 multipart upload,而是将每个分片作为独立对象存储
"""
chunk_key = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
async with self.session.client(
's3',
endpoint_url=self.endpoint_url,
aws_session_token=self.aws_session_token,
region_name=self.region_name,
config=Config(signature_version=self.signature_version),
) as s3:
async with self._client() as s3:
# 将分片作为独立对象上传
await s3.put_object(
Bucket=self.bucket_name,
@@ -444,13 +462,7 @@ class S3FileStorage(FileStorageInterface):
file_sha256 = hashlib.sha256()
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
async with self.session.client(
's3',
endpoint_url=self.endpoint_url,
aws_session_token=self.aws_session_token,
region_name=self.region_name,
config=Config(signature_version=self.signature_version),
) as s3:
async with self._client() as s3:
# 创建 multipart upload
mpu = await s3.create_multipart_upload(
Bucket=self.bucket_name,
@@ -524,13 +536,7 @@ class S3FileStorage(FileStorageInterface):
:param save_path: 文件保存路径
"""
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
async with self.session.client(
's3',
endpoint_url=self.endpoint_url,
aws_session_token=self.aws_session_token,
region_name=self.region_name,
config=Config(signature_version=self.signature_version),
) as s3:
async with self._client() as s3:
try:
# 列出并删除所有分片对象
paginator = s3.get_paginator('list_objects_v2')
@@ -543,7 +549,7 @@ class S3FileStorage(FileStorageInterface):
Delete={'Objects': delete_objects}
)
except Exception as e:
logger.info(f"清理 S3 分片数据时出错: {e}")
logger.warning(f"清理 S3 分片数据时出错: {e}")
async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]:
"""
@@ -552,13 +558,7 @@ class S3FileStorage(FileStorageInterface):
:param expires_in: URL过期时间(秒),默认15分钟
:return: 预签名PUT URL
"""
async with self.session.client(
"s3",
endpoint_url=self.endpoint_url,
aws_session_token=self.aws_session_token,
region_name=self.region_name,
config=Config(signature_version=self.signature_version),
) as s3:
async with self._client() as s3:
return await s3.generate_presigned_url(
"put_object",
Params={
@@ -574,18 +574,31 @@ class S3FileStorage(FileStorageInterface):
:param save_path: 文件路径
:return: 文件是否存在
"""
async with self.session.client(
"s3",
endpoint_url=self.endpoint_url,
aws_session_token=self.aws_session_token,
region_name=self.region_name,
config=Config(signature_version=self.signature_version),
) as s3:
async with self._client() as s3:
last_error = None
for attempt in range(3):
try:
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
return True
except Exception as e:
last_error = e
if attempt < 2:
await asyncio.sleep(0.2 * (attempt + 1))
try:
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
return True
except Exception:
return False
result = await s3.list_objects_v2(
Bucket=self.bucket_name,
Prefix=save_path,
MaxKeys=1,
)
for item in result.get("Contents", []):
if item.get("Key") == save_path:
return True
except Exception as e:
last_error = e
logger.warning(f"S3文件确认失败 key={save_path}: {last_error}")
return False
class OneDriveFileStorage(FileStorageInterface):
@@ -737,7 +750,9 @@ class OneDriveFileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
)
except HTTPException:
raise
@@ -862,7 +877,7 @@ class OneDriveFileStorage(FileStorageInterface):
try:
await asyncio.to_thread(self._delete_chunk_dir, chunk_dir)
except Exception as e:
logger.info(f"清理 OneDrive 分片时出错: {e}")
logger.warning(f"清理 OneDrive 分片时出错: {e}")
def _file_exists(self, save_path: str) -> bool:
"""同步检查文件是否存在"""
@@ -1020,7 +1035,7 @@ class OpenDALFileStorage(FileStorageInterface):
# OpenDAL 支持递归删除
await self.operator.remove_all(chunk_dir)
except Exception as e:
logger.info(f"清理 OpenDAL 分片时出错: {e}")
logger.warning(f"清理 OpenDAL 分片时出错: {e}")
async def file_exists(self, save_path: str) -> bool:
"""
@@ -1230,7 +1245,9 @@ class WebDAVFileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
)
except aiohttp.ClientError as e:
raise HTTPException(
@@ -1346,16 +1363,16 @@ class WebDAVFileStorage(FileStorageInterface):
file_url = self._build_url(file_path)
async with session.delete(file_url) as delete_resp:
if delete_resp.status not in (200, 204, 404):
logger.info(f"删除分片文件失败: {file_path}")
logger.warning(f"删除分片文件失败: {file_path}")
# 删除分片目录
async with session.delete(chunk_dir_url) as delete_resp:
if delete_resp.status not in (200, 204, 404):
logger.info(f"删除分片目录失败: {chunk_dir_url}")
logger.warning(f"删除分片目录失败: {chunk_dir_url}")
else:
logger.info(f"分片目录不存在: {chunk_dir_url}")
except Exception as e:
logger.info(f"清理 WebDAV 分片时出错: {e}")
logger.warning(f"清理 WebDAV 分片时出错: {e}")
async def file_exists(self, save_path: str) -> bool:
"""