148 lines
5.3 KiB
Markdown
148 lines
5.3 KiB
Markdown
# 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 не выполнять.**
|