feat: add document artifact service for hash, persist, resolve, and invalidate

This commit is contained in:
Арсентьев Александр
2026-09-29 16:17:54 +03:00
parent adc92e3460
commit cddde114fe
4 changed files with 1216 additions and 0 deletions
+364
View File
@@ -0,0 +1,364 @@
"""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)
@@ -0,0 +1,101 @@
# Implementation Report — DOC-B2-document-artifact-service
### Status
DONE
### API
`app/services/document_artifact_service.py`:
| Функция | Назначение |
|---|---|
| `compute_content_hash(bytes) -> str` | SHA-256 → 64-char hex |
| `compute_input_hash(dto, template_type, template_version) -> str` | SHA-256(canonical_json + type + version) |
| `canonical_json(dto) -> str` | deterministic JSON |
| `build_storage_key(...)` | server-generated relative key |
| `resolve_storage_path(storage_key)` | key → Path inside storage root (с защитой) |
| `persist_artifact(db, *, ...) -> DocumentArtifact` | bytes → файл + строка (без commit) |
| `resolve_artifact(db, *, ...) -> (row, bytes)` | current artifact |
| `resolve_artifact_by_id(db, *, ...) -> (row, bytes)` | historical, проверка project_id |
| `invalidate_artifacts(db, *, ...) -> int` | current → false, idempotent |
Ошибки: `DocumentArtifactError`, `ArtifactNotFoundError`, `ArtifactPathError`, `ArtifactHashMismatchError`.
### Canonicalization
- `sort_keys=True`, separators `(",", ":")`, UTF-8;
- Decimal → строка без экспоненты (нормализация trailing zeros);
- date/datetime → ISO;
- dataclass → `asdict` (рекурсивно);
- dict/list — рекурсивно;
- ORM-модели не поддерживаются (намеренно).
### Storage
`<storage_root>/projects/<project_id>/documents/<document_type>/<document_id>/<template>_v<N>_<timestamp>.<ext>`
- имя формирует только сервер (`build_storage_key`);
- `storage_key` — относительный, без `..`, без абсолютных путей;
- `resolve_storage_path` проверяет `resolve().relative_to(root)`.
### Transaction ownership
Сервис **не делает commit**. Caller управляет транзакцией (в отличие от части legacy-сервисов проекта — выбран приоритет задачи, закреплён тестом `test_persist_no_internal_commit`). После rollback строки нет.
### Atomicity (compensating cleanup)
1. временный файл (`tempfile.mkstemp` в целевой папке);
2. `fsync` + `os.replace` (атомарная подмена);
3. demote старых current + insert новой строки (`flush`);
4. при любой ошибке: удалить tmp и файл текущей попытки; существующие artifacts не трогать.
Ограничение: если caller делает rollback **после** возврата сервиса, файл уже записан — сервис об этом не знает. Зафиксировано: для issued-сценария caller должен commit'ить; при rollback удалять файл вручную (B5/B8).
### Resolve / security
- current: `project_id + document_type + document_id + format`, `is_current = true`;
- historical: `artifact_id` + **обязательная** проверка `project_id`;
- файл обязан существовать;
- `content_hash` проверяется по умолчанию (`verify_hash=True`);
- traversal / absolute / `..` → `ArtifactPathError`.
### Invalidate
- `is_current = false` для current-строк;
- historical не меняются;
- `format=None` — все форматы; иначе — только указанный;
- файлы и строки не удаляются;
- idempotent (повтор → 0).
### Тесты
`tests/test_doc_b2_artifact_service.py` — **23 теста** (все пункты §9):
hash (7), persist (8), resolve (6), invalidate (6). Включая no-commit, DB-failure cleanup, hash mismatch, path traversal.
Результат `pytest -q`:
```
358 passed, 284 warnings in 31.35s
```
(335 существующих + 23 новых.)
Результат `git diff --check`:
```
(без ошибок)
```
Запуск приложения: проверен в B1, модель не менялась.
### Deviations
- Сервис не делает `commit` (приоритет задачи), тогда как `daily_report_service` / `payment_service` делают. При вызове из B5 нужно учитывать это и коммитить на уровне вызова.
- Файл остаётся на диске при rollback caller'а после возврата сервиса — ограничение компенсирующего cleanup (см. выше).
### Follow-up для DOC-B3 / DOC-B4
- Renderer'ы будут вызывать `persist_artifact` с `content=render_bytes`, `dto=KS2ExportDocument/KS3ExportDocument`.
- Hash DTO уже поддерживает dataclass (`asdict`).
- Для issued: один `persist_artifact` при `issue_*`, далее `resolve_artifact` без перегенерации.
@@ -0,0 +1,147 @@
# DOC-B2 — Artifact Service
## Цель
Реализовать сервисный слой для `DocumentArtifact` из DOC-B1:
`DTO / bytes → Artifact Service → hash / persist / resolve / invalidate`
Не реализовывать renderer, шаблоны, UI, issue-интеграцию, Export/Import или Database Reset.
## 1. Service API
Создать `app/services/document_artifact_service.py` (либо эквивалентное место по стилю проекта):
- `compute_content_hash(bytes) -> str`
- `compute_input_hash(dto, template_type, template_version) -> str`
- `persist_artifact(...)`
- `resolve_artifact(...)`
- `invalidate_artifacts(...)`
Конкретные сигнатуры — по стилю проекта.
## 2. Content hash
SHA-256 bytes → 64-char hex. Не писать файл для вычисления hash.
## 3. Canonical input hash
Правило:
`SHA256(canonical_json(DTO) + template_type + template_version)`
Canonical JSON:
- `sort_keys=True`;
- Decimal → string;
- date/datetime → ISO;
- UTF-8;
- deterministic;
- порядок ключей исходного dict не влияет.
Поддержать dict, dataclass DTO, вложенные dict/list, Decimal, date/datetime. Не использовать `str()`/`repr()` ORM-модели.
## 4. persist
Вход: project_id, document_type/id, format, template_type/version, bytes, input_hash или DTO, Session.
Создавать:
`<storage_root>/projects/<project_id>/documents/<document_type>/<document_id>/`
Storage key — относительный. Имя формируется сервером, например:
`ks2_act_v1_2026-09-29_143012.xlsx`
Порядок:
1. content_hash;
2. input_hash;
3. безопасная временная запись;
4. DB artifact;
5. старый current того же `(type,id,format)` → false;
6. новый → true.
Не использовать пользовательский путь.
**Transaction ownership:** предпочтительно сервис не делает commit; caller управляет transaction. Если текущий проект устроен иначе — следовать существующему паттерну и описать в отчёте.
## 5. Atomicity
SQLite и FS не имеют общей транзакции. Использовать compensating cleanup:
- временный файл;
- при DB failure/rollback удалить только файл текущей попытки;
- существующие artifacts не удалять.
За внешний commit/rollback, если он происходит после возврата сервиса, сервис автоматически отвечать не может — зафиксировать ограничение.
## 6. resolve
Поддержать:
1. current по project_id + document_type + document_id + format;
2. historical по artifact_id с обязательной проверкой project_id.
Проверять наличие artifact и физического файла.
Путь:
`(storage_root / storage_key).resolve()` должен оставаться внутри storage root.
Запретить absolute path, `..`, traversal и выход за root.
Проверять `content_hash` файла по умолчанию. Несовпадение → domain/service error, файл не отдавать.
## 7. invalidate
`invalidate_artifacts(session, project_id, document_type, document_id, format=None)`
- current → false;
- historical не менять;
- `format=None` → все форматы;
- задан format → только его;
- файлы и DB rows не удалять;
- idempotent;
- commit — по transaction pattern проекта.
## 8. Current
Учитывать partial unique index B1. При IntegrityError из-за гонки:
- старые artifacts не удалять;
- удалить только файл текущей попытки;
- понятная ошибка вверх;
- сложный retry не реализовывать.
## 9. Tests
Добавить минимум:
### Hash
1 identical content;
2 different content;
3 dict key order;
4 Decimal;
5 date/datetime;
6 dataclass;
7 nested list/dict.
### Persist
8 storage directory;
9 physical file;
10 DB row;
11 content_hash;
12 input_hash;
13 new current;
14 old current becomes historical;
15 history preserved;
16 different formats can both be current;
17 no internal commit;
18 DB failure cleans created file.
### Resolve
19 current;
20 historical;
21 wrong project rejected;
22 missing file;
23 modified file/hash mismatch;
24 traversal/root escape.
### Invalidate
25 current false;
26 historical unchanged;
27 one format only;
28 all formats;
29 repeat safe;
30 files remain.
## 10. Не делать
Renderer, templates, UI, HTTP download, issue/lifecycle changes, Export/Import, Reset, project-storage cleanup, watermark, PDF, signature.
## 11. Проверка
`pytest -q`
`git diff --check`
Проверить запуск приложения. Browser smoke не требуется.
## 12. Отчёт
Создать `docs/implementation/DOC-B2-document-artifact-service.md` с API, canonicalization, storage, transaction ownership, atomicity, resolve/security, invalidate, тестами, pytest, diff-check, deviations и follow-up B3/B4.
**Commit/push не выполнять.**
+604
View File
@@ -0,0 +1,604 @@
"""Tests for DOC-B2: document artifact service."""
from __future__ import annotations
import hashlib
from dataclasses import dataclass
from datetime import date, datetime
from decimal import Decimal
from pathlib import Path
import pytest
from sqlalchemy import create_engine, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.config import ENV_DOCUMENT_STORAGE_ROOT
from app.database.database import Base
from app.models import ( # noqa: F401 — register mappers
agreement,
boq,
daily_report,
document_artifact,
ks2,
ks3,
payment,
project,
work_journal,
)
from app.models.document_artifact import DocumentArtifact
from app.models.project import Project
from app.services.document_artifact_service import (
ArtifactHashMismatchError,
ArtifactNotFoundError,
ArtifactPathError,
DocumentArtifactError,
build_storage_key,
canonical_json,
compute_content_hash,
compute_input_hash,
invalidate_artifacts,
persist_artifact,
resolve_artifact,
resolve_artifact_by_id,
resolve_storage_path,
)
@dataclass(frozen=True)
class SampleDto:
name: str
amount: Decimal
when: date
@pytest.fixture
def storage_root(tmp_path, monkeypatch):
root = tmp_path / "artifact-storage"
monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(root))
return root
@pytest.fixture
def db_session():
engine = create_engine(
"sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool
)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine, expire_on_commit=False)
session = Session()
try:
yield session
finally:
session.close()
engine.dispose()
@pytest.fixture
def project_id(db_session):
p = Project(name="Artifact service")
db_session.add(p)
db_session.commit()
return p.id
# ---------------------------------------------------------------------------
# Hash
# ---------------------------------------------------------------------------
def test_content_hash_identical():
assert compute_content_hash(b"abc") == compute_content_hash(b"abc")
assert compute_content_hash(b"abc") == hashlib.sha256(b"abc").hexdigest()
def test_content_hash_different():
assert compute_content_hash(b"abc") != compute_content_hash(b"abd")
def test_input_hash_dict_key_order_irrelevant():
a = compute_input_hash({"a": 1, "b": 2}, "ks2_act", 1)
b = compute_input_hash({"b": 2, "a": 1}, "ks2_act", 1)
assert a == b
def test_input_hash_decimal_canonical():
a = compute_input_hash({"v": Decimal("1.50")}, "t", 1)
b = compute_input_hash({"v": Decimal("1.5")}, "t", 1)
assert a == b
assert a != compute_input_hash({"v": Decimal("1.51")}, "t", 1)
def test_input_hash_date_datetime():
d1 = compute_input_hash({"d": date(2026, 1, 2)}, "t", 1)
d2 = compute_input_hash({"d": date(2026, 1, 2)}, "t", 1)
assert d1 == d2
assert d1 != compute_input_hash({"d": date(2026, 1, 3)}, "t", 1)
dt1 = compute_input_hash({"t": datetime(2026, 1, 2, 3, 4, 5)}, "t", 1)
dt2 = compute_input_hash({"t": datetime(2026, 1, 2, 3, 4, 5)}, "t", 1)
assert dt1 == dt2
def test_input_hash_dataclass():
dto = SampleDto(name="X", amount=Decimal("2.5"), when=date(2026, 1, 1))
a = compute_input_hash(dto, "ks2_act", 1)
b = compute_input_hash(
{"name": "X", "amount": Decimal("2.5"), "when": date(2026, 1, 1)}, "ks2_act", 1
)
assert a == b
def test_input_hash_nested_list_dict():
dto = {"items": [{"a": 1, "b": [Decimal("3"), date(2026, 1, 1)]}]}
a = compute_input_hash(dto, "t", 1)
b = compute_input_hash({"items": [{"b": [Decimal("3.0"), date(2026, 1, 1)], "a": 1}]}, "t", 1)
assert a == b
assert a != compute_input_hash({"items": [{"a": 1, "b": [Decimal("3.1"), date(2026, 1, 1)]}]}, "t", 1)
# ---------------------------------------------------------------------------
# Persist
# ---------------------------------------------------------------------------
def test_persist_creates_directory_file_and_row(storage_root, db_session, project_id):
art = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=15,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"hello-bytes",
dto={"n": 1},
)
path = resolve_storage_path(art.storage_key)
assert path.is_file()
assert path.read_bytes() == b"hello-bytes"
assert path.parent == (
storage_root.resolve()
/ "projects"
/ str(project_id)
/ "documents"
/ "ks2"
/ "15"
)
assert art.content_hash == compute_content_hash(b"hello-bytes")
assert art.input_hash == compute_input_hash({"n": 1}, "ks2_act", 1)
assert art.is_current is True or art.is_current == 1
assert art.project_id == project_id
# service does not commit
assert art.id is not None # flushed
assert db_session.in_transaction()
def test_persist_no_internal_commit(storage_root, db_session, project_id):
persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=1,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"x",
dto={},
)
# Row is visible in this session (flush) but caller still owns the tx
assert db_session.in_transaction()
db_session.rollback()
# After rollback the row is gone — proving no commit happened
assert db_session.execute(select(DocumentArtifact)).all() == []
def test_persist_new_current_and_old_becomes_historical(storage_root, db_session, project_id):
old = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=3,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"v1",
dto={},
)
old_id = old.id
new = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=3,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"v2",
dto={},
)
db_session.commit()
db_session.refresh(old)
db_session.refresh(new)
assert old.is_current in (False, 0)
assert new.is_current in (True, 1)
# History preserved
assert db_session.get(DocumentArtifact, old_id) is not None
assert resolve_storage_path(old.storage_key).is_file()
assert resolve_storage_path(new.storage_key).is_file()
def test_persist_different_formats_both_current(storage_root, db_session, project_id):
a = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=4,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"excel",
dto={},
)
b = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=4,
format="pdf",
template_type="ks2_act",
template_version=1,
content=b"pdf",
dto={},
)
db_session.commit()
assert a.is_current in (True, 1)
assert b.is_current in (True, 1)
def test_persist_db_failure_cleans_created_file(storage_root, db_session, project_id, monkeypatch):
persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=5,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"first",
dto={},
)
db_session.commit()
first = resolve_storage_path(
db_session.execute(select(DocumentArtifact)).scalar_one().storage_key
)
assert first.is_file()
def boom(*args, **kwargs):
raise RuntimeError("forced db failure")
monkeypatch.setattr(db_session, "flush", boom)
with pytest.raises(RuntimeError, match="forced db failure"):
persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=5,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"should-be-cleaned",
dto={},
)
monkeypatch.undo()
db_session.rollback()
after_files = list((storage_root / "projects").rglob("*.xlsx"))
leaked = [p for p in after_files if p.read_bytes() == b"should-be-cleaned"]
assert leaked == []
# Existing artifact file is untouched
assert first.is_file()
assert first.read_bytes() == b"first"
# ---------------------------------------------------------------------------
# Resolve
# ---------------------------------------------------------------------------
def test_resolve_current(storage_root, db_session, project_id):
persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=7,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"current-bytes",
dto={},
)
db_session.commit()
art, content = resolve_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=7,
format="xlsx",
)
assert content == b"current-bytes"
assert art.document_id == 7
def test_resolve_historical_by_id(storage_root, db_session, project_id):
old = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=8,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"old",
dto={},
)
db_session.commit()
old_id = old.id
persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=8,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"new",
dto={},
)
db_session.commit()
art, content = resolve_artifact_by_id(
db_session, artifact_id=old_id, project_id=project_id
)
assert content == b"old"
assert art.is_current in (False, 0)
def test_resolve_wrong_project_rejected(storage_root, db_session, project_id):
art = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=9,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"data",
dto={},
)
db_session.commit()
with pytest.raises(DocumentArtifactError, match="does not belong"):
resolve_artifact_by_id(
db_session, artifact_id=art.id, project_id=project_id + 999
)
with pytest.raises(ArtifactNotFoundError):
resolve_artifact(
db_session,
project_id=project_id + 999,
document_type="ks2",
document_id=9,
format="xlsx",
)
def test_resolve_missing_file(storage_root, db_session, project_id):
art = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=10,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"soon-deleted",
dto={},
)
db_session.commit()
resolve_storage_path(art.storage_key).unlink()
with pytest.raises(ArtifactNotFoundError, match="not found"):
resolve_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=10,
format="xlsx",
)
def test_resolve_hash_mismatch(storage_root, db_session, project_id):
art = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=11,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"original",
dto={},
)
db_session.commit()
path = resolve_storage_path(art.storage_key)
path.write_bytes(b"tampered")
with pytest.raises(ArtifactHashMismatchError):
resolve_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=11,
format="xlsx",
)
def test_resolve_path_traversal_rejected(storage_root, db_session, project_id):
with pytest.raises(ArtifactPathError):
resolve_storage_path("../secret.txt")
with pytest.raises(ArtifactPathError):
resolve_storage_path("/etc/passwd")
with pytest.raises(ArtifactPathError):
resolve_storage_path("projects/1/../../../etc/passwd")
with pytest.raises(ArtifactPathError):
resolve_storage_path("")
# ---------------------------------------------------------------------------
# Invalidate
# ---------------------------------------------------------------------------
def test_invalidate_current(storage_root, db_session, project_id):
art = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=20,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"a",
dto={},
)
db_session.commit()
updated = invalidate_artifacts(
db_session,
project_id=project_id,
document_type="ks2",
document_id=20,
format="xlsx",
)
db_session.commit()
assert updated == 1
db_session.refresh(art)
assert art.is_current in (False, 0)
# file remains
assert resolve_storage_path(art.storage_key).is_file()
def test_invalidate_leaves_historical_unchanged(storage_root, db_session, project_id):
old = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=21,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"old",
dto={},
)
db_session.commit()
old_id = old.id
persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=21,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"new",
dto={},
)
db_session.commit()
# old is already historical
row = db_session.get(DocumentArtifact, old_id)
assert row.is_current in (False, 0)
invalidate_artifacts(
db_session,
project_id=project_id,
document_type="ks2",
document_id=21,
format="xlsx",
)
db_session.commit()
assert db_session.get(DocumentArtifact, old_id).is_current in (False, 0)
def test_invalidate_one_format_only(storage_root, db_session, project_id):
xlsx = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=22,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"x",
dto={},
)
pdf = persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=22,
format="pdf",
template_type="ks2_act",
template_version=1,
content=b"p",
dto={},
)
db_session.commit()
invalidate_artifacts(
db_session,
project_id=project_id,
document_type="ks2",
document_id=22,
format="xlsx",
)
db_session.commit()
db_session.refresh(xlsx)
db_session.refresh(pdf)
assert xlsx.is_current in (False, 0)
assert pdf.is_current in (True, 1)
def test_invalidate_all_formats(storage_root, db_session, project_id):
for fmt in ("xlsx", "pdf"):
persist_artifact(
db_session,
project_id=project_id,
document_type="ks3",
document_id=23,
format=fmt,
template_type="ks3_act",
template_version=1,
content=f"b-{fmt}".encode(),
dto={},
)
db_session.commit()
updated = invalidate_artifacts(
db_session,
project_id=project_id,
document_type="ks3",
document_id=23,
)
db_session.commit()
assert updated == 2
assert (
db_session.execute(
select(DocumentArtifact).where(DocumentArtifact.is_current.is_(True))
).all()
== []
)
def test_invalidate_idempotent(storage_root, db_session, project_id):
persist_artifact(
db_session,
project_id=project_id,
document_type="ks2",
document_id=24,
format="xlsx",
template_type="ks2_act",
template_version=1,
content=b"z",
dto={},
)
db_session.commit()
assert invalidate_artifacts(
db_session, project_id=project_id, document_type="ks2", document_id=24
) == 1
db_session.commit()
assert invalidate_artifacts(
db_session, project_id=project_id, document_type="ks2", document_id=24
) == 0
db_session.commit()