feat(file-check): 新增文件资产管理与清理功能,支持上传、查询、删除及下载

This commit is contained in:
hugo committed 2026-07-14 09:14:44 +08:00
1 parent 143e054d86
commit 729546a7b7
52 files changed
+3420 -34

No files matched your search

@@ -0,0 +1,83 @@
"""
backend/app/services/file_assets/cleanup.py
用途:过期未引用 FileAsset 与关联 intake 的清理编排。
依赖:file_assets.storage、models.FileAsset/ShippingNoticeIntake。
逻辑:由排程或 file_asset_cleanup Job 调用;先标记 expired → 删 MinIO → 成功后 mark deleted;
MinIO 删除失败不伪装成功,保留记录供下次重试。
"""
from __future__ import annotations
import logging
from datetime import datetime
from sqlalchemy import or_
from app import db
from app.models import FileAsset, ShippingNoticeIntake
from app.services.file_assets.storage import file_asset_storage
_LOGGER = logging.getLogger(__name__)
def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
"""
清理过期或已标记 expired 但尚未物理删除的临时资产。
Returns:
统计字典:scanned/expired/deleted/errors。
"""
now = datetime.utcnow()
assets = (
db.session.query(FileAsset)
.filter(
FileAsset.reference_count == 0,
FileAsset.deleted_at.is_(None),
or_(
(
(FileAsset.lifecycle_status == 'temporary')
& (FileAsset.expires_at.isnot(None))
& (FileAsset.expires_at < now)
),
FileAsset.lifecycle_status == 'expired',
),
)
.order_by(FileAsset.expires_at.asc().nullsfirst(), FileAsset.id.asc())
.limit(max(int(limit or 100), 1))
.all()
)
stats = {'scanned': len(assets), 'expired': 0, 'deleted': 0, 'errors': 0}
for asset in assets:
consumed = (
db.session.query(ShippingNoticeIntake.id)
.filter(
ShippingNoticeIntake.asset_id == asset.id,
ShippingNoticeIntake.parse_status == 'consumed',
)
.first()
)
if consumed:
continue
stats['expired'] += 1
asset.lifecycle_status = 'expired'
(
db.session.query(ShippingNoticeIntake)
.filter(
ShippingNoticeIntake.asset_id == asset.id,
ShippingNoticeIntake.consumed_at.is_(None),
ShippingNoticeIntake.parse_status.notin_(('consumed', 'cancelled')),
)
.update({'parse_status': 'expired', 'updated_at': now}, synchronize_session=False)
)
try:
file_asset_storage.delete_object(asset.storage_key)
asset.upload_status = 'deleted'
asset.deleted_at = now
asset.updated_at = now
stats['deleted'] += 1
except Exception:
stats['errors'] += 1
asset.updated_at = now
_LOGGER.exception('failed to delete minio object for asset %s', asset.asset_no)
db.session.commit()
return stats