Files
work-volume-tracker/app/services/document_artifact_service.py
2026-09-29 18:17:36 +03:00

393 lines
13 KiB
Python

"""Document artifact service: hash, persist, resolve, invalidate.
Implements the service layer for DocumentArtifact (DOC-B1):
DTO / bytes -> Artifact Service -> hash / persist / resolve / invalidate
Transaction ownership: the service does NOT commit. The caller manages the
database transaction. Filesystem writes use compensating cleanup on failure.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import tempfile
from dataclasses import asdict, is_dataclass
from datetime import date, datetime
from decimal import Decimal
from pathlib import Path
from typing import Any
from sqlalchemy import select, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.config import document_storage_root
from app.models.document_artifact import DocumentArtifact
_ZERO_DECIMAL = Decimal("0")
class DocumentArtifactError(ValueError):
"""Domain error raised by the artifact service."""
class ArtifactNotFoundError(DocumentArtifactError):
"""Artifact row or physical file is missing."""
class ArtifactPathError(DocumentArtifactError):
"""storage_key is unsafe or escapes the storage root."""
class ArtifactHashMismatchError(DocumentArtifactError):
"""Physical file content does not match the recorded content_hash."""
# ---------------------------------------------------------------------------
# Hashing
# ---------------------------------------------------------------------------
def compute_content_hash(content: bytes) -> str:
"""SHA-256 of raw bytes as a 64-char lowercase hex string."""
return hashlib.sha256(content).hexdigest()
def _canonicalize(value: Any) -> Any:
"""Convert a value into a deterministic JSON-safe structure."""
if is_dataclass(value) and not isinstance(value, type):
return _canonicalize(asdict(value))
if isinstance(value, dict):
return {str(k): _canonicalize(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [_canonicalize(v) for v in value]
if isinstance(value, Decimal):
# Normalize to a plain decimal string without exponent noise.
text = format(value, "f")
if "." in text:
text = text.rstrip("0").rstrip(".")
return text
if isinstance(value, datetime):
return value.isoformat()
if isinstance(value, date):
return value.isoformat()
if isinstance(value, (str, int, float, bool)) or value is None:
return value
raise DocumentArtifactError(
f"Unsupported type for canonical input hash: {type(value)!r}"
)
def canonical_json(dto: Any) -> str:
"""Deterministic JSON: sorted keys, Decimal/date as strings, UTF-8."""
return json.dumps(
_canonicalize(dto),
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
)
def compute_input_hash(dto: Any, template_type: str, template_version: int) -> str:
"""SHA-256(canonical_json(dto) + template_type + template_version)."""
payload = (
canonical_json(dto)
+ "|"
+ str(template_type)
+ "|"
+ str(int(template_version))
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
# ---------------------------------------------------------------------------
# Storage paths
# ---------------------------------------------------------------------------
_SAFE_SEGMENT = re.compile(r"^[A-Za-z0-9._-]+$")
def _validate_segment(value: Any, label: str) -> str:
text = str(value)
if not _SAFE_SEGMENT.match(text):
raise ArtifactPathError(f"Invalid {label}: {text!r}")
return text
def build_storage_key(
project_id: int,
document_type: str,
document_id: int,
template_type: str,
template_version: int,
extension: str,
when: datetime | None = None,
) -> str:
"""Server-generated relative storage key. Never uses user input."""
project_id = int(project_id)
document_id = int(document_id)
if project_id <= 0 or document_id <= 0:
raise ArtifactPathError("project_id and document_id must be positive")
doc_type = _validate_segment(document_type, "document_type")
template = _validate_segment(template_type, "template_type")
ext = _validate_segment(extension.lstrip("."), "extension")
stamp = (when or datetime.now()).strftime("%Y-%m-%d_%H%M%S_%f")
name = f"{template}_v{int(template_version)}_{stamp}.{ext}"
return (
f"projects/{project_id}/documents/{doc_type}/{document_id}/{name}"
)
def resolve_storage_path(storage_key: str) -> Path:
"""Map a relative storage key to an absolute path inside the storage root."""
if not storage_key or not str(storage_key).strip():
raise ArtifactPathError("storage_key is required")
key = str(storage_key).replace("\\", "/").strip()
if key.startswith("/") or re.match(r"^[A-Za-z]:", key):
raise ArtifactPathError("storage_key must be relative")
if ".." in Path(key).parts:
raise ArtifactPathError("storage_key must not contain '..'")
root = document_storage_root().resolve()
candidate = (root / key).resolve()
try:
candidate.relative_to(root)
except ValueError as exc:
raise ArtifactPathError("storage_key escapes storage root") from exc
return candidate
# ---------------------------------------------------------------------------
# Persist
# ---------------------------------------------------------------------------
def persist_artifact(
db: Session,
*,
project_id: int,
document_type: str,
document_id: int,
format: str,
template_type: str,
template_version: int,
content: bytes,
input_hash: str | None = None,
dto: Any = None,
generated_at: datetime | None = None,
) -> DocumentArtifact:
"""
Store artifact bytes on disk and stage a DocumentArtifact row.
Does NOT commit. The caller owns the transaction. On failure the file
created by this call is removed (compensating cleanup); existing artifacts
are never touched.
"""
if input_hash is None and dto is None:
raise DocumentArtifactError("Either input_hash or dto is required")
if not isinstance(content, (bytes, bytearray)):
raise DocumentArtifactError("content must be bytes")
content = bytes(content)
fmt = _validate_segment(format, "format")
content_hash = compute_content_hash(content)
if input_hash is None:
input_hash = compute_input_hash(dto, template_type, template_version)
storage_key = build_storage_key(
project_id,
document_type,
document_id,
template_type,
template_version,
fmt,
when=generated_at,
)
path = resolve_storage_path(storage_key)
path.parent.mkdir(parents=True, exist_ok=True)
tmp_fd, tmp_name = tempfile.mkstemp(
dir=str(path.parent), prefix=".tmp-artifact-", suffix=f".{fmt}"
)
tmp_path = Path(tmp_name)
try:
with os.fdopen(tmp_fd, "wb") as handle:
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp_path, path)
# Demote any previous current rows for this (type, id, format).
db.execute(
update(DocumentArtifact)
.where(
DocumentArtifact.document_type == document_type,
DocumentArtifact.document_id == document_id,
DocumentArtifact.format == fmt,
DocumentArtifact.is_current.is_(True),
)
.values(is_current=False)
)
artifact = DocumentArtifact(
project_id=project_id,
document_type=document_type,
document_id=document_id,
format=fmt,
storage_key=storage_key,
template_type=template_type,
template_version=int(template_version),
content_hash=content_hash,
input_hash=input_hash,
is_current=True,
generated_at=generated_at or datetime.now(),
)
db.add(artifact)
db.flush()
return artifact
except Exception:
# Compensating cleanup: remove only the file created by this attempt.
try:
if tmp_path.exists():
tmp_path.unlink()
if path.exists():
path.unlink()
except OSError:
pass
raise
# ---------------------------------------------------------------------------
# Resolve
# ---------------------------------------------------------------------------
def _artifact_to_path(artifact: DocumentArtifact) -> Path:
path = resolve_storage_path(artifact.storage_key)
if not path.is_file():
raise ArtifactNotFoundError(
f"Artifact file not found: {artifact.storage_key!r}"
)
return path
def _check_content_hash(path: Path, expected: str) -> bytes:
content = path.read_bytes()
actual = compute_content_hash(content)
if actual != expected:
raise ArtifactHashMismatchError(
"Artifact file content does not match recorded hash"
)
return content
def resolve_artifact(
db: Session,
*,
project_id: int,
document_type: str,
document_id: int,
format: str,
verify_hash: bool = True,
) -> tuple[DocumentArtifact, bytes]:
"""Resolve the current artifact and return (row, bytes)."""
fmt = _validate_segment(format, "format")
artifact = db.execute(
select(DocumentArtifact)
.where(
DocumentArtifact.project_id == project_id,
DocumentArtifact.document_type == document_type,
DocumentArtifact.document_id == document_id,
DocumentArtifact.format == fmt,
DocumentArtifact.is_current.is_(True),
)
.order_by(DocumentArtifact.id.desc())
).scalar_one_or_none()
if artifact is None:
raise ArtifactNotFoundError(
f"No current artifact for {document_type}:{document_id} ({fmt})"
)
path = _artifact_to_path(artifact)
content = _check_content_hash(path, artifact.content_hash) if verify_hash else path.read_bytes()
return artifact, content
def resolve_artifact_by_id(
db: Session,
*,
artifact_id: int,
project_id: int,
verify_hash: bool = True,
) -> tuple[DocumentArtifact, bytes]:
"""Resolve a historical artifact by id, always scoped to a project."""
artifact = db.get(DocumentArtifact, artifact_id)
if artifact is None:
raise ArtifactNotFoundError(f"Artifact {artifact_id} not found")
if artifact.project_id != project_id:
raise DocumentArtifactError(
f"Artifact {artifact_id} does not belong to project {project_id}"
)
path = _artifact_to_path(artifact)
content = _check_content_hash(path, artifact.content_hash) if verify_hash else path.read_bytes()
return artifact, content
# ---------------------------------------------------------------------------
# Invalidate
# ---------------------------------------------------------------------------
def invalidate_artifacts(
db: Session,
*,
project_id: int,
document_type: str,
document_id: int,
format: str | None = None,
) -> int:
"""
Mark current artifacts as historical. Idempotent.
Files and rows are not deleted. Returns the number of rows updated.
"""
stmt = (
update(DocumentArtifact)
.where(
DocumentArtifact.project_id == project_id,
DocumentArtifact.document_type == document_type,
DocumentArtifact.document_id == document_id,
DocumentArtifact.is_current.is_(True),
)
.values(is_current=False)
)
if format is not None:
stmt = stmt.where(DocumentArtifact.format == _validate_segment(format, "format"))
result = db.execute(stmt)
return int(result.rowcount or 0)
# ---------------------------------------------------------------------------
# Cleanup helper (for failed transactions)
# ---------------------------------------------------------------------------
def remove_artifact_file(artifact: DocumentArtifact) -> bool:
"""
Delete the physical file of a single artifact row.
Narrowly scoped cleanup for a failed transaction that created an artifact
file but could not commit. Accepts only a DocumentArtifact row (never an
arbitrary path). Resolves through the safe path resolver. Never touches
other artifacts. Returns True if a file was removed.
"""
if artifact is None or not artifact.storage_key:
return False
try:
path = resolve_storage_path(artifact.storage_key)
except ArtifactPathError:
return False
try:
if path.is_file():
path.unlink()
return True
except OSError:
return False
return False