"""在途调拨 MinIO 归档与 Hash 校验。 用途:将大型快照/报文/Excel 归档到对象存储(MinIO),索引与 Hash 留库; 归档必须重新计算 Hash 并写审计事件(决策/规格 §11.3)。 依赖:typing.Protocol 对象存储协议、models.TransferArchive、audit。 逻辑:默认实现 MinioObjectStore 直连 MinIO(配置来自环境);测试注入 Fake。 凭据只来自环境/配置,绝不写入归档内容或索引。 """ from __future__ import annotations import hashlib import io import uuid from datetime import datetime from typing import Any, Protocol from app import db from app.core.errors import AppError from app.models import TransferArchive from app.services.in_transit_transfer.audit import build_transfer_audit_event ARCHIVE_STORAGE_PROVIDER = "minio" DEFAULT_ARCHIVE_BUCKET = "hxops-transfer" class ObjectStore(Protocol): """对象存储协议(MinIO 或测试替身)。""" def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str: """写入对象,返回对象键。""" def get_bytes(self, *, bucket: str, key: str) -> bytes: """读取对象字节。""" def delete_object(self, *, bucket: str, key: str) -> None: """删除对象。""" class MinioObjectStore: """默认 MinIO 对象存储;凭据仅来自 Flask config / 环境变量。""" def __init__(self, bucket: str = DEFAULT_ARCHIVE_BUCKET) -> None: from flask import current_app self.bucket = str(current_app.config.get("IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET") or bucket) endpoint = str(current_app.config.get("MINIO_ENDPOINT") or "").strip() access_key = str(current_app.config.get("MINIO_ACCESS_KEY") or "").strip() secret_key = str(current_app.config.get("MINIO_SECRET_KEY") or "").strip() secure = bool(current_app.config.get("MINIO_SECURE", False)) if not endpoint: raise AppError( code="TRANSFER.ARCHIVE_NOT_CONFIGURED", message="MinIO endpoint not configured", http_status=503, ) from minio import Minio self.client = Minio(endpoint, access_key=access_key, secret_key=secret_key, secure=secure) def _ensure_bucket(self) -> None: """确保 bucket 存在(幂等)。""" if not self.client.bucket_exists(self.bucket): self.client.make_bucket(self.bucket) def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str: """写入对象并返回键。""" self._ensure_bucket() self.client.put_object( bucket_name=bucket or self.bucket, object_name=key, data=io.BytesIO(data), length=len(data), content_type=content_type, ) return key def get_bytes(self, *, bucket: str, key: str) -> bytes: """读取对象字节。""" response = self.client.get_object(bucket_name=bucket or self.bucket, object_name=key) try: return response.read() finally: response.close() response.release_conn() def delete_object(self, *, bucket: str, key: str) -> None: """删除对象。""" self.client.remove_object(bucket_name=bucket or self.bucket, object_name=key) def _safe_filename(name: str) -> str: """清洗文件名片段。""" return "".join(char for char in str(name or "archive") if char.isalnum() or char in {"-", "_", "."}) or "archive" def archive_snapshot( *, object_type: str, object_id: str, data: bytes, original_filename: str, content_type: str, object_store: ObjectStore, bucket: str = DEFAULT_ARCHIVE_BUCKET, request_id: str | None = None, ) -> TransferArchive: """归档一份对象并持久化索引 + 审计。 Args: object_type: 对象类型(external_inventory_snapshot / exception_excel / inbound_file)。 object_id: 业务对象编号(matching_no / run_no)。 data: 待归档字节。 original_filename: 原始文件名。 content_type: MIME。 object_store: 对象存储替身。 bucket: 目标 bucket。 Returns: TransferArchive 索引记录。 """ digest = hashlib.sha256(data).hexdigest() key = ( f"{object_type}/{object_id}/{datetime.utcnow():%Y%m%d}/" f"{uuid.uuid4().hex[:8]}-{_safe_filename(original_filename)}" ) object_store.put_bytes(bucket=bucket, key=key, data=data, content_type=content_type) archive = TransferArchive( archive_no=f"ARC-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:6].upper()}", object_type=object_type, object_id=object_id, storage_provider=ARCHIVE_STORAGE_PROVIDER, storage_bucket=bucket, storage_key=key, original_filename=original_filename, content_type=content_type, file_size=len(data), sha256=digest, ) db.session.add(archive) db.session.add(build_transfer_audit_event( event_type="TRANSFER_ARCHIVED", aggregate_type=object_type, aggregate_id=object_id, actor_type="worker", request_id=request_id, result="success", after={"storage_key": key, "sha256": digest, "file_size": len(data)}, )) db.session.commit() return archive def verify_archive_hash(archive: TransferArchive, *, object_store: ObjectStore) -> bool: """复核归档 Hash(下载对象重新计算)。 Args: archive: TransferArchive 索引。 object_store: 对象存储替身。 Returns: True 一致;False 损坏/篡改。 """ data = object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key) return hashlib.sha256(data).hexdigest() == archive.sha256 def restore_archive_bytes(archive: TransferArchive, *, object_store: ObjectStore) -> bytes: """恢复归档对象字节。""" return object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key)