forked from mtusi2026/mtusi2026lab4
feat: добавить reconciler PostgreSQL и S3
This commit is contained in:
@@ -4,7 +4,7 @@ CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test test-attachments load load-attachments test-persistence test-failover test-attachment-failover
|
||||
.PHONY: help check validate test test-attachments load load-attachments test-persistence test-failover test-attachment-failover reconcile-dry reconcile-apply benchmark-reconciler
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -38,3 +38,12 @@ test-failover:
|
||||
test-attachment-failover:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
||||
$(PYTHON) tests/attachment_failover.py --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
reconcile-dry:
|
||||
docker compose exec -T api python -m app.tools.reconcile_attachments --dry-run
|
||||
|
||||
reconcile-apply:
|
||||
docker compose exec -T api python -m app.tools.reconcile_attachments --apply
|
||||
|
||||
benchmark-reconciler:
|
||||
./scripts/benchmark-reconciler.sh
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Отчёт — лабораторная 4
|
||||
|
||||
- Автор, группа: Сергей Возжин, БПИ2301.
|
||||
- Целевая оценка: 4; трек 5 не выбран.
|
||||
- Целевая оценка: 5; выбран трек 2 — согласованность PostgreSQL и S3.
|
||||
- Commit/PR: TODO после публикации.
|
||||
- Использованные источники: контракт репозитория, документация Docker Compose, Chainguard Images, MinIO SDK и Pillow.
|
||||
- Библиотеки: FastAPI, Uvicorn, SQLAlchemy, asyncpg, Alembic, redis-py, MinIO Python SDK, Pillow, Argon2, pytest.
|
||||
@@ -57,8 +57,15 @@ docker compose --env-file .env up -d --wait --wait-timeout 60 api lb
|
||||
scripts/check-private-bucket.sh
|
||||
scripts/check-s3-outage.sh
|
||||
.venv/bin/python scripts/measure-upload-memory.py --concurrency 10 --uploads 30
|
||||
make reconcile-dry
|
||||
make benchmark-reconciler
|
||||
```
|
||||
|
||||
Исправления следует сначала просмотреть через `make reconcile-dry`. Изменяющий данные
|
||||
`make reconcile-apply` запускается оператором только после проверки dry-run.
|
||||
`make benchmark-reconciler` сам создаёт 1000 изолированных пар metadata/object,
|
||||
выполняет dry-run и удаляет тестовые данные; объём меняется через `SIZE=...`.
|
||||
|
||||
Каждый failover-тест намеренно оставляет выбранную API-реплику остановленной, поэтому между сценариями и после последнего сценария она явно восстанавливается указанной командой `docker compose up`.
|
||||
|
||||
Безопасная остановка с сохранением данных:
|
||||
@@ -95,7 +102,8 @@ HAProxy :8080
|
||||
- синхронный binary upload PNG/JPEG;
|
||||
- авторизованные metadata/download endpoints;
|
||||
- `attachment_ids` в сообщениях и в области сравнения идемпотентного body;
|
||||
- компенсационное удаление объекта и безопасный cleanup старых orphan-объектов.
|
||||
- компенсационное удаление объекта и безопасный cleanup старых orphan-объектов;
|
||||
- повторяемый reconciler метаданных PostgreSQL и оригиналов S3.
|
||||
|
||||
PostgreSQL является источником истины для метаданных. В БД не хранятся bytes изображения. MinIO хранит оригинал по серверному ключу `originals/<UUID>`. Пользовательский `filename` хранится только как метаданные и не используется в object key или пути файловой системы.
|
||||
|
||||
@@ -130,6 +138,42 @@ docker compose --env-file .env run --rm --no-deps api \
|
||||
|
||||
По умолчанию используется grace period один час; CLI запрещает значения меньше 60 секунд. Объекты с существующими метаданными и свежие orphan-объекты не удаляются. Сначала используется `--dry-run`, затем осознанный `--apply`.
|
||||
|
||||
### Reconciler PostgreSQL/S3 — трек 2
|
||||
|
||||
Расширенный reconciler запускается внутри API-контейнера, где уже есть те же настройки и
|
||||
ограниченные S3 credentials, что у приложения:
|
||||
|
||||
```sh
|
||||
docker compose exec -T api \
|
||||
python -m app.tools.reconcile_attachments --dry-run --grace-seconds 3600
|
||||
docker compose exec -T api \
|
||||
python -m app.tools.reconcile_attachments --apply --grace-seconds 3600
|
||||
```
|
||||
|
||||
Он читает снимок всех `attachments` и список `originals/`, после чего различает:
|
||||
|
||||
- `orphan`: объект S3 есть, но ни одной строки с таким `object_key` нет;
|
||||
- `missing`: строка в состоянии `ready` есть, а оригинала S3 нет;
|
||||
- корректную пару: присутствуют обе стороны;
|
||||
- свежее расхождение: возраст меньше grace period, изменять его нельзя.
|
||||
|
||||
В `--dry-run` выводятся `WOULD_DELETE_ORPHAN` и `WOULD_MARK_MISSING`, но записи и объекты
|
||||
не меняются. В `--apply` старый orphan удаляется, а missing-метаданные сохраняются и
|
||||
переходят в `status=failed`, `error_code=original_missing`. Сообщение и связь с вложением
|
||||
не удаляются. Повторный `--apply` ничего не делает: orphan уже отсутствует, а `failed`
|
||||
больше не считается ожидающим оригинал состоянием. При этом строка `failed` по-прежнему
|
||||
защищает внезапно появившийся объект с тем же ключом от удаления как orphan.
|
||||
|
||||
Grace period защищает upload, который ещё выполняется, и запрещён ниже 60 секунд.
|
||||
Используемые сообщением вложения не имеют особого исключения: любой известный PostgreSQL
|
||||
ключ защищён одинаково, поэтому корректный оригинал связанного сообщения не удаляется.
|
||||
Content для `failed` возвращает 409, а привязать такое вложение к новому сообщению нельзя.
|
||||
|
||||
Операции между двумя хранилищами всё ещё не образуют общей транзакции. Если apply
|
||||
прервётся, уже выполненное безопасное удаление orphan не требует отката, условный SQL
|
||||
UPDATE меняет только всё ещё `ready` строки, а повторный запуск завершает оставшуюся
|
||||
работу.
|
||||
|
||||
### Доступ и идемпотентность
|
||||
|
||||
Метаданные и content доступны любому участнику чата. Неизвестный объект и запрос постороннего одинаково возвращают 404. Download идёт через API без redirect. Публичный ответ не раскрывает object key, endpoint или credentials.
|
||||
@@ -152,6 +196,9 @@ docker compose --env-file .env run --rm --no-deps api \
|
||||
| Concurrency/RAM | `scripts/measure-upload-memory.py --concurrency 10 --uploads 30` | 30/30 upload, обе реплики, пики 68,50/68,33 MiB | `evidence/upload-memory.json` |
|
||||
| Идемпотентный bootstrap | повторный запуск `docker compose up` после restart/failover | bootstrap повторно завершился с code 0 | `evidence/results.md` |
|
||||
| Cleanup dry-run | `cleanup_orphans --dry-run --grace-seconds 60` | 164 известных объекта, удалено 0 | `evidence/results.md` |
|
||||
| Reconciler fault injection | реальный PostgreSQL + MinIO: orphan, missing и используемый control | dry-run без изменений; apply исправил 2 расхождения; повторный apply — 0 действий | `tests/test_reconciler_integration.py`, `evidence/results.md` |
|
||||
| Полный тестовый стенд | изолированный Compose, все pytest | `17 passed` | `evidence/results.md` |
|
||||
| Стоимость обхода | `SIZE=1000 make benchmark-reconciler` | 1000 строк и 1000 объектов: 229,657 мс, пик 4 202 814 bytes | `evidence/results.md` |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
@@ -164,6 +211,20 @@ docker compose --env-file .env run --rm --no-deps api \
|
||||
|
||||
Профиль upload: 30 запросов, concurrency 10, fixture 111 817 bytes, closed-loop, без retry. Получено 30 успешных upload за 0,382 с; максимальная latency 0,300 с; задействованы обе API-реплики. Пиковая наблюдаемая RAM: 68,50 MiB и 68,33 MiB при лимите 256 MiB на реплику.
|
||||
|
||||
Fault injection reconciler выполняется на настоящих PostgreSQL и MinIO. Тест создаёт
|
||||
старую `ready` строку без объекта, объект без строки и корректное вложение, уже связанное
|
||||
с сообщением. Управляемые часы имитируют истечение 60-секундного grace period без
|
||||
ожидания в тесте. Dry-run сохраняет обе ошибки, apply удаляет только orphan и маркирует
|
||||
missing, второй apply сообщает нулевое число действий. Корректный объект и связь сообщения
|
||||
после обоих запусков остаются на месте.
|
||||
|
||||
Воспроизводимый benchmark сначала удаляет прежнюю фикстуру, затем создаёт 1000 строк
|
||||
`attachments` и 1000 объектов MinIO, выполняет полный dry-run и удаляет фикстуру.
|
||||
Обход занял 229,657 мс, пик Python allocations составил 4 202 814 bytes. Измерение
|
||||
включает запрос PostgreSQL, listing MinIO и сравнение снимков; время подготовки и очистки
|
||||
в `elapsed_ms` reconciler не входит. Контрольный dry-run после cleanup показал 0 строк и
|
||||
0 объектов benchmark-набора.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| Restart API + PostgreSQL + Redis + MinIO | token, metadata и bytes сохраняются | persistence PASS | потерь нет |
|
||||
@@ -175,8 +236,8 @@ docker compose --env-file .env run --rm --no-deps api \
|
||||
|
||||
Стенд выдерживает остановку одной API-реплики и штатный restart контейнеров с сохранёнными volumes. Он не выдерживает потерю Docker-host, единственного HAProxy, PostgreSQL, Redis или MinIO volume. Несколько API-процессов не делают единственные хранилища высокодоступными.
|
||||
|
||||
Upload синхронный, поэтому клиент ждёт S3 и PostgreSQL. `SpooledTemporaryFile` ограничивает RAM одной загрузки, но временный disk API должен иметь достаточный объём и отдельную квоту в production. Cleanup делает полный список объектов и строк БД; для большого bucket нужны пагинация, метрики и плановый запуск.
|
||||
Upload синхронный, поэтому клиент ждёт S3 и PostgreSQL. `SpooledTemporaryFile` ограничивает RAM одной загрузки, но временный disk API должен иметь достаточный объём и отдельную квоту в production. Reconciler загружает полный список объектов и строк БД в память, поэтому его стоимость O(N), а для большого bucket нужны страничный/потоковый обход, метрики, checkpoint и плановый запуск.
|
||||
|
||||
Chainguard-образы зафиксированы по digest, поэтому обновляются только явно. Стенд изолирован учебной сетью. Перед production-развёртыванием потребовались бы непривилегированный UID с корректными правами на volume, TLS, внешний secret manager, HA хранилищ, аудит и резервное копирование.
|
||||
|
||||
Presigned upload, worker, thumbnail, варианты изображений и исследовательский reconciler для оценки 5 намеренно не реализованы.
|
||||
Presigned upload, worker, thumbnail и варианты изображений намеренно не реализованы: для выбранного трека 2 они не требуются.
|
||||
|
||||
@@ -64,17 +64,21 @@ class MessageRepository:
|
||||
return None
|
||||
|
||||
if attachment_ids:
|
||||
found = set(
|
||||
await session.scalars(
|
||||
select(AttachmentRow.id).where(
|
||||
AttachmentRow.id.in_(attachment_ids),
|
||||
AttachmentRow.chat_id == accessible_chat_id,
|
||||
AttachmentRow.status == 'ready',
|
||||
found = {
|
||||
attachment_id: status
|
||||
for attachment_id, status in (
|
||||
await session.execute(
|
||||
select(AttachmentRow.id, AttachmentRow.status).where(
|
||||
AttachmentRow.id.in_(attachment_ids),
|
||||
AttachmentRow.chat_id == accessible_chat_id,
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
if found != set(attachment_ids):
|
||||
).all()
|
||||
}
|
||||
if set(found) != set(attachment_ids):
|
||||
raise NotFound('вложение не найдено')
|
||||
if any(status != 'ready' for status in found.values()):
|
||||
raise Conflict('оригинал вложения недоступен')
|
||||
|
||||
statement = (
|
||||
insert(MessageRow)
|
||||
|
||||
@@ -12,6 +12,7 @@ from uuid import UUID, uuid4
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from ..domain.errors import (
|
||||
Conflict,
|
||||
Invalid,
|
||||
NotFound,
|
||||
PayloadTooLarge,
|
||||
@@ -137,6 +138,8 @@ class AttachmentService:
|
||||
|
||||
async def content(self, actor: User, attachment_id: UUID) -> tuple[Attachment, ObjectStream]:
|
||||
attachment = await self.get(actor, attachment_id)
|
||||
if attachment.status != 'ready':
|
||||
raise Conflict('оригинал вложения недоступен')
|
||||
try:
|
||||
stream = await self._storage.get(attachment.object_key)
|
||||
except FileNotFoundError as error:
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
import tracemalloc
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Callable, Sequence
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from ..config import load_settings
|
||||
from ..db import create_engine, create_session_factory
|
||||
from ..models.attachment import AttachmentRow
|
||||
from ..storage import S3Storage, StoredObject
|
||||
|
||||
MISSING_ERROR_CODE = 'original_missing'
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentSnapshot:
|
||||
id: UUID
|
||||
object_key: str
|
||||
status: str
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ReconcilePlan:
|
||||
orphan: tuple[StoredObject, ...]
|
||||
fresh_orphan: tuple[StoredObject, ...]
|
||||
missing: tuple[AttachmentSnapshot, ...]
|
||||
fresh_missing: tuple[AttachmentSnapshot, ...]
|
||||
correct: int
|
||||
|
||||
|
||||
def build_plan(
|
||||
attachments: Sequence[AttachmentSnapshot],
|
||||
objects: Sequence[StoredObject],
|
||||
cutoff: datetime,
|
||||
) -> ReconcilePlan:
|
||||
"""Compare immutable PostgreSQL and S3 snapshots without changing either side."""
|
||||
known_keys = {attachment.object_key for attachment in attachments}
|
||||
object_keys = {item.key for item in objects}
|
||||
|
||||
unknown_objects = [item for item in objects if item.key not in known_keys]
|
||||
orphan = tuple(item for item in unknown_objects if item.last_modified <= cutoff)
|
||||
fresh_orphan = tuple(item for item in unknown_objects if item.last_modified > cutoff)
|
||||
|
||||
ready_without_object = [
|
||||
attachment
|
||||
for attachment in attachments
|
||||
if attachment.status == 'ready' and attachment.object_key not in object_keys
|
||||
]
|
||||
missing = tuple(
|
||||
attachment for attachment in ready_without_object if attachment.updated_at <= cutoff
|
||||
)
|
||||
fresh_missing = tuple(
|
||||
attachment for attachment in ready_without_object if attachment.updated_at > cutoff
|
||||
)
|
||||
correct = sum(attachment.object_key in object_keys for attachment in attachments)
|
||||
return ReconcilePlan(orphan, fresh_orphan, missing, fresh_missing, correct)
|
||||
|
||||
|
||||
async def _load_attachments(
|
||||
sessions: async_sessionmaker[AsyncSession],
|
||||
) -> tuple[AttachmentSnapshot, ...]:
|
||||
async with sessions() as session:
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(
|
||||
AttachmentRow.id,
|
||||
AttachmentRow.object_key,
|
||||
AttachmentRow.status,
|
||||
AttachmentRow.updated_at,
|
||||
)
|
||||
)
|
||||
).all()
|
||||
return tuple(AttachmentSnapshot(*row) for row in rows)
|
||||
|
||||
|
||||
async def reconcile(
|
||||
sessions: async_sessionmaker[AsyncSession],
|
||||
storage: S3Storage,
|
||||
*,
|
||||
apply: bool,
|
||||
grace_seconds: int,
|
||||
now: datetime | None = None,
|
||||
output: Callable[[str], None] = print,
|
||||
) -> dict[str, int | float | str]:
|
||||
started = time.perf_counter()
|
||||
tracemalloc.start()
|
||||
current_time = now or datetime.now(timezone.utc)
|
||||
cutoff = current_time - timedelta(seconds=grace_seconds)
|
||||
|
||||
attachments = await _load_attachments(sessions)
|
||||
objects = await storage.list('originals/')
|
||||
plan = build_plan(attachments, objects, cutoff)
|
||||
|
||||
for item in plan.fresh_orphan:
|
||||
output(
|
||||
f'SKIP_FRESH_ORPHAN key={item.key} modified={item.last_modified.isoformat()}'
|
||||
)
|
||||
for attachment in plan.fresh_missing:
|
||||
output(
|
||||
'SKIP_FRESH_MISSING '
|
||||
f'attachment_id={attachment.id} key={attachment.object_key} '
|
||||
f'updated={attachment.updated_at.isoformat()}'
|
||||
)
|
||||
|
||||
removed = 0
|
||||
for item in plan.orphan:
|
||||
action = 'DELETE_ORPHAN' if apply else 'WOULD_DELETE_ORPHAN'
|
||||
output(f'{action} key={item.key} modified={item.last_modified.isoformat()}')
|
||||
if apply:
|
||||
await storage.remove(item.key)
|
||||
removed += 1
|
||||
|
||||
marked_failed = 0
|
||||
for attachment in plan.missing:
|
||||
action = 'MARK_MISSING' if apply else 'WOULD_MARK_MISSING'
|
||||
output(
|
||||
f'{action} attachment_id={attachment.id} key={attachment.object_key} '
|
||||
f'updated={attachment.updated_at.isoformat()}'
|
||||
)
|
||||
|
||||
if apply and plan.missing:
|
||||
async with sessions() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
update(AttachmentRow)
|
||||
.where(
|
||||
AttachmentRow.id.in_([item.id for item in plan.missing]),
|
||||
AttachmentRow.status == 'ready',
|
||||
)
|
||||
.values(
|
||||
status='failed',
|
||||
error_code=MISSING_ERROR_CODE,
|
||||
updated_at=current_time,
|
||||
)
|
||||
)
|
||||
marked_failed = result.rowcount or 0
|
||||
|
||||
_, peak_bytes = tracemalloc.get_traced_memory()
|
||||
tracemalloc.stop()
|
||||
summary: dict[str, int | float | str] = {
|
||||
'mode': 'apply' if apply else 'dry-run',
|
||||
'metadata': len(attachments),
|
||||
'objects': len(objects),
|
||||
'correct': plan.correct,
|
||||
'orphan': len(plan.orphan),
|
||||
'missing': len(plan.missing),
|
||||
'fresh_protected': len(plan.fresh_orphan) + len(plan.fresh_missing),
|
||||
'removed': removed,
|
||||
'marked_failed': marked_failed,
|
||||
'grace_seconds': grace_seconds,
|
||||
'elapsed_ms': round((time.perf_counter() - started) * 1000, 3),
|
||||
'peak_memory_bytes': peak_bytes,
|
||||
}
|
||||
output(f'summary {json.dumps(summary, sort_keys=True)}')
|
||||
return summary
|
||||
|
||||
|
||||
async def run(apply: bool, grace_seconds: int) -> int:
|
||||
settings = load_settings()
|
||||
engine = create_engine(settings.database_url)
|
||||
storage = S3Storage(
|
||||
settings.s3_endpoint,
|
||||
settings.s3_access_key_id,
|
||||
settings.s3_secret_access_key,
|
||||
settings.s3_bucket,
|
||||
settings.s3_region,
|
||||
)
|
||||
try:
|
||||
await reconcile(
|
||||
create_session_factory(engine),
|
||||
storage,
|
||||
apply=apply,
|
||||
grace_seconds=grace_seconds,
|
||||
)
|
||||
return 0
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Reconcile attachment metadata in PostgreSQL with original objects in S3'
|
||||
)
|
||||
mode = parser.add_mutually_exclusive_group(required=True)
|
||||
mode.add_argument('--dry-run', action='store_true')
|
||||
mode.add_argument('--apply', action='store_true')
|
||||
parser.add_argument('--grace-seconds', type=int, default=3600)
|
||||
args = parser.parse_args()
|
||||
if args.grace_seconds < 60:
|
||||
parser.error('--grace-seconds must be at least 60')
|
||||
raise SystemExit(asyncio.run(run(args.apply, args.grace_seconds)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,136 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from io import BytesIO
|
||||
from uuid import NAMESPACE_URL, uuid5
|
||||
|
||||
from sqlalchemy import delete, insert
|
||||
|
||||
from ..config import load_settings
|
||||
from ..db import create_engine, create_session_factory
|
||||
from ..models.attachment import AttachmentRow
|
||||
from ..models.chat import ChatMemberRow, ChatRow
|
||||
from ..models.user import UserRow
|
||||
from ..storage import S3Storage
|
||||
|
||||
USER_ID = uuid5(NAMESPACE_URL, 'reconciler-benchmark:user')
|
||||
CHAT_ID = uuid5(NAMESPACE_URL, 'reconciler-benchmark:chat')
|
||||
OBJECT_PREFIX = 'originals/reconciler-benchmark/'
|
||||
WORKERS = 16
|
||||
|
||||
|
||||
async def _put_objects(
|
||||
storage: S3Storage,
|
||||
keys: list[str],
|
||||
) -> None:
|
||||
for offset in range(0, len(keys), WORKERS):
|
||||
batch = keys[offset : offset + WORKERS]
|
||||
await asyncio.gather(
|
||||
*(storage.put(key, BytesIO(b'x'), 1, 'application/octet-stream') for key in batch)
|
||||
)
|
||||
|
||||
|
||||
async def prepare(size: int) -> None:
|
||||
settings = load_settings()
|
||||
engine = create_engine(settings.database_url)
|
||||
sessions = create_session_factory(engine)
|
||||
storage = S3Storage(
|
||||
settings.s3_endpoint,
|
||||
settings.s3_access_key_id,
|
||||
settings.s3_secret_access_key,
|
||||
settings.s3_bucket,
|
||||
settings.s3_region,
|
||||
)
|
||||
old = datetime.now(timezone.utc) - timedelta(hours=2)
|
||||
rows = [
|
||||
{
|
||||
'id': uuid5(NAMESPACE_URL, f'reconciler-benchmark:attachment:{index}'),
|
||||
'chat_id': CHAT_ID,
|
||||
'owner_id': USER_ID,
|
||||
'filename': f'benchmark-{index}.png',
|
||||
'object_key': f'{OBJECT_PREFIX}{index}',
|
||||
'content_type': 'image/png',
|
||||
'size_bytes': 1,
|
||||
'sha256': '0' * 64,
|
||||
'width': 1,
|
||||
'height': 1,
|
||||
'status': 'ready',
|
||||
'error_code': None,
|
||||
'created_at': old,
|
||||
'updated_at': old,
|
||||
}
|
||||
for index in range(size)
|
||||
]
|
||||
try:
|
||||
async with sessions() as session:
|
||||
async with session.begin():
|
||||
session.add(UserRow(
|
||||
id=USER_ID,
|
||||
username=f'bench-{USER_ID.hex[:16]}',
|
||||
display_name='Reconciler benchmark',
|
||||
password_hash='not-used',
|
||||
created_at=old,
|
||||
))
|
||||
session.add(ChatRow(id=CHAT_ID, title='Reconciler benchmark', created_at=old))
|
||||
await session.flush()
|
||||
session.add(ChatMemberRow(chat_id=CHAT_ID, user_id=USER_ID))
|
||||
await session.flush()
|
||||
for offset in range(0, size, 500):
|
||||
await session.execute(insert(AttachmentRow), rows[offset : offset + 500])
|
||||
|
||||
await _put_objects(storage, [row['object_key'] for row in rows])
|
||||
print(f'prepared metadata={size} objects={size}')
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
async def cleanup() -> None:
|
||||
settings = load_settings()
|
||||
engine = create_engine(settings.database_url)
|
||||
sessions = create_session_factory(engine)
|
||||
storage = S3Storage(
|
||||
settings.s3_endpoint,
|
||||
settings.s3_access_key_id,
|
||||
settings.s3_secret_access_key,
|
||||
settings.s3_bucket,
|
||||
settings.s3_region,
|
||||
)
|
||||
try:
|
||||
objects = await storage.list(OBJECT_PREFIX)
|
||||
keys = [item.key for item in objects]
|
||||
for offset in range(0, len(keys), WORKERS):
|
||||
await asyncio.gather(
|
||||
*(storage.remove(key) for key in keys[offset : offset + WORKERS])
|
||||
)
|
||||
|
||||
async with sessions() as session:
|
||||
async with session.begin():
|
||||
await session.execute(delete(ChatRow).where(ChatRow.id == CHAT_ID))
|
||||
await session.execute(delete(UserRow).where(UserRow.id == USER_ID))
|
||||
print(f'cleaned objects={len(keys)}')
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Prepare and clean isolated PostgreSQL/S3 data for reconciler benchmarks'
|
||||
)
|
||||
subparsers = parser.add_subparsers(dest='command', required=True)
|
||||
prepare_parser = subparsers.add_parser('prepare')
|
||||
prepare_parser.add_argument('--size', type=int, required=True)
|
||||
subparsers.add_parser('cleanup')
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.command == 'prepare':
|
||||
if args.size < 1 or args.size > 10000:
|
||||
parser.error('--size must be between 1 and 10000')
|
||||
asyncio.run(prepare(args.size))
|
||||
else:
|
||||
asyncio.run(cleanup())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -106,7 +106,14 @@ services:
|
||||
dockerfile: Dockerfile.test
|
||||
environment:
|
||||
BASE_URL: http://api:8080
|
||||
DATABASE_URL: postgresql+asyncpg://messenger_test:messenger_test@postgres:5432/messenger_test
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
SESSION_TTL_SECONDS: 3600
|
||||
S3_ENDPOINT: http://s3:9000
|
||||
S3_REGION: us-east-1
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID: messenger-api
|
||||
S3_SECRET_ACCESS_KEY: test-minio-api-password
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
|
||||
+43
-1
@@ -1,6 +1,6 @@
|
||||
# Результаты проверки lab4
|
||||
|
||||
Дата последней перепроверки: 2026-11-04. Стенд: Apple M4 Pro, 12 CPU cores, 24 GB RAM, Docker Desktop.
|
||||
Дата последней перепроверки: 2026-11-05. Стенд: Apple M4 Pro, 12 CPU cores, 24 GB RAM, Docker Desktop.
|
||||
|
||||
## Версии runtime
|
||||
|
||||
@@ -54,6 +54,14 @@ $ docker compose -p lab4-chainguard-tests -f compose.tests.yaml run --rm tests p
|
||||
13 passed in 0.41s
|
||||
```
|
||||
|
||||
После добавления reconciler трека 2 итоговый запуск в отдельном Compose-проекте:
|
||||
|
||||
```text
|
||||
$ docker compose -p lab4track2test -f compose.tests.yaml run --rm tests
|
||||
................. [100%]
|
||||
17 passed in 0.55s
|
||||
```
|
||||
|
||||
## Приватность и bootstrap
|
||||
|
||||
```text
|
||||
@@ -101,3 +109,37 @@ summary mode=dry-run known=164 removed=0 grace_seconds=60
|
||||
```
|
||||
|
||||
Dry-run не менял данные. Применение требует явного `--apply`; значения grace period меньше 60 секунд запрещены.
|
||||
|
||||
## Reconciler PostgreSQL/S3 — трек 2
|
||||
|
||||
`tests/test_reconciler_integration.py` внедряет ошибки на обеих сторонах настоящего
|
||||
тестового стенда: старую metadata без объекта (`missing`) и объект без metadata
|
||||
(`orphan`). Контрольное вложение связано с сообщением.
|
||||
|
||||
```text
|
||||
$ docker compose -p lab4track2test -f compose.tests.yaml run --build --rm tests \
|
||||
python -m pytest -q tests/test_reconciler.py tests/test_reconciler_integration.py
|
||||
... [100%]
|
||||
3 passed in 0.32s
|
||||
```
|
||||
|
||||
Проверено: dry-run обнаруживает по одному расхождению и ничего не меняет; apply удаляет
|
||||
ровно один orphan и переводит ровно один missing в `failed/original_missing`; повторный
|
||||
apply выполняет 0 изменений. Объект контрольного вложения и связь с сообщением сохранены.
|
||||
|
||||
Воспроизводимый end-to-end benchmark самостоятельно подготовил реальные данные в
|
||||
PostgreSQL и MinIO, а после измерения удалил их:
|
||||
|
||||
```text
|
||||
$ SIZE=1000 ./scripts/benchmark-reconciler.sh
|
||||
cleaned objects=0
|
||||
prepared metadata=1000 objects=1000
|
||||
summary {"correct": 1000, "elapsed_ms": 229.657, "fresh_protected": 0,
|
||||
"grace_seconds": 3600, "marked_failed": 0, "metadata": 1000, "missing": 0,
|
||||
"mode": "dry-run", "objects": 1000, "orphan": 0,
|
||||
"peak_memory_bytes": 4202814, "removed": 0}
|
||||
cleaned objects=1000
|
||||
```
|
||||
|
||||
Повторный dry-run после cleanup показал `metadata=0`, `objects=0`: benchmark-фикстура
|
||||
не осталась в PostgreSQL или MinIO.
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
size="${SIZE:-1000}"
|
||||
|
||||
docker compose exec -T api python -m app.tools.seed_reconciler_benchmark cleanup
|
||||
docker compose exec -T api python -m app.tools.seed_reconciler_benchmark prepare --size "$size"
|
||||
docker compose exec -T api python -m app.tools.reconcile_attachments --dry-run
|
||||
docker compose exec -T api python -m app.tools.seed_reconciler_benchmark cleanup
|
||||
@@ -6,6 +6,8 @@ from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from app.domain.errors import Conflict
|
||||
from app.domain.models import Attachment
|
||||
from app.domain.models import User
|
||||
from app.services.attachments import AttachmentService
|
||||
|
||||
@@ -30,6 +32,19 @@ class RecordingStorage:
|
||||
self.removed_key = key
|
||||
|
||||
|
||||
class FailedAttachmentRepository:
|
||||
def __init__(self, attachment):
|
||||
self.attachment = attachment
|
||||
|
||||
async def get_for_member(self, attachment_id, user_id):
|
||||
return self.attachment
|
||||
|
||||
|
||||
class StorageThatMustNotBeRead:
|
||||
async def get(self, key):
|
||||
raise AssertionError('failed attachment must not read S3')
|
||||
|
||||
|
||||
def test_uploaded_object_is_removed_when_metadata_commit_fails():
|
||||
storage = RecordingStorage()
|
||||
service = AttachmentService(FailingRepository(), storage, 10 * 1024 * 1024, 40_000_000)
|
||||
@@ -52,3 +67,30 @@ def test_uploaded_object_is_removed_when_metadata_commit_fails():
|
||||
|
||||
assert storage.put_key is not None
|
||||
assert storage.removed_key == storage.put_key
|
||||
|
||||
|
||||
def test_failed_attachment_content_returns_conflict_without_s3_read():
|
||||
now = datetime.now(timezone.utc)
|
||||
attachment = Attachment(
|
||||
id=uuid4(),
|
||||
chat_id=uuid4(),
|
||||
owner_id=uuid4(),
|
||||
filename='missing.png',
|
||||
object_key=f'originals/{uuid4()}',
|
||||
content_type='image/png',
|
||||
size_bytes=1,
|
||||
sha256='0' * 64,
|
||||
width=1,
|
||||
height=1,
|
||||
status='failed',
|
||||
error_code='original_missing',
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
service = AttachmentService(
|
||||
FailedAttachmentRepository(attachment), StorageThatMustNotBeRead(), 1, 1
|
||||
)
|
||||
actor = User(uuid4(), 'tester', 'Tester', now)
|
||||
|
||||
with pytest.raises(Conflict, match='недоступен'):
|
||||
asyncio.run(service.content(actor, attachment.id))
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from app.storage import StoredObject
|
||||
from app.tools.reconcile_attachments import AttachmentSnapshot, build_plan
|
||||
|
||||
|
||||
def test_plan_classifies_both_sides_and_protects_fresh_items():
|
||||
now = datetime.now(timezone.utc)
|
||||
cutoff = now - timedelta(minutes=1)
|
||||
correct_key = f'originals/{uuid4()}'
|
||||
missing = AttachmentSnapshot(uuid4(), f'originals/{uuid4()}', 'ready', cutoff)
|
||||
fresh_missing = AttachmentSnapshot(uuid4(), f'originals/{uuid4()}', 'ready', now)
|
||||
already_failed = AttachmentSnapshot(uuid4(), f'originals/{uuid4()}', 'failed', cutoff)
|
||||
attachments = (
|
||||
AttachmentSnapshot(uuid4(), correct_key, 'ready', cutoff),
|
||||
missing,
|
||||
fresh_missing,
|
||||
already_failed,
|
||||
)
|
||||
old_orphan = StoredObject(f'originals/{uuid4()}', cutoff)
|
||||
fresh_orphan = StoredObject(f'originals/{uuid4()}', now)
|
||||
|
||||
plan = build_plan(
|
||||
attachments,
|
||||
(StoredObject(correct_key, cutoff), old_orphan, fresh_orphan),
|
||||
cutoff,
|
||||
)
|
||||
|
||||
assert plan.correct == 1
|
||||
assert plan.orphan == (old_orphan,)
|
||||
assert plan.fresh_orphan == (fresh_orphan,)
|
||||
assert plan.missing == (missing,)
|
||||
assert plan.fresh_missing == (fresh_missing,)
|
||||
|
||||
|
||||
def test_failed_metadata_still_protects_its_object_from_orphan_cleanup():
|
||||
now = datetime.now(timezone.utc)
|
||||
key = f'originals/{uuid4()}'
|
||||
failed = AttachmentSnapshot(uuid4(), key, 'failed', now - timedelta(hours=2))
|
||||
|
||||
plan = build_plan(
|
||||
(failed,),
|
||||
(StoredObject(key, now - timedelta(hours=2)),),
|
||||
now - timedelta(hours=1),
|
||||
)
|
||||
|
||||
assert plan.correct == 1
|
||||
assert plan.orphan == ()
|
||||
assert plan.missing == ()
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Real PostgreSQL + S3 fault injection for grade 5, track 2."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from io import BytesIO
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.config import load_settings
|
||||
from app.db import create_engine, create_session_factory
|
||||
from app.models.attachment import AttachmentRow, MessageAttachmentRow
|
||||
from app.models.chat import ChatMemberRow, ChatRow
|
||||
from app.models.message import MessageRow
|
||||
from app.models.user import UserRow
|
||||
from app.storage import S3Storage
|
||||
from app.tools.reconcile_attachments import MISSING_ERROR_CODE, reconcile
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not os.getenv('DATABASE_URL'), reason='requires the compose PostgreSQL and S3 services'
|
||||
)
|
||||
|
||||
|
||||
def test_dry_run_apply_and_repeat_are_safe():
|
||||
asyncio.run(_check_dry_run_apply_and_repeat_are_safe())
|
||||
|
||||
|
||||
async def _check_dry_run_apply_and_repeat_are_safe():
|
||||
settings = load_settings()
|
||||
engine = create_engine(settings.database_url)
|
||||
sessions = create_session_factory(engine)
|
||||
storage = S3Storage(
|
||||
settings.s3_endpoint,
|
||||
settings.s3_access_key_id,
|
||||
settings.s3_secret_access_key,
|
||||
settings.s3_bucket,
|
||||
settings.s3_region,
|
||||
)
|
||||
now = datetime.now(timezone.utc)
|
||||
old = now - timedelta(hours=2)
|
||||
simulated_after_grace = now + timedelta(seconds=61)
|
||||
user_id, chat_id, message_id = uuid4(), uuid4(), uuid4()
|
||||
correct_id, missing_id = uuid4(), uuid4()
|
||||
correct_key = f'originals/reconcile-correct-{uuid4()}'
|
||||
orphan_key = f'originals/reconcile-orphan-{uuid4()}'
|
||||
|
||||
try:
|
||||
async with sessions() as session:
|
||||
async with session.begin():
|
||||
session.add(UserRow(
|
||||
id=user_id,
|
||||
username=f'reconcile-{user_id.hex[:16]}',
|
||||
display_name='Reconciler test',
|
||||
password_hash='not-used',
|
||||
created_at=old,
|
||||
))
|
||||
session.add(ChatRow(id=chat_id, title='Reconciler test', created_at=old))
|
||||
await session.flush()
|
||||
session.add(ChatMemberRow(chat_id=chat_id, user_id=user_id))
|
||||
for attachment_id, key in (
|
||||
(correct_id, correct_key),
|
||||
(missing_id, f'originals/reconcile-missing-{uuid4()}'),
|
||||
):
|
||||
session.add(AttachmentRow(
|
||||
id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=user_id,
|
||||
filename='test.png',
|
||||
object_key=key,
|
||||
content_type='image/png',
|
||||
size_bytes=1,
|
||||
sha256='0' * 64,
|
||||
width=1,
|
||||
height=1,
|
||||
status='ready',
|
||||
error_code=None,
|
||||
created_at=old,
|
||||
updated_at=old,
|
||||
))
|
||||
await session.flush()
|
||||
session.add(MessageRow(
|
||||
id=message_id,
|
||||
chat_id=chat_id,
|
||||
sender_id=user_id,
|
||||
text='used attachment must survive',
|
||||
created_at=old,
|
||||
idempotency_key=f'reconcile-{message_id}',
|
||||
))
|
||||
await session.flush()
|
||||
session.add(MessageAttachmentRow(
|
||||
message_id=message_id,
|
||||
attachment_id=correct_id,
|
||||
position=0,
|
||||
))
|
||||
|
||||
for key in (correct_key, orphan_key):
|
||||
await storage.put(key, BytesIO(b'x'), 1, 'application/octet-stream')
|
||||
|
||||
dry_run = await reconcile(
|
||||
sessions,
|
||||
storage,
|
||||
apply=False,
|
||||
grace_seconds=60,
|
||||
now=simulated_after_grace,
|
||||
output=lambda _line: None,
|
||||
)
|
||||
assert dry_run['orphan'] == 1
|
||||
assert dry_run['missing'] == 1
|
||||
assert dry_run['removed'] == 0
|
||||
assert dry_run['marked_failed'] == 0
|
||||
assert {item.key for item in await storage.list('originals/')} >= {
|
||||
correct_key,
|
||||
orphan_key,
|
||||
}
|
||||
|
||||
applied = await reconcile(
|
||||
sessions,
|
||||
storage,
|
||||
apply=True,
|
||||
grace_seconds=60,
|
||||
now=simulated_after_grace,
|
||||
output=lambda _line: None,
|
||||
)
|
||||
assert applied['removed'] == 1
|
||||
assert applied['marked_failed'] == 1
|
||||
|
||||
repeated = await reconcile(
|
||||
sessions,
|
||||
storage,
|
||||
apply=True,
|
||||
grace_seconds=60,
|
||||
now=simulated_after_grace,
|
||||
output=lambda _line: None,
|
||||
)
|
||||
assert repeated['orphan'] == 0
|
||||
assert repeated['missing'] == 0
|
||||
assert repeated['removed'] == 0
|
||||
assert repeated['marked_failed'] == 0
|
||||
|
||||
object_keys = {item.key for item in await storage.list('originals/')}
|
||||
assert correct_key in object_keys
|
||||
assert orphan_key not in object_keys
|
||||
async with sessions() as session:
|
||||
missing_row = await session.get(AttachmentRow, missing_id)
|
||||
assert missing_row is not None
|
||||
assert missing_row.status == 'failed'
|
||||
assert missing_row.error_code == MISSING_ERROR_CODE
|
||||
assert await session.scalar(
|
||||
select(MessageAttachmentRow.attachment_id).where(
|
||||
MessageAttachmentRow.message_id == message_id
|
||||
)
|
||||
) == correct_id
|
||||
finally:
|
||||
await storage.remove(correct_key)
|
||||
await storage.remove(orphan_key)
|
||||
async with sessions() as session:
|
||||
async with session.begin():
|
||||
chat = await session.get(ChatRow, chat_id)
|
||||
if chat is not None:
|
||||
await session.delete(chat)
|
||||
await session.flush()
|
||||
user = await session.get(UserRow, user_id)
|
||||
if user is not None:
|
||||
await session.delete(user)
|
||||
await engine.dispose()
|
||||
Reference in New Issue
Block a user