""" backend/app/services/file_assets/service.py 用途:FileAsset 业务编排(校验、哈希、落库、鉴权、生命周期)。 依赖:file_assets.storage、models.FileAsset、Flask current_app。 逻辑:由 /api/files 与 shipping intake 调用;storage_key 不向前端返回; create_derived_file_asset_from_bytes 供 EML 附件子资产幂等落库(阶段二); mark/release 以 SQL 原子 UPDATE 按关联边增减 reference_count;补偿失败写 orphan_cleanup 行。 """ from __future__ import annotations import hashlib import logging import mimetypes import os import re import uuid from datetime import datetime, timedelta from typing import Any from flask import current_app from sqlalchemy import case, update from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session 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 _LOGGER = logging.getLogger(__name__) def _keep_first_source_attachment_key( asset: FileAsset, *, source_attachment_key: str | None, ) -> bool: """ 仅在资产尚无来源键时写入首次 source_attachment_key,复用/复活不覆盖。 Returns: 是否实际写入了字段。 """ incoming = str(source_attachment_key or '').strip() if not incoming or str(asset.source_attachment_key or '').strip(): return False asset.source_attachment_key = incoming[:64] return True _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 _build_derived_storage_key( *, user_id: int, parent_asset_no: str, 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' parent = re.sub(r'[^\w\-]+', '_', str(parent_asset_no or 'parent'))[:64] or 'parent' return f"derived/{user_id}/{now:%Y}/{now:%m}/{parent}/{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, 'parent_asset_id': asset.parent_asset_id, 'asset_role': asset.asset_role, 'source_attachment_key': asset.source_attachment_key, '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, parent_asset_id=None, asset_role='upload', source_attachment_key=None, 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 _find_derived_by_parent_hash( *, parent_id: int, content_hash: str, include_deleted: bool = False, ) -> FileAsset | None: """按父资产 + content_hash 查找派生资产(默认可复用活记录)。""" query = db.session.query(FileAsset).filter( FileAsset.parent_asset_id == int(parent_id), FileAsset.content_hash == content_hash, ) if not include_deleted: query = query.filter(FileAsset.deleted_at.is_(None)) return query.order_by(FileAsset.id.asc()).first() def _revive_soft_deleted_derived_asset( asset: FileAsset, *, data: bytes, filename: str, mime_type: str | None, source_attachment_key: str | None, uploaded_storage_keys: list[str] | None, ) -> FileAsset: """ 恢复被 soft-delete 的派生资产并重新上传对象。 核心逻辑:清理 deleted_at 后复用原 storage_key;失败时保持 expired 供清理。 """ resolved_mime = ( str(mime_type or asset.mime_type or '').strip() or mimetypes.guess_type(filename)[0] or 'application/octet-stream' ) asset.deleted_at = None asset.upload_status = 'uploading' asset.lifecycle_status = 'temporary' asset.reference_count = 0 asset.expires_at = datetime.utcnow() + timedelta(hours=_temp_ttl_hours()) asset.original_filename = str(filename or asset.original_filename or 'attachment.bin')[:255] asset.mime_type = resolved_mime[:128] # 复活时仅补写空的首次来源键,不覆盖历史审计值 _keep_first_source_attachment_key(asset, source_attachment_key=source_attachment_key) asset.updated_at = datetime.utcnow() db.session.flush() try: file_asset_storage.upload_bytes( storage_key=asset.storage_key, data=data, content_type=resolved_mime, ) asset.upload_status = 'ready' if uploaded_storage_keys is not None: uploaded_storage_keys.append(asset.storage_key) except Exception: asset.upload_status = 'failed' asset.lifecycle_status = 'expired' asset.updated_at = datetime.utcnow() raise return asset def create_derived_file_asset_from_bytes( *, user_id: int, parent: FileAsset, data: bytes, filename: str, mime_type: str | None = None, source_attachment_key: str | None = None, asset_role: str = 'derived_attachment', uploaded_storage_keys: list[str] | None = None, ) -> tuple[FileAsset, bool]: """ 从可信内部字节创建(或复用)派生 FileAsset。 核心逻辑:按 parent_asset_id + content_hash 幂等;DB 唯一约束兜底并发; IntegrityError 时 SAVEPOINT 回滚后回查已有行;新建成功后记录 storage_key 供事务失败补偿。 source_attachment_key 语义为「首次来源键」:已有值时复用不覆盖。 Args: user_id: 所有者,须与 parent.owner_user_id 一致。 parent: EML 等根资产。 data: 附件原始字节(不可为空)。 filename: 原始文件名。 mime_type: MIME;缺省按文件名猜测。 source_attachment_key: 首次资产化时的 att-key(审计);后续复用不改。 asset_role: 默认 derived_attachment。 uploaded_storage_keys: 若提供,本函数成功上传的新对象 key 会 append,供调用方失败补偿。 Returns: (已 ready 的 FileAsset, created_new);flush,不 commit。 Raises: ForbiddenError: 非父资产所有者。 ValidationError: 空内容或超大。 """ if int(parent.owner_user_id) != int(user_id): raise ForbiddenError(code='FILE_ASSET.FORBIDDEN', message='无权在该父资产下创建派生文件') 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().lower() existing = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash) if existing is not None: if _keep_first_source_attachment_key(existing, source_attachment_key=source_attachment_key): existing.updated_at = datetime.utcnow() if str(existing.upload_status or '') == 'ready': return existing, False try: file_asset_storage.upload_bytes( storage_key=existing.storage_key, data=data, content_type=existing.mime_type or 'application/octet-stream', ) existing.upload_status = 'ready' existing.updated_at = datetime.utcnow() if uploaded_storage_keys is not None: uploaded_storage_keys.append(existing.storage_key) except Exception: existing.upload_status = 'failed' existing.updated_at = datetime.utcnow() raise return existing, False # 软删除记录挡住同哈希时优先复活,避免孤儿行永久占位 soft_deleted = _find_derived_by_parent_hash( parent_id=int(parent.id), content_hash=content_hash, include_deleted=True, ) if soft_deleted is not None and soft_deleted.deleted_at is not None: revived = _revive_soft_deleted_derived_asset( soft_deleted, data=data, filename=str(filename or soft_deleted.original_filename or 'attachment.bin'), mime_type=mime_type, source_attachment_key=source_attachment_key, uploaded_storage_keys=uploaded_storage_keys, ) return revived, False safe_filename = str(filename or '').strip() or 'attachment.bin' ext = _normalize_extension(safe_filename) if not ext: ext = 'bin' if not os.path.splitext(safe_filename)[1]: safe_filename = f'{safe_filename}.bin' asset_no = generate_asset_no() storage_key = _build_derived_storage_key( user_id=int(user_id), parent_asset_no=str(parent.asset_no or ''), asset_no=asset_no, filename=safe_filename, ) resolved_mime = ( str(mime_type or '').strip() or mimetypes.guess_type(safe_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), parent_asset_id=int(parent.id), asset_role=str(asset_role or 'derived_attachment')[:32], source_attachment_key=(str(source_attachment_key)[:64] if source_attachment_key else None), original_filename=safe_filename[:255], storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, content_hash=content_hash, file_size=len(data), mime_type=resolved_mime[:128], extension=ext[:32] if ext else None, upload_status='uploading', lifecycle_status='temporary', reference_count=0, expires_at=expires_at, ) # [STEP] 幂等插入派生资产:先查后建规避常见唯一约束冲突;冲突时回读已有行。 # 不使用 begin_nested SAVEPOINT:被 SAVEPOINT 语义包住的 INSERT 在同一 Session # 内创建多个派生资产时,其行对后续 autoflush 的 UPDATE 不可见,会触发 StaleDataError。 try: db.session.add(asset) db.session.flush() except IntegrityError: raced = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash) if raced is not None: if _keep_first_source_attachment_key(raced, source_attachment_key=source_attachment_key): raced.updated_at = datetime.utcnow() return raced, False # 冲突落在软删除行(旧全量唯一约束环境)时尝试复活 raced_deleted = _find_derived_by_parent_hash( parent_id=int(parent.id), content_hash=content_hash, include_deleted=True, ) if raced_deleted is None: raise revived = _revive_soft_deleted_derived_asset( raced_deleted, data=data, filename=safe_filename, mime_type=mime_type, source_attachment_key=source_attachment_key, uploaded_storage_keys=uploaded_storage_keys, ) return revived, False try: file_asset_storage.upload_bytes( storage_key=storage_key, data=data, content_type=resolved_mime, ) asset.upload_status = 'ready' if uploaded_storage_keys is not None: uploaded_storage_keys.append(storage_key) except Exception: asset.upload_status = 'failed' raise return asset, True def mark_asset_referenced(asset: FileAsset) -> None: """ 建立一次业务引用:原子 +1,并置 lifecycle=referenced。 核心逻辑:数据库层 `reference_count = reference_count + 1`,避免并发读改写丢失。 """ now = datetime.utcnow() db.session.execute( update(FileAsset) .where(FileAsset.id == int(asset.id)) .values( reference_count=FileAsset.reference_count + 1, lifecycle_status='referenced', expires_at=None, updated_at=now, ) ) db.session.refresh(asset) def release_asset_reference(asset: FileAsset) -> None: """ 原子减少业务引用;派生资产归零后恢复 temporary + TTL,供清理任务回收。 核心逻辑:单条 UPDATE 内用旧值计算新计数与 lifecycle,避免并发少计/多计。 """ now = datetime.utcnow() expires = now + timedelta(hours=_temp_ttl_hours()) # 不用 GREATEST:SQLite 测试库无该函数;CASE 在 PG/SQLite 均可原子计算新计数 new_count = case( (FileAsset.reference_count > 0, FileAsset.reference_count - 1), else_=0, ) db.session.execute( update(FileAsset) .where(FileAsset.id == int(asset.id)) .values( reference_count=new_count, lifecycle_status=case( ( (FileAsset.reference_count <= 1) & (FileAsset.asset_role == 'derived_attachment'), 'temporary', ), ( FileAsset.reference_count > 1, 'referenced', ), else_=FileAsset.lifecycle_status, ), expires_at=case( ( (FileAsset.reference_count <= 1) & (FileAsset.asset_role == 'derived_attachment'), expires, ), ( FileAsset.reference_count > 1, None, ), else_=FileAsset.expires_at, ), updated_at=now, ) ) db.session.refresh(asset) def _persist_orphan_storage_key_for_cleanup( *, storage_key: str, owner_user_id: int | None, storage_bucket: str | None, ) -> None: """ 补偿删除失败时写入可被 cleanup 回收的孤儿资产行。 核心逻辑:使用独立 Session,避免污染调用方 Session;标记 expired + orphan_cleanup。 """ now = datetime.utcnow() owner = int(owner_user_id or 0) if owner <= 0: # 无可用所有者时仍记录日志即可,不强写无主行 _LOGGER.error( 'orphan minio key has no owner_user_id; cannot persist cleanup row key=%s', storage_key, ) return bind = db.session.get_bind() if bind is None: _LOGGER.error('orphan persist skipped: no DB bind for key=%s', storage_key) return row = FileAsset( asset_no=generate_asset_no(), owner_user_id=owner, parent_asset_id=None, asset_role='orphan_cleanup', source_attachment_key=None, original_filename='orphan.bin', storage_provider='minio', storage_bucket=str(storage_bucket or file_asset_storage.bucket_name)[:128], storage_key=storage_key[:512], content_hash=hashlib.sha256(storage_key.encode('utf-8')).hexdigest(), file_size=0, mime_type='application/octet-stream', extension='bin', upload_status='ready', lifecycle_status='expired', reference_count=0, expires_at=now, deleted_at=None, ) with Session(bind=bind) as orphan_session: orphan_session.add(row) orphan_session.commit() def compensate_uploaded_storage_keys( storage_keys: list[str] | None, *, owner_user_id: int | None = None, storage_bucket: str | None = None, ) -> None: """ 事务失败后尽力删除本轮新上传的 MinIO 对象。 核心逻辑:删除失败则 error 日志 + 独立 Session 写入 orphan_cleanup; 台账写入失败会 rollback 调用方 Session,避免 PendingRollbackError。 Args: storage_keys: create_derived 写入的 storage_key 列表。 owner_user_id: 孤儿行归属用户;缺省时仅打日志。 storage_bucket: MinIO bucket;缺省用配置桶。 """ for key in storage_keys or []: normalized = str(key or '').strip() if not normalized: continue try: file_asset_storage.delete_object(normalized) except Exception: _LOGGER.exception('failed to compensate-delete minio object key=%s', normalized) try: _persist_orphan_storage_key_for_cleanup( storage_key=normalized, owner_user_id=owner_user_id, storage_bucket=storage_bucket, ) except Exception: _LOGGER.exception( 'failed to persist orphan cleanup row for minio key=%s', normalized, ) try: db.session.rollback() except Exception: _LOGGER.exception( 'failed to rollback session after orphan persist error key=%s', normalized, ) 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)