✨ feat(core): 引入垃圾回收管理功能

* 新增垃圾回收管理逻辑,支持批量管理与清理功能
* 在数据模型中增加过期时间与保留天数验证逻辑
* 在 FileService 中集成垃圾回收管理模块
* 调整任务调度逻辑以适配新的垃圾回收规则
* 为垃圾回收功能补充相应的单元测试覆盖
This commit is contained in:
orion committed 2026-09-18 09:39:27 +08:00
1 parent 356f23bae1
commit b10113e5ab
6 files changed
+388 -46

No files matched your search

+132
View File
@@ -0,0 +1,132 @@
"""Recycle-bin queries and bulk orchestration; storage actions stay in FileService."""
from datetime import datetime, timedelta
from typing import Any
from fastapi import HTTPException
from tortoise.expressions import Q, RawSQL
from apps.base.models import FileCodes
from core.utils import get_now
def automatic_trash_reason(file_code: FileCodes, now: datetime) -> str | None:
deadline = file_code.expired_at
if deadline is not None and deadline.tzinfo is None:
deadline = deadline.replace(tzinfo=now.tzinfo)
timed_out = deadline is not None and deadline <= now
count_exhausted = file_code.expired_count == 0
if timed_out and count_exhausted:
return "expired_both"
if timed_out:
return "expired_time"
if count_exhausted:
return "expired_count"
return None
class TrashManagementMixin:
async def list_trash(self, page: int, size: int, keyword: str = "", state: str = "all", reason: str = "") -> dict[str, Any]:
if state not in {"all", "recoverable", "permanent", "scheduled", "purged"}:
raise HTTPException(400, "无效的回收站状态")
if reason not in {"", "manual", "batch_delete", "expired_time", "expired_count", "expired_both", "expired"}:
raise HTTPException(400, "无效的移入原因")
page, size = max(page, 1), min(max(size, 1), 100)
base = FileCodes.filter(is_trashed=True)
stored_total = await base.count()
purged = await base.filter(trash_purged_at__isnull=False).count()
query = base
if state == "purged":
query = query.filter(trash_purged_at__isnull=False)
elif state != "all":
query = query.filter(trash_purged_at__isnull=True)
if state in {"permanent", "scheduled"}:
query = query.filter(trash_expires_at__isnull=state == "permanent")
if reason:
query = query.filter(trash_reason=reason)
keyword = keyword.strip()
if keyword:
# FileCodeBox uses SQLite; a fixed expression joins both filename parts.
# User input remains an ORM-bound value, never SQL source.
query = query.annotate(trash_name=RawSQL('COALESCE("prefix", \'\') || COALESCE("suffix", \'\')')).filter(
Q(trash_name__icontains=keyword) | Q(code__icontains=keyword)
)
total = await query.count()
files = await query.order_by("-trashed_at", "-id").offset((page - 1) * size).limit(size)
now = await get_now()
items = []
for file_code in files:
item = await self._build_admin_file_item(file_code, now=now)
item.update({
"trashedAt": file_code.trashed_at, "trashExpiresAt": file_code.trash_expires_at,
"trashReason": file_code.trash_reason, "trashPurgedAt": file_code.trash_purged_at,
"isTrashPermanent": file_code.trash_expires_at is None and file_code.trash_purged_at is None,
"isTrashPurged": file_code.trash_purged_at is not None,
})
items.append(item)
return {"page": page, "size": size, "total": total, "data": items,
"summary": {"total": stored_total, "recoverable": stored_total-purged, "purged": purged},
"capabilities": {"filters": True, "batch": True, "customRetention": True}}
async def _retention_deadline(self, retention_days: int | None, expires_at: datetime | None):
if (retention_days is None) == (expires_at is None):
raise HTTPException(400, "请选择保留天数或自动清理时间")
now = await get_now()
if expires_at is None:
return self._trash_expiry(now, retention_days)
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=now.tzinfo)
else:
expires_at = expires_at.astimezone(now.tzinfo)
if not now < expires_at <= now + timedelta(days=self.TRASH_MAX_RETENTION_DAYS):
raise HTTPException(400, "自动清理时间必须在未来 365 天内")
return expires_at
async def set_trash_retention(self, file_id: int, retention_days: int | None = None, expires_at: datetime | None = None) -> FileCodes:
deadline = await self._retention_deadline(retention_days, expires_at)
file_code = await FileCodes.filter(id=file_id, is_trashed=True).first()
if not file_code:
raise HTTPException(404, "回收站文件不存在")
if file_code.trash_purged_at is not None:
raise HTTPException(409, "文件已清理,不能修改保留时间")
file_code.trash_expires_at = deadline
await file_code.save(update_fields=["trash_expires_at"])
await self.record_admin_activity("trash.retention", "file", file_id, self._build_file_activity_name(file_code),
meta={"expiresAt": deadline.isoformat() if deadline else None})
return file_code
async def batch_trash(self, ids: list[int], action: str, retention_days: int | None = None, expires_at: datetime | None = None) -> dict[str, Any]:
if not ids or len(ids) > 100 or any(type(i) is not int or i <= 0 for i in ids):
raise HTTPException(400, "请选择 1 到 100 条有效记录")
if action not in {"restore", "purge", "retention"}:
raise HTTPException(400, "无效的批量操作")
if action == "retention":
await self._retention_deadline(retention_days, expires_at)
elif retention_days is not None or expires_at is not None:
raise HTTPException(400, "该操作不接受清理时间参数")
unique_ids = list(dict.fromkeys(ids))
succeeded, failed = [], []
for file_id in unique_ids:
try:
item = await FileCodes.filter(id=file_id, is_trashed=True).first()
if not item:
raise HTTPException(404, "回收站文件不存在")
if item.trash_purged_at is not None:
raise HTTPException(409, "文件已清理,仅保留审计记录")
if action == "restore":
restored = await self.restore_from_trash(file_id)
succeeded.append({"id": file_id, "code": restored.code})
elif action == "purge":
await self.purge_trashed_file(item)
succeeded.append({"id": file_id})
else:
updated = await self.set_trash_retention(file_id, retention_days, expires_at)
succeeded.append({"id": file_id, "trashExpiresAt": updated.trash_expires_at})
except HTTPException as exc:
failed.append({"id": file_id, "reason": str(exc.detail)})
except Exception:
# Storage exceptions can contain private endpoints or credentials.
failed.append({"id": file_id, "reason": "操作失败,请重试"})
if succeeded:
await self.record_admin_activity(f"trash.batch_{action}", "file", count=len(succeeded),
meta={"requestedCount": len(unique_ids), "failedCount": len(failed)})
return {"requestedCount": len(unique_ids), "succeeded": succeeded, "failed": failed}