✨ 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
+55
-20
@@ -1,3 +1,6 @@
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from typing import TypedDict
|
||||
from ipaddress import ip_address, ip_network
|
||||
from typing import Dict, Iterable, Union
|
||||
from datetime import datetime, timedelta
|
||||
@@ -65,36 +68,68 @@ def get_client_ip(request: Request) -> str:
|
||||
return client_host
|
||||
|
||||
|
||||
class _IPRecord(TypedDict):
|
||||
count: int
|
||||
last_seen: float
|
||||
|
||||
|
||||
# Upper bound for tracked source IPs per limiter. Without it a scan using
|
||||
# spoofed/rotating addresses grows the dict forever on a small VPS.
|
||||
DEFAULT_MAX_TRACKED_IPS = 10_000
|
||||
|
||||
|
||||
class IPRateLimit:
|
||||
def __init__(self, count: int, minutes: int):
|
||||
self.ips: Dict[str, Dict[str, Union[int, datetime]]] = {}
|
||||
def __init__(
|
||||
self,
|
||||
count: int,
|
||||
minutes: int,
|
||||
max_ips: int = DEFAULT_MAX_TRACKED_IPS,
|
||||
):
|
||||
# Ordered by last activity (oldest first) so capacity eviction and the
|
||||
# periodic cleanup are both O(1)/O(expired) instead of a full rebuild.
|
||||
self.ips: OrderedDict[str, _IPRecord] = OrderedDict()
|
||||
self.count = count
|
||||
self.minutes = minutes
|
||||
self.max_ips = max(1, max_ips)
|
||||
|
||||
def _window_seconds(self) -> float:
|
||||
# minutes is mutable at runtime via apps.base.config._sync_ip_limits.
|
||||
return float(self.minutes) * 60
|
||||
|
||||
def check_ip(self, ip: str) -> bool:
|
||||
if ip in self.ips:
|
||||
ip_info = self.ips[ip]
|
||||
if ip_info["count"] >= self.count:
|
||||
if ip_info["time"] + timedelta(minutes=self.minutes) > datetime.now():
|
||||
return False
|
||||
self.ips.pop(ip)
|
||||
record = self.ips.get(ip)
|
||||
if record is None:
|
||||
return True
|
||||
if record["count"] >= self.count:
|
||||
if record["last_seen"] + self._window_seconds() > time.monotonic():
|
||||
return False
|
||||
self.ips.pop(ip, None)
|
||||
return True
|
||||
|
||||
def add_ip(self, ip: str) -> int:
|
||||
ip_info = self.ips.get(ip, {"count": 0, "time": datetime.now()})
|
||||
ip_info["count"] += 1
|
||||
ip_info["time"] = datetime.now()
|
||||
self.ips[ip] = ip_info
|
||||
return ip_info["count"]
|
||||
now = time.monotonic()
|
||||
record = self.ips.get(ip)
|
||||
if record is None:
|
||||
record = {"count": 0, "last_seen": now}
|
||||
self.ips[ip] = record
|
||||
else:
|
||||
self.ips.move_to_end(ip)
|
||||
record["count"] += 1
|
||||
record["last_seen"] = now
|
||||
while len(self.ips) > self.max_ips:
|
||||
# Evict the least recently active IP; fail-open for the evicted
|
||||
# address is preferable to unbounded memory growth.
|
||||
self.ips.popitem(last=False)
|
||||
return record["count"]
|
||||
|
||||
async def remove_expired_ip(self) -> None:
|
||||
now = datetime.now()
|
||||
expiration = timedelta(minutes=self.minutes)
|
||||
self.ips = {
|
||||
ip: info
|
||||
for ip, info in self.ips.items()
|
||||
if info["time"] + expiration >= now
|
||||
}
|
||||
now = time.monotonic()
|
||||
window = self._window_seconds()
|
||||
while self.ips:
|
||||
_, record = next(iter(self.ips.items()))
|
||||
if record["last_seen"] + window >= now:
|
||||
break
|
||||
self.ips.popitem(last=False)
|
||||
|
||||
def __call__(self, request: Request) -> str:
|
||||
ip = get_client_ip(request)
|
||||
|
||||
@@ -13,7 +13,7 @@ from __future__ import annotations
|
||||
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
from core.storage import build_attachment_headers
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
@@ -96,8 +96,7 @@ def build_local_ref_download(file_code) -> FileResponse:
|
||||
filename = f"{getattr(file_code, 'prefix', '') or ''}{getattr(file_code, 'suffix', '') or ''}"
|
||||
if not filename:
|
||||
filename = path.name
|
||||
encoded_filename = quote(filename, safe="")
|
||||
headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"}
|
||||
headers = build_attachment_headers(filename)
|
||||
try:
|
||||
headers["Content-Length"] = str(path.stat().st_size)
|
||||
except OSError:
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
from tortoise import connections
|
||||
|
||||
# 高频查询字段索引。真实部署的 schema 全部由迁移建立
|
||||
# (init_db 不调用 generate_schemas),因此索引必须写在迁移里;
|
||||
# apps/base/models.py 中的 index/Meta 仅用于测试的 generate_schemas 路径。
|
||||
#
|
||||
# - filecodes(expired_at):过期扫描(delete_expire_files)与后台过期统计。
|
||||
# - filecodes(created_at):后台默认倒序列表、首页最近记录、今日/昨日统计。
|
||||
# - uploadchunk(upload_id, chunk_index):分片状态检查与合并;其前缀同时
|
||||
# 覆盖仅按 upload_id 的删除/清理查询(原先没有对应索引)。
|
||||
# 已知缺口:clean_incomplete_uploads 的 chunk_index=-1 AND created_at<? 用不上
|
||||
# 该复合索引,待清理任务改为分批查询后再评估。
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_expired_at
|
||||
ON filecodes (expired_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_created_at
|
||||
ON filecodes (created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_uploadchunk_upload_chunk
|
||||
ON uploadchunk (upload_id, chunk_index);
|
||||
"""
|
||||
)
|
||||
+6
-3
@@ -21,10 +21,10 @@ class FileCodes(models.Model):
|
||||
file_path = fields.CharField(max_length=255, null=True)
|
||||
size = fields.BigIntField(default=0)
|
||||
text = fields.TextField(null=True)
|
||||
expired_at = fields.DatetimeField(null=True)
|
||||
expired_at = fields.DatetimeField(null=True, index=True)
|
||||
expired_count = fields.IntField(default=-1)
|
||||
used_count = fields.IntField(default=0)
|
||||
created_at = fields.DatetimeField(auto_now_add=True)
|
||||
created_at = fields.DatetimeField(auto_now_add=True, index=True)
|
||||
file_hash = fields.CharField(max_length=64, null=True)
|
||||
is_chunked = fields.BooleanField(default=False)
|
||||
upload_id = fields.CharField(max_length=36, null=True)
|
||||
@@ -61,7 +61,7 @@ class ShareCodeReservations(models.Model):
|
||||
|
||||
class UploadChunk(models.Model):
|
||||
id = fields.IntField(pk=True)
|
||||
upload_id = fields.CharField(max_length=36, index=True)
|
||||
upload_id = fields.CharField(max_length=36)
|
||||
chunk_index = fields.IntField()
|
||||
chunk_hash = fields.CharField(max_length=64)
|
||||
total_chunks = fields.IntField()
|
||||
@@ -73,6 +73,9 @@ class UploadChunk(models.Model):
|
||||
completed = fields.BooleanField(default=False)
|
||||
storage_mode = fields.CharField(max_length=32, default="legacy")
|
||||
|
||||
class Meta:
|
||||
indexes = [("upload_id", "chunk_index")]
|
||||
|
||||
|
||||
class TransferStats(models.Model):
|
||||
id = fields.IntField(pk=True)
|
||||
|
||||
+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