Files
syops/backend/app/services/procurement_contract/artifact_archive.py
T
sophie 9bcbf9d211 fix(contract): 优化合同审核方案
(cherry picked from commit bdb2c3113efe87604244a24258cd973955dce544)
2026-08-05 10:20:31 +08:00

224 lines
8.0 KiB
Python

"""
backend/app/services/procurement_contract/artifact_archive.py
用途:将采购合同审核的本地运行产物归档至私有 MinIO,并在本地缓存缺失时按需恢复。
依赖:Flask current_app、minio、procurement_contract.preprocessing 的审查目录约定。
逻辑:审核完成后先上传所有文件,再上传 manifest;manifest 成功后本地目录可安全清理,
后续标注合同或 OCR 页码定位通过 manifest 从 MinIO 恢复所需文件。
"""
from __future__ import annotations
import hashlib
import io
import json
import logging
import mimetypes
import shutil
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from flask import current_app
from minio import Minio
from minio.error import S3Error
_LOGGER = logging.getLogger(__name__)
_MANIFEST_NAME = "_manifest.json"
def _archive_enabled() -> bool:
"""读取归档开关,关闭时调用方保持本地缓存行为。"""
return bool(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_ENABLED", True))
def _archive_bucket() -> str:
"""获取合同专用私有桶名,拒绝空配置避免误写默认桶。"""
bucket = str(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_BUCKET") or "").strip()
if not bucket:
raise RuntimeError("PROCUREMENT_CONTRACT_ARCHIVE_BUCKET is required")
return bucket
def _archive_client() -> Minio:
"""构造 MinIO 客户端;合同归档不设置 public-read policy。"""
endpoint = str(current_app.config.get("MINIO_ENDPOINT") or "").strip()
if not endpoint:
raise RuntimeError("MINIO_ENDPOINT is required")
return Minio(
endpoint,
access_key=str(current_app.config.get("MINIO_ACCESS_KEY") or ""),
secret_key=str(current_app.config.get("MINIO_SECRET_KEY") or ""),
secure=bool(current_app.config.get("MINIO_SECURE", False)),
)
def _review_root(review_no: str) -> Path:
"""将审查编号限制在存储根目录内,和预处理阶段保持同一目录规则。"""
root = Path(str(current_app.config["PROCUREMENT_CONTRACT_STORAGE_ROOT"])).resolve()
candidate = (root / str(review_no or "").strip()).resolve()
if candidate.parent != root:
raise RuntimeError("invalid review_no")
return candidate
def _object_key(review_no: str, relative_path: Path) -> str:
"""生成稳定对象键,保留审查目录内的相对层级。"""
return f"reviews/{review_no}/{relative_path.as_posix()}"
def _ensure_bucket(client: Minio, bucket: str) -> None:
"""确保私有合同桶存在;禁止继承公开资料桶策略。"""
if not client.bucket_exists(bucket):
client.make_bucket(bucket)
def _file_entry(path: Path, *, root: Path) -> dict[str, Any]:
"""生成可校验的归档清单条目,供恢复时限定允许路径。"""
data = path.read_bytes()
relative = path.relative_to(root)
return {
"path": relative.as_posix(),
"size": len(data),
"sha256": hashlib.sha256(data).hexdigest(),
"content_type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
}
def archive_review_artifacts(review_no: str) -> dict[str, Any]:
"""
上传一份审核的所有本地产物,并最后写入 manifest 作为完整归档提交标记。
Args:
review_no: 已完成审核编号。
Returns:
归档状态、bucket、对象前缀和文件数量;开关关闭时返回 disabled。
Raises:
RuntimeError: 本地目录不存在或 MinIO 上传失败;调用方必须保留本地目录。
"""
if not _archive_enabled():
return {"status": "disabled"}
root = _review_root(review_no)
if not root.is_dir():
raise RuntimeError(f"review artifact directory not found: {review_no}")
files = sorted(
(path for path in root.rglob("*") if path.is_file() and path.name != _MANIFEST_NAME),
key=lambda path: path.relative_to(root).as_posix(),
)
if not files:
raise RuntimeError(f"review artifact directory is empty: {review_no}")
client = _archive_client()
bucket = _archive_bucket()
_ensure_bucket(client, bucket)
entries: list[dict[str, Any]] = []
for path in files:
entry = _file_entry(path, root=root)
data = path.read_bytes()
client.put_object(
bucket,
_object_key(review_no, Path(entry["path"])),
io.BytesIO(data),
len(data),
content_type=entry["content_type"],
)
entries.append(entry)
manifest = {
"review_no": review_no,
"archived_at": datetime.now(timezone.utc).isoformat(),
"files": entries,
}
manifest_data = json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8")
client.put_object(
bucket,
_object_key(review_no, Path(_MANIFEST_NAME)),
io.BytesIO(manifest_data),
len(manifest_data),
content_type="application/json",
)
return {
"status": "archived",
"bucket": bucket,
"prefix": f"reviews/{review_no}/",
"manifest_key": _object_key(review_no, Path(_MANIFEST_NAME)),
"file_count": len(entries),
}
def restore_review_artifact(review_no: str, relative_path: str) -> Path | None:
"""
本地缓存缺失时,从已提交 manifest 的私有归档恢复单个文件。
Args:
review_no: 审查编号。
relative_path: 审查目录下的相对文件路径,不允许绝对路径或父级跳转。
Returns:
已存在或恢复后的本地路径;归档关闭或 manifest 未包含该文件时返回 None。
"""
root = _review_root(review_no)
relative = Path(relative_path)
target = (root / relative).resolve()
if target.parent != root and root not in target.parents:
raise RuntimeError("invalid artifact relative path")
if target.is_file():
return target
if not _archive_enabled():
return None
client = _archive_client()
bucket = _archive_bucket()
try:
response = client.get_object(bucket, _object_key(review_no, Path(_MANIFEST_NAME)))
try:
manifest = json.loads(response.read().decode("utf-8"))
finally:
response.close()
response.release_conn()
allowed = {str(item.get("path")): item for item in manifest.get("files") or [] if isinstance(item, dict)}
entry = allowed.get(relative.as_posix())
if not entry:
return None
response = client.get_object(bucket, _object_key(review_no, relative))
try:
data = response.read()
finally:
response.close()
response.release_conn()
except S3Error as exc:
if exc.code == "NoSuchKey":
# [STEP 1] 审核执行中可选 OCR 坐标不存在时,归档尚未提交属于预期状态,不刷告警。
_LOGGER.debug(
"[contract-review] artifact manifest not ready review_no=%s path=%s",
review_no,
relative,
)
return None
_LOGGER.warning("[contract-review] artifact restore failed review_no=%s path=%s err=%s", review_no, relative, exc)
return None
except Exception as exc:
_LOGGER.warning("[contract-review] artifact restore failed review_no=%s path=%s err=%s", review_no, relative, exc)
return None
if hashlib.sha256(data).hexdigest() != str(entry.get("sha256") or ""):
_LOGGER.warning("[contract-review] artifact checksum mismatch review_no=%s path=%s", review_no, relative)
return None
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
return target
def cleanup_local_review_artifacts(review_no: str) -> bool:
"""仅在归档成功后删除本地运行缓存;由环境开关控制,删除失败不影响归档结果。"""
if not bool(current_app.config.get("PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL", True)):
return False
root = _review_root(review_no)
if not root.is_dir():
return False
shutil.rmtree(root)
return True