feat(shipping-notice): 新增发货通知重复检测与处理接口,支持重复决策保存与重新执行检测

This commit is contained in:
hugo committed 2026-07-14 21:12:36 +08:00
1 parent 729546a7b7
commit ceb49461e8
72 files changed
+14270 -460

No files matched your search

+439 -6
View File
@@ -3,12 +3,15 @@ backend/app/services/file_assets/service.py
用途:FileAsset 业务编排(校验、哈希、落库、鉴权、生命周期)。
依赖:file_assets.storage、models.FileAsset、Flask current_app。
逻辑:由 /api/files 与 shipping intake 调用;storage_key 不向前端返回。
逻辑:由 /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
@@ -17,6 +20,9 @@ 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
@@ -26,6 +32,26 @@ 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',
@@ -58,6 +84,21 @@ def _build_storage_key(*, user_id: int, asset_no: str, filename: str) -> str:
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,
@@ -67,6 +108,9 @@ def _serialize_asset(asset: FileAsset) -> dict[str, Any]:
'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),
}
@@ -121,6 +165,9 @@ def upload_file_asset(*, user_id: int, upload: FileStorage) -> dict[str, Any]:
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,
@@ -148,12 +195,398 @@ def upload_file_asset(*, user_id: int, upload: FileStorage) -> dict[str, Any]:
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
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] SAVEPOINT:唯一约束冲突时只回滚本插入,保留外层 Document 事务
try:
with db.session.begin_nested():
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: