✨ 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

+24 -3
View File
@@ -1,7 +1,7 @@
import datetime
from typing import Any, Optional, Union
from typing import Annotated, Any, Literal, Optional, Union
from pydantic import BaseModel
from pydantic import BaseModel, Field, model_validator
class IDData(BaseModel):
@@ -59,7 +59,28 @@ class BatchFilePolicyActionData(BaseModel):
class TrashRetentionData(BaseModel):
id: int
retentionDays: int
retentionDays: Optional[int] = Field(default=None, ge=0, le=365)
expiresAt: Optional[datetime.datetime] = None
@model_validator(mode="after")
def one_deadline(self):
if (self.retentionDays is None) == (self.expiresAt is None):
raise ValueError("请选择保留天数或自动清理时间")
return self
class BatchTrashData(BaseModel):
ids: list[Annotated[int, Field(strict=True, gt=0)]] = Field(min_length=1, max_length=100)
action: Literal["restore", "purge", "retention"]
retentionDays: Optional[int] = Field(default=None, ge=0, le=365)
expiresAt: Optional[datetime.datetime] = None
@model_validator(mode="after")
def validate_action_payload(self):
provided = int(self.retentionDays is not None) + int(self.expiresAt is not None)
if (self.action == "retention" and provided != 1) or (self.action != "retention" and provided):
raise ValueError("清理时间参数与操作不匹配")
return self
class FileMetadataData(BaseModel):
+19 -40
View File
@@ -26,7 +26,10 @@ from core.settings import data_root
from core.utils import get_now, hash_password, is_password_hashed
class FileService:
from apps.admin.trash_management import TrashManagementMixin
class FileService(TrashManagementMixin):
FILE_METADATA_KEY_PREFIX = "admin_file_metadata:"
FILE_VIEW_PRESETS_KEY = "admin_file_view_presets"
ADMIN_ACTIVITY_KEY = "admin_activity_events"
@@ -107,8 +110,8 @@ class FileService:
deduped.append(stat)
return deduped
async def _delete_file_code(self, file_code: FileCodes):
await self.move_to_trash(file_code, reason="manual")
async def _delete_file_code(self, file_code: FileCodes, reason: str = "manual"):
await self.move_to_trash(file_code, reason=reason)
@staticmethod
def _trash_path(file_code: FileCodes) -> str:
@@ -181,11 +184,18 @@ class FileService:
)
file_code.file_path = destination_dir
original_code = file_code.code
await ShareCodeReservations.get_or_create(
code=original_code,
defaults={"file_code_id": file_code.id, "reason": "restored"},
)
file_code.code = await get_random_code()
active_collision = await FileCodes.filter(
code=original_code, is_trashed=False
).exclude(id=file_code.id).exists()
if active_collision:
raise HTTPException(status_code=409, detail="原取件码已被其他文件占用,无法复用")
reservations = await ShareCodeReservations.filter(code=original_code).all()
if any(reservation.file_code_id != file_code.id for reservation in reservations):
raise HTTPException(status_code=409, detail="原取件码已被历史记录占用,无法复用")
await ShareCodeReservations.filter(
code=original_code, file_code_id=file_code.id
).delete()
file_code.code = original_code
file_code.is_trashed = False
file_code.trashed_at = None
file_code.trash_expires_at = None
@@ -248,37 +258,6 @@ class FileService:
meta={"auditOnly": True},
)
async def list_trash(self, page: int, size: int) -> dict[str, Any]:
page = max(page, 1)
size = min(max(size, 1), 100)
query = FileCodes.filter(is_trashed=True).order_by("-trashed_at", "-id")
total = await query.count()
files = await query.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}
async def set_trash_retention(self, file_id: int, retention_days: int) -> FileCodes:
file_code = await FileCodes.filter(id=file_id, is_trashed=True).first()
if not file_code:
raise HTTPException(status_code=404, detail="回收站文件不存在")
file_code.trash_expires_at = self._trash_expiry(await get_now(), retention_days)
await file_code.save(update_fields=["trash_expires_at"])
return file_code
async def delete_file(self, file_id: int):
file_code = await FileCodes.get(id=file_id)
target_name = self._build_file_activity_name(file_code)
@@ -304,7 +283,7 @@ class FileService:
continue
try:
await self._delete_file_code(file_code)
await self._delete_file_code(file_code, reason="batch_delete")
deleted.append(file_id)
except Exception as exc:
failed.append({"id": file_id, "reason": str(exc)})
+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}
+14 -2
View File
@@ -22,6 +22,7 @@ from apps.admin.schemas import (
BatchFilePolicyActionData,
FilePolicyActionData,
TrashRetentionData,
BatchTrashData,
FileMetadataData,
FileViewPresetData,
FileViewPresetDeleteData,
@@ -459,9 +460,20 @@ async def file_batch_delete_post(
async def trash_list(
page: int = 1,
size: int = 20,
keyword: str = "",
state: str = "all",
reason: str = "",
file_service: FileService = Depends(get_file_service),
):
return APIResponse(detail=await file_service.list_trash(page, size))
return APIResponse(detail=await file_service.list_trash(page, size, keyword, state, reason))
@admin_api.post("/trash/batch")
async def trash_batch(
data: BatchTrashData,
file_service: FileService = Depends(get_file_service),
):
return APIResponse(detail=await file_service.batch_trash(data.ids, data.action, data.retentionDays, data.expiresAt))
@admin_api.post("/trash/restore")
@@ -478,7 +490,7 @@ async def trash_retention(
data: TrashRetentionData,
file_service: FileService = Depends(get_file_service),
):
file_code = await file_service.set_trash_retention(data.id, data.retentionDays)
file_code = await file_service.set_trash_retention(data.id, data.retentionDays, data.expiresAt)
return APIResponse(detail={"id": file_code.id, "trashExpiresAt": file_code.trash_expires_at})