feat(file-check): 新增文件资产管理与清理功能,支持上传、查询、删除及下载
This commit is contained in:
1 parent
143e054d86
commit
729546a7b7
52 files changed
+3420
-34
No files matched your search
@@ -0,0 +1,200 @@
|
||||
"""
|
||||
backend/app/services/file_assets/service.py
|
||||
|
||||
用途:FileAsset 业务编排(校验、哈希、落库、鉴权、生命周期)。
|
||||
依赖:file_assets.storage、models.FileAsset、Flask current_app。
|
||||
逻辑:由 /api/files 与 shipping intake 调用;storage_key 不向前端返回。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from werkzeug.datastructures import FileStorage
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.core.response import utc_iso
|
||||
from app.models import FileAsset
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
_ALLOWED_EXTENSIONS = {
|
||||
'pdf', 'doc', 'docx', 'txt', 'md', 'log', 'html', 'htm', 'eml',
|
||||
'csv', 'png', 'jpg', 'jpeg', 'webp',
|
||||
}
|
||||
|
||||
|
||||
def _max_file_size_bytes() -> int:
|
||||
mb = int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30)
|
||||
return max(mb, 1) * 1024 * 1024
|
||||
|
||||
|
||||
def _temp_ttl_hours() -> int:
|
||||
return max(int(current_app.config.get('FILE_ASSET_TEMP_TTL_HOURS', 72) or 72), 1)
|
||||
|
||||
|
||||
def generate_asset_no() -> str:
|
||||
"""生成 FA-YYYYMMDD-XXXXXXXX 格式资产编号。"""
|
||||
return f"FA-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def _normalize_extension(filename: str) -> str:
|
||||
ext = os.path.splitext(str(filename or '').strip())[1].lower().lstrip('.')
|
||||
return ext
|
||||
|
||||
|
||||
def _build_storage_key(*, user_id: int, asset_no: str, filename: str) -> str:
|
||||
now = datetime.utcnow()
|
||||
safe_name = secure_filename(filename) or 'file'
|
||||
safe_name = re.sub(r'[^\w\-.]+', '_', safe_name)[:120] or 'file'
|
||||
return f"temporary/{user_id}/{now:%Y}/{now:%m}/{asset_no}/{safe_name}"
|
||||
|
||||
|
||||
def _serialize_asset(asset: FileAsset) -> dict[str, Any]:
|
||||
return {
|
||||
'asset_no': asset.asset_no,
|
||||
'original_filename': asset.original_filename,
|
||||
'file_size': asset.file_size,
|
||||
'mime_type': asset.mime_type,
|
||||
'content_hash': asset.content_hash,
|
||||
'upload_status': asset.upload_status,
|
||||
'lifecycle_status': asset.lifecycle_status,
|
||||
'expires_at': utc_iso(asset.expires_at),
|
||||
'created_at': utc_iso(asset.created_at),
|
||||
}
|
||||
|
||||
|
||||
def get_asset_for_user(asset_no: str, user_id: int) -> FileAsset:
|
||||
"""
|
||||
按编号查询当前用户拥有的资产。
|
||||
Raises:
|
||||
NotFoundError: 不存在或已逻辑删除。
|
||||
ForbiddenError: 非所有者。
|
||||
"""
|
||||
normalized = str(asset_no or '').strip().upper()
|
||||
asset = (
|
||||
db.session.query(FileAsset)
|
||||
.filter(FileAsset.asset_no == normalized, FileAsset.deleted_at.is_(None))
|
||||
.first()
|
||||
)
|
||||
if not asset:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在')
|
||||
if int(asset.owner_user_id) != int(user_id):
|
||||
raise ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权访问该文件资产')
|
||||
return asset
|
||||
|
||||
|
||||
def upload_file_asset(*, user_id: int, upload: FileStorage) -> dict[str, Any]:
|
||||
"""
|
||||
上传文件并创建 FileAsset 记录。
|
||||
核心逻辑:校验类型与大小 → SHA-256 → 写 MinIO → 落库 ready/temporary。
|
||||
"""
|
||||
filename = str(upload.filename or '').strip() or 'file'
|
||||
ext = _normalize_extension(filename)
|
||||
if ext not in _ALLOWED_EXTENSIONS:
|
||||
raise ValidationError(
|
||||
code='FILE_ASSET.INVALID_TYPE',
|
||||
message=f'不支持的文件类型: .{ext or "unknown"}',
|
||||
)
|
||||
|
||||
data = upload.read()
|
||||
if not data:
|
||||
raise ValidationError(code='FILE_ASSET.UPLOAD_FAILED', message='文件内容为空')
|
||||
if len(data) > _max_file_size_bytes():
|
||||
raise ValidationError(code='FILE_ASSET.SIZE_EXCEEDED', message='文件大小超过限制')
|
||||
|
||||
content_hash = hashlib.sha256(data).hexdigest()
|
||||
asset_no = generate_asset_no()
|
||||
storage_key = _build_storage_key(user_id=user_id, asset_no=asset_no, filename=filename)
|
||||
mime_type = upload.mimetype or mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
||||
expires_at = datetime.utcnow() + timedelta(hours=_temp_ttl_hours())
|
||||
|
||||
asset = FileAsset(
|
||||
asset_no=asset_no,
|
||||
owner_user_id=int(user_id),
|
||||
original_filename=filename,
|
||||
storage_provider='minio',
|
||||
storage_bucket=file_asset_storage.bucket_name,
|
||||
storage_key=storage_key,
|
||||
content_hash=content_hash,
|
||||
file_size=len(data),
|
||||
mime_type=mime_type,
|
||||
extension=ext or None,
|
||||
upload_status='uploading',
|
||||
lifecycle_status='temporary',
|
||||
reference_count=0,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
|
||||
try:
|
||||
file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type=mime_type)
|
||||
asset.upload_status = 'ready'
|
||||
except Exception:
|
||||
asset.upload_status = 'failed'
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
db.session.commit()
|
||||
return _serialize_asset(asset)
|
||||
|
||||
|
||||
def mark_asset_referenced(asset: FileAsset) -> None:
|
||||
"""将资产标记为被业务引用。"""
|
||||
asset.lifecycle_status = 'referenced'
|
||||
asset.reference_count = int(asset.reference_count or 0) + 1
|
||||
asset.expires_at = None
|
||||
asset.updated_at = datetime.utcnow()
|
||||
|
||||
|
||||
def delete_temporary_asset(*, asset_no: str, user_id: int) -> None:
|
||||
"""
|
||||
删除未引用的临时资产:先标记 expired,再删 MinIO;成功后标记 deleted。
|
||||
Raises:
|
||||
ConflictError: 已被业务引用。
|
||||
ServiceUnavailableError: MinIO 删除失败(保留 expired 供清理重试)。
|
||||
"""
|
||||
asset = get_asset_for_user(asset_no, user_id)
|
||||
if str(asset.lifecycle_status or '') == 'referenced' or int(asset.reference_count or 0) > 0:
|
||||
raise ConflictError(code='FILE_ASSET.ALREADY_REFERENCED', message='文件已被业务引用,无法删除')
|
||||
if str(asset.upload_status or '') == 'deleted' and asset.deleted_at is not None:
|
||||
return
|
||||
|
||||
now = datetime.utcnow()
|
||||
asset.lifecycle_status = 'expired'
|
||||
asset.updated_at = now
|
||||
db.session.flush()
|
||||
|
||||
try:
|
||||
file_asset_storage.delete_object(asset.storage_key)
|
||||
except Exception:
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
asset.upload_status = 'deleted'
|
||||
asset.deleted_at = now
|
||||
asset.updated_at = now
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def read_asset_bytes(asset: FileAsset) -> bytes:
|
||||
"""读取资产对象字节,校验未过期/未删除。"""
|
||||
if asset.deleted_at is not None:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='文件资产不存在')
|
||||
if asset.expires_at and asset.expires_at < datetime.utcnow() and asset.lifecycle_status == 'temporary':
|
||||
raise ValidationError(code='FILE_ASSET.EXPIRED', message='文件资产已过期')
|
||||
return file_asset_storage.get_bytes(asset.storage_key)
|
||||
|
||||
|
||||
def serialize_asset_public(asset: FileAsset) -> dict[str, Any]:
|
||||
"""对外序列化资产(不含 storage_key)。"""
|
||||
return _serialize_asset(asset)
|
||||
Reference in new issue
Block a user