feat: крролик, по тщ 5 лаба

This commit is contained in:
Enterxx2
2026-11-10 12:38:09 +03:00
parent 1d8dfb7ea4
commit 595a959b96
65 changed files with 2692 additions and 216 deletions
+11 -1
View File
@@ -61,7 +61,7 @@ ATTACHMENT_STORE_TIMEOUT_SEC=30
ATTACHMENT_PENDING_GRACE_SEC=900
JANITOR_INTERVAL_SEC=60
# Параметры шаблона lab5; подключаются на этапе реализации очереди.
# Логические параметры skeleton; это приложение использует DB_*/VALKEY_* выше.
DATABASE_URL_FILE=/run/secrets/database_url
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
@@ -73,3 +73,13 @@ STAGING_RETENTION_SECONDS=86400
# Порт PostgreSQL на localhost (55432 занят другим локальным стендом).
DB_HOST_PORT=55433
# Lab5: RabbitMQ и ограниченный pipeline изображений
RABBITMQ_USER=test
RABBITMQ_PASS=test
WORKER_PREFETCH=2
JOB_LEASE_SECONDS=90
JOB_RETRY_BASE_SECONDS=2
JOB_RETRY_MAX_SECONDS=60
IMAGE_PROCESS_MEMORY_MB=768
OUTBOX_POLL_SECONDS=0.5
+12
View File
@@ -126,3 +126,15 @@ experiment-failover:
experiment-rolling:
$(PYTHON) scripts/experiment.py rolling --base-url "$(BASE_URL)" --output evidence/experiment-rolling.json
.PHONY: test-pipeline-failures jobs-failed replay
test-pipeline-failures:
BASE_URL="$(BASE_URL)" RUN_PIPELINE_FAILURE_TESTS=1 poetry run pytest student-tests/test_pipeline_failures.py -v -s
jobs-failed:
docker compose exec -T dispatcher python src/jobs.py failed
replay:
@test -n "$(JOB_ID)" -a -n "$(OPERATOR)" -a -n "$(REASON)" || (echo "Set JOB_ID, OPERATOR and REASON"; exit 2)
docker compose exec -T dispatcher python src/jobs.py replay --job-id "$(JOB_ID)" --operator "$(OPERATOR)" --reason "$(REASON)"
+10 -3
View File
@@ -1,10 +1,17 @@
# Лабораторная 5. Очереди и асинхронная обработка изображений
## Текущее состояние: перенесена база lab4
## Запуск реализации на оценку 4
Реализация lab4 перенесена с сохранением слоистой архитектуры и прежнего поведения API: upload пока возвращает `201 ready`. Требования lab5 ниже ещё не реализованы. Исходный отчёт и результаты lab4 сохранены в [REPORT.lab4.md](REPORT.lab4.md) и `evidence/`; это исторические результаты, а не доказательства выполнения lab5.
Реализованы RabbitMQ, отдельные dispatcher/worker, transactional outbox, thumbnail/crop/WebP, lease, ограниченные retry с jitter, реестр failed и операторский replay. Слои и стиль проекта lab4 сохранены. Подробности, настройки, ограничения и доказательства — в [REPORT.md](REPORT.md); исторический отчёт lab4 — в [REPORT.lab4.md](REPORT.lab4.md).
Запуск базы: `make init && make up`. API: `http://localhost:8080`; PostgreSQL: `localhost:55433`. Compose-проект `messenger-lab5` использует собственные volumes и образ `mtusi-messenger:lab5`. Проверки перенесённой реализации: `make install && make student-test`; проверка структуры задания: `make check`. Публичный `make test` проверяет уже lab5 и потребует реализации очереди и worker.
```sh
make init && make up
make check && make test
make install && make student-test
make test-pipeline-failures
```
API: `http://localhost:8080`; PostgreSQL: `localhost:55433`. Compose-проект `messenger-lab5` использует собственные volumes. Upload возвращает `202 queued`; клиент опрашивает метаданные до `ready`/`failed`. `make jobs-failed` показывает реестр ошибок; `make replay JOB_ID=<uuid> OPERATOR=<имя> REASON='<причина>'` ставит failed-задачу повторно с аудитом. Тесты сбоев явно перезапускают компоненты только этого стенда и занимают несколько минут.
## Задание lab5
+68 -24
View File
@@ -1,37 +1,81 @@
# Отчёт — лабораторная 5
# Лабораторная 5. Асинхронная обработка изображений
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
**Автор:** Саватеев Артём. **Целевая оценка:** 4.
## Запуск из чистого clone
## Запуск
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Требования: Docker Compose ≥ 2.20.2; для собственных тестов — Python 3.12 и Poetry 2.2.
## Архитектура и решения
```sh
make init
make up
make install
poetry run python -m pip install -r requirements-dev.txt
make test
```
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
`make init` создаёт `.env` и локальные секреты. API: `http://localhost:8080`, PostgreSQL: `localhost:55433`. RabbitMQ и S3 доступны внутри стенда. Миграции применяются автоматически. `make down` сохраняет данные в volumes PostgreSQL, S3 и RabbitMQ.
## Доказательства критериев
## Архитектура и обработка
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
Слои: `domain` — схемы и ошибки; `interfaces` — абстракции; `infrastructure` — сервисы и адаптеры PostgreSQL/S3/RabbitMQ; `application` — HTTP API.
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
```text
API → S3 staging + PostgreSQL/outbox → dispatcher → RabbitMQ → worker → S3 + PostgreSQL
```
## Эксперименты и отказы
1. API принимает файл потоком, проверяет доступ, MIME, размер и параметры изображения. После сохранения staging одна транзакция создаёт job/outbox и состояние `queued`. Ответ — `202 queued`.
2. Dispatcher публикует persistent сообщения в durable очередь с `mandatory` и publisher confirms. Событие отмечается отправленным после confirm; сбой между COMMIT и publish восстанавливается через outbox. Сообщения содержат только ID и служебные поля.
3. Worker захватывает job с lease, проверяет SHA-256 исходника и создаёт варианты. После записи всех объектов одна транзакция публикует метаданные и `ready`; затем отправляется consumer ack.
4. Ключи объектов детерминированы, `(attachment_id, pipeline_version, variant)` уникален. Повтор ready-задачи — no-op; просроченный lease восстанавливается, устаревший lease_token не позволяет зафиксировать результат. Доставка — at least once.
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
Состояния: `queued → processing → ready/failed`. До ready скачивание возвращает `409`; доступ постороннего пользователя — `404`. Queued/processing можно прикрепить к сообщению, failed — нельзя. Готовые файлы выдаются через авторизованный API из приватного S3.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
## Варианты и лимиты
## Ограничения и следующие шаги
| Вариант | Параметры |
| --- | --- |
| original | Исходные байты, MIME, размер и SHA-256 сохранены |
| thumbnail | JPEG, quality 85, вписан в 256×256 без увеличения; размеры округляются вниз, минимум 1 px |
| crop | JPEG, quality 85, центрированный квадрат 128×128; увеличение допускается |
| optimized | WebP, quality 80, вписан в 1280×1280 без увеличения |
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
Для производных применяется EXIF orientation, прозрачность компонуется на белый, EXIF/XMP/ICC удаляются. Resize выполняется Lanczos. Уменьшение размера каждого файла не гарантируется.
Лимиты входа: **10 MiB и 40 млн пикселей**. Worker полностью декодирует изображение в отдельном процессе: память **768 MiB**, CPU **60 с**, timeout всего задания **60 с**, lease **90 с**. При timeout процесс декодера завершается. Concurrency/prefetch — **2/2**; контейнер worker ограничен **1792 MiB и 2 CPU**. Значения задаются через `.env`.
## Повторы и очистка
Максимум **5 попыток**. Постоянные ошибки завершаются в failed; временные повторяются с backoff и jitter: `ceiling = min(60, 2 × 2^(n−1))`, задержка `[ceiling/2, ceiling]` секунд. Причина, следующая попытка и outbox сохраняются устойчиво. После исчерпания попыток — `retry_exhausted`; реестр failed хранится в PostgreSQL.
```sh
make jobs-failed
make replay JOB_ID=UUID OPERATOR=artem REASON='причина устранена'
```
Replay разрешён только для failed с сохранённым исходником и записывается в аудит. Для ready/queued/processing — no-op. Cleanup и replay блокируют job и attachment, исключая повторный запуск уже очищенного исходника.
Janitor удаляет staging после COMMIT ready. Failed-исходники хранятся **24 часа**, незавершённые загрузки очищаются после **900 с**; период проверки — **60 с**. Активные queued/processing сохраняются независимо от возраста.
## Проверки
Зафиксировано **218 успешных тестов**: 195 основных и 23 проверки, запускаемые отдельно.
| Команда | Результат | Протокол |
| --- | --- | --- |
| `make check validate PYTHON='poetry run python'` | PASS | [Контракты](evidence/lab5-contracts.txt) |
| `make test` | PASS | [Smoke](evidence/lab5-public.txt) |
| `make student-test` | 195 passed | [Основной набор](evidence/lab5-tests.txt) |
| `make test-pipeline-failures` | 7 passed | [Сбои pipeline](evidence/lab5-pipeline-failures.txt) |
| `make test-storage` | 8 passed | [Хранилище](evidence/lab5-storage.txt) |
| `make test-failures` | 6 passed | [Отказы зависимостей/API](evidence/lab5-dependency-failures.txt) |
| `make test-expiry` | 2 passed | [Сессии](evidence/lab5-expiry.txt) |
| `make test-migrations` | PASS | [Миграции](evidence/lab5-migrations.txt) |
| `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS | [Сохранность данных](evidence/lab5-persistence.txt) |
| `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`; затем `make restore` | PASS | [Failover](evidence/lab5-failover.txt) |
Проверены остановленный worker, разрыв COMMIT/publish, рестарт broker с volume, crash после S3 PUT и после COMMIT до ack, redelivery, исчерпание retry, replay и retention. После восстановления checksum совпадают, варианты не дублируются. При failover: **132 успешные записи, 0 ошибок, восстановление за 1,772 с**.
## Ограничения
Стенд работает на одном Docker-host; PostgreSQL, RabbitMQ, S3 и nginx имеют по одному экземпляру. Потеря host/volumes не покрывается. После retention для failed требуется новая загрузка.
+84 -1
View File
@@ -1,6 +1,6 @@
name: messenger-lab5
# Один образ приложения для api, migrate, s3-bootstrap и janitor. Собирает его
# Один образ приложения для API, worker, dispatcher, migrate, s3-bootstrap и janitor. Собирает его
# только api: параллельная сборка одного тега несколькими сервисами конфликтует.
x-app: &app
image: mtusi-messenger:lab5
@@ -262,6 +262,86 @@ services:
cpus: "0.25"
memory: 192M
broker:
image: rabbitmq:4.1.4-alpine
hostname: broker
restart: unless-stopped
environment:
RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-test}
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASS:-test}
volumes:
- rabbitmq_data:/var/lib/rabbitmq
networks:
- backend
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 5s
timeout: 5s
retries: 20
stop_grace_period: 30s
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
dispatcher:
<<: *app
command: ["python", "src/dispatcher.py"]
restart: unless-stopped
depends_on:
migrate:
condition: service_completed_successfully
broker:
condition: service_healthy
secrets:
- broker_url
networks:
- backend
healthcheck:
test: ["CMD", "python", "src/healthcheck.py", "dispatcher"]
interval: 5s
timeout: 3s
retries: 5
start_period: 20s
stop_grace_period: 10s
deploy:
resources:
limits:
cpus: "0.25"
memory: 192M
worker:
<<: *app
command: ["python", "src/worker.py"]
restart: unless-stopped
depends_on:
migrate:
condition: service_completed_successfully
s3-bootstrap:
condition: service_completed_successfully
broker:
condition: service_healthy
secrets:
- broker_url
- s3_access_key_id
- s3_secret_access_key
networks:
- backend
- storage
healthcheck:
test: ["CMD", "python", "src/healthcheck.py", "worker"]
interval: 5s
timeout: 3s
retries: 5
start_period: 20s
stop_grace_period: 10s
deploy:
resources:
limits:
cpus: "2.0"
memory: 1792M
api-short-ttl:
<<: *api
profiles:
@@ -286,9 +366,12 @@ networks:
volumes:
postgres_data:
s3_data:
rabbitmq_data:
# Создаются scripts/init-secrets.sh; в git не попадают
secrets:
broker_url:
file: ./secrets/broker_url
s3_access_key_id:
file: ./secrets/s3_access_key_id
s3_secret_access_key:
+1
View File
@@ -0,0 +1 @@
PASS: producer JSON matches jobs.schema.json, including UUID/date-time formats; carrier contains only service fields
+10
View File
@@ -0,0 +1,10 @@
============================= test session starts ==============================
platform darwin -- Python 3.12.12, pytest-9.1.1, pluggy-1.6.0
rootdir: /Users/enterxx/Desktop/university/4course/mtusi2026lab5
configfile: pyproject.toml
plugins: anyio-4.15.1
collected 1 item
student-tests/test_pipeline_races.py . [100%]
============================== 1 passed in 8.72s ===============================
+4
View File
@@ -0,0 +1,4 @@
.venv/bin/python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
+21
View File
@@ -0,0 +1,21 @@
BASE_URL="http://localhost:8080" RUN_FAILURE_TESTS=1 poetry run pytest student-tests/test_dependency_failures.py student-tests/test_storage_failures.py student-tests/test_attachment_failover.py -s
/Users/enterxx/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
============================= test session starts ==============================
platform darwin -- Python 3.12.12, pytest-9.1.1, pluggy-1.6.0 -- /Users/enterxx/Desktop/university/4course/mtusi2026lab5/.venv/bin/python
cachedir: .pytest_cache
rootdir: /Users/enterxx/Desktop/university/4course/mtusi2026lab5
configfile: pyproject.toml
plugins: anyio-4.15.1
collecting ... collected 6 items
student-tests/test_dependency_failures.py::test_valkey_down_cache_is_bypassed PASSED
student-tests/test_dependency_failures.py::test_logout_during_valkey_outage_is_not_resurrected PASSED
student-tests/test_dependency_failures.py::test_postgres_down_returns_bounded_503_and_no_anonymous_access PASSED
student-tests/test_dependency_failures.py::test_session_survives_postgres_restart PASSED
student-tests/test_storage_failures.py::test_s3_outage_is_isolated_and_leaves_no_garbage PASSED
student-tests/test_attachment_failover.py::test_download_survives_stop_of_uploading_replica
UPLOADED BY ae079a9d572c, DOWNLOADED FROM ['4c15afa83957']
PASSED
========================= 6 passed in 72.77s (0:01:12) =========================
+52
View File
@@ -0,0 +1,52 @@
docker compose --profile expiry up -d --build --wait api-short-ttl
Container messenger-lab5-postgres-1 Running
Container messenger-lab5-s3-1 Running
Container messenger-lab5-valkey-1 Running
Container messenger-lab5-api-short-ttl-1 Creating
Container messenger-lab5-api-short-ttl-1 Created
Container messenger-lab5-s3-1 Waiting
Container messenger-lab5-postgres-1 Waiting
Container messenger-lab5-s3-1 Healthy
Container messenger-lab5-s3-bootstrap-1 Starting
Container messenger-lab5-postgres-1 Healthy
Container messenger-lab5-migrate-1 Starting
Container messenger-lab5-s3-bootstrap-1 Started
Container messenger-lab5-migrate-1 Started
Container messenger-lab5-s3-bootstrap-1 Waiting
Container messenger-lab5-postgres-1 Waiting
Container messenger-lab5-migrate-1 Waiting
Container messenger-lab5-postgres-1 Healthy
Container messenger-lab5-migrate-1 Exited
Container messenger-lab5-s3-bootstrap-1 Exited
Container messenger-lab5-api-short-ttl-1 Starting
Container messenger-lab5-api-short-ttl-1 Started
Container messenger-lab5-migrate-1 Waiting
Container messenger-lab5-s3-1 Waiting
Container messenger-lab5-valkey-1 Waiting
Container messenger-lab5-s3-bootstrap-1 Waiting
Container messenger-lab5-api-short-ttl-1 Waiting
Container messenger-lab5-postgres-1 Waiting
Container messenger-lab5-migrate-1 Exited
Container messenger-lab5-s3-bootstrap-1 Exited
Container messenger-lab5-valkey-1 Healthy
Container messenger-lab5-s3-1 Healthy
Container messenger-lab5-postgres-1 Healthy
Container messenger-lab5-api-short-ttl-1 Healthy
EXPIRY_BASE_URL=http://localhost:8081 poetry run pytest student-tests/test_expiry.py -s; \
status=$?; docker compose --profile expiry stop api-short-ttl; exit $status
/Users/enterxx/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
============================= test session starts ==============================
platform darwin -- Python 3.12.12, pytest-9.1.1, pluggy-1.6.0 -- /Users/enterxx/Desktop/university/4course/mtusi2026lab5/.venv/bin/python
cachedir: .pytest_cache
rootdir: /Users/enterxx/Desktop/university/4course/mtusi2026lab5
configfile: pyproject.toml
plugins: anyio-4.15.1
collecting ... collected 2 items
student-tests/test_expiry.py::test_session_expires_after_short_ttl PASSED
student-tests/test_expiry.py::test_expires_at_matches_short_ttl PASSED
============================== 2 passed in 3.57s ===============================
Container messenger-lab5-api-short-ttl-1 Stopping
Container messenger-lab5-api-short-ttl-1 Stopped
+12
View File
@@ -0,0 +1,12 @@
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 132, "failed_attempts": 0, "first_recovery_seconds": 1.772}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
./scripts/restore.sh
Container messenger-lab5-api-2 Running
Container messenger-lab5-api-1 Starting
Container messenger-lab5-api-1 Started
Container messenger-lab5-api-1 Waiting
Container messenger-lab5-api-2 Waiting
Container messenger-lab5-api-1 Healthy
Container messenger-lab5-api-2 Healthy
+18
View File
@@ -0,0 +1,18 @@
./scripts/check_migrations.sh
2026-11-09 19:54:59.229 | INFO | infrastructure.dependencies.database:create_pool:69 - Установка соединения с базой данных psql
2026-11-09 19:54:59.305 | INFO | infrastructure.dependencies.database:create_pool:99 - Соединение с базой данных psql установлено. DB_NAME: test, pool: 2..10
пустой volume: таблиц в public = 0
API до migrate: В БД не применены миграции [1, 2, 3, 4, 5]: сначала запустите migrate
2026-11-09 19:54:59.333 | INFO | infrastructure.dependencies.database:apply_migrations:152 - Применена миграция 0001_init.sql
2026-11-09 19:54:59.336 | INFO | infrastructure.dependencies.database:apply_migrations:152 - Применена миграция 0002_message_idempotency.sql
2026-11-09 19:54:59.344 | INFO | infrastructure.dependencies.database:apply_migrations:152 - Применена миграция 0003_attachments.sql
2026-11-09 19:54:59.368 | INFO | infrastructure.dependencies.database:apply_migrations:152 - Применена миграция 0004_attachment_jobs.sql
2026-11-09 19:54:59.370 | INFO | infrastructure.dependencies.database:apply_migrations:152 - Применена миграция 0005_job_error_code.sql
2026-11-09 19:54:59.371 | INFO | infrastructure.dependencies.database:apply_migrations:157 - Схема БД в актуальной версии
запуск 1: schema_migrations = [(1, '0001_init'), (2, '0002_message_idempotency'), (3, '0003_attachments'), (4, '0004_attachment_jobs'), (5, '0005_job_error_code')], таблиц = 13
2026-11-09 19:54:59.373 | INFO | infrastructure.dependencies.database:apply_migrations:157 - Схема БД в актуальной версии
запуск 2: schema_migrations = [(1, '0001_init'), (2, '0002_message_idempotency'), (3, '0003_attachments'), (4, '0004_attachment_jobs'), (5, '0005_job_error_code')], таблиц = 13
2026-11-09 19:54:59.375 | INFO | infrastructure.dependencies.database:apply_migrations:157 - Схема БД в актуальной версии
запуск 3: schema_migrations = [(1, '0001_init'), (2, '0002_message_idempotency'), (3, '0003_attachments'), (4, '0004_attachment_jobs'), (5, '0005_job_error_code')], таблиц = 13
2026-11-09 19:54:59.376 | INFO | infrastructure.dependencies.database:check_migrations:179 - Схема БД совместима: версия 5
API после migrate: схема совместима
+3
View File
@@ -0,0 +1,3 @@
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
+27
View File
@@ -0,0 +1,27 @@
BASE_URL="http://localhost:8080" RUN_PIPELINE_FAILURE_TESTS=1 poetry run pytest student-tests/test_pipeline_failures.py -v -s
/Users/enterxx/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
============================= test session starts ==============================
platform darwin -- Python 3.12.12, pytest-9.1.1, pluggy-1.6.0 -- /Users/enterxx/Desktop/university/4course/mtusi2026lab5/.venv/bin/python
cachedir: .pytest_cache
rootdir: /Users/enterxx/Desktop/university/4course/mtusi2026lab5
configfile: pyproject.toml
plugins: anyio-4.15.1
collecting ... collected 7 items
student-tests/test_pipeline_failures.py::test_commit_publish_gap_worker_down_and_broker_volume HANDOFF: COMMIT -> API restart -> publish -> broker restart with volume -> ready 01a1c1ec-7b94-7c97-ab8d-d0d2e893d496
PASSED
student-tests/test_pipeline_failures.py::test_crash_before_ack_does_not_duplicate_effect[after-objects] CRASH/REDELIVERY: after-objects attempt 2 variants=3 01a1c1ec-ed54-7446-a47d-8851fc400e66
PASSED
student-tests/test_pipeline_failures.py::test_crash_before_ack_does_not_duplicate_effect[after-result] CRASH/REDELIVERY: after-result attempt 1 variants=3 01a1c1ee-89fb-779e-be9e-81a3544a205e
PASSED
student-tests/test_pipeline_failures.py::test_retry_exhaustion_and_safe_operator_replay RETRY: attempts=5, backoff seconds [6.043809, 4.38054, 5.512209, 9.174088] failed -> audited replay -> ready; ready replay no-op
PASSED
student-tests/test_pipeline_failures.py::test_publisher_crash_after_confirm_recovers_outbox CONFIRM GAP: confirmed publish -> crash -> outbox lease -> duplicate no-op 01a1c1ef-69aa-75e1-b54c-d1bf3316d9bf
PASSED
student-tests/test_pipeline_failures.py::test_staging_cleanup_retention_and_replay_guard CLEANUP: ready staging removed; expired failed retired; active queued preserved; expired replay rejected
PASSED
student-tests/test_pipeline_failures.py::test_worker_process_has_effective_memory_limit Linux RLIMIT_AS=128MiB: decoder refused 40Mpx without killing worker
PASSED
======================== 7 passed in 237.35s (0:03:57) =========================
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
+11
View File
@@ -0,0 +1,11 @@
After persistence hook: project messenger-lab5
/messenger-lab5-api-1 2026-11-09T19:57:14.96035305Z running healthy
/messenger-lab5-api-2 2026-11-09T19:57:14.982231217Z running healthy
/messenger-lab5-broker-1 2026-11-09T19:56:49.183801511Z running healthy
/messenger-lab5-dispatcher-1 2026-11-09T19:57:13.860204841Z running healthy
/messenger-lab5-janitor-1 2026-11-09T19:57:15.214248217Z running healthy
/messenger-lab5-nginx-1 2026-11-09T19:57:16.063443301Z running healthy
/messenger-lab5-postgres-1 2026-11-09T19:56:48.389312427Z running healthy
/messenger-lab5-s3-1 2026-11-09T19:57:13.160023341Z running healthy
/messenger-lab5-valkey-1 2026-11-09T19:56:48.29408776Z running healthy
/messenger-lab5-worker-1 2026-11-09T19:57:13.722188758Z running healthy
+23
View File
@@ -0,0 +1,23 @@
BASE_URL="http://localhost:8080" RUN_STORAGE_TESTS=1 poetry run pytest student-tests/test_storage_security.py student-tests/test_storage_consistency.py -s
/Users/enterxx/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
============================= test session starts ==============================
platform darwin -- Python 3.12.12, pytest-9.1.1, pluggy-1.6.0 -- /Users/enterxx/Desktop/university/4course/mtusi2026lab5/.venv/bin/python
cachedir: .pytest_cache
rootdir: /Users/enterxx/Desktop/university/4course/mtusi2026lab5
configfile: pyproject.toml
plugins: anyio-4.15.1
collecting ... collected 8 items
student-tests/test_storage_security.py::test_anonymous_s3_access_is_denied PASSED
student-tests/test_storage_security.py::test_api_credentials_are_limited_to_own_bucket_objects PASSED
student-tests/test_storage_security.py::test_api_container_has_no_admin_credentials PASSED
student-tests/test_storage_security.py::test_admin_interfaces_are_not_reachable PASSED
student-tests/test_storage_security.py::test_balancer_network_cannot_reach_storage PASSED
student-tests/test_storage_security.py::test_bucket_bootstrap_is_idempotent PASSED
student-tests/test_storage_consistency.py::test_janitor_cleans_only_stale_unaccounted_data
JANITOR REPORT: {"dry_run": false, "unfinished_claimed": 2, "unfinished_objects_deleted": 2, "unfinished_rows_deleted": 2, "objects_scanned": 408, "orphan_objects_found": 5, "orphan_objects_deleted": 5}
PASSED
student-tests/test_storage_consistency.py::test_interrupted_upload_leaves_nothing PASSED
======================== 8 passed in 108.63s (0:01:48) =========================
+232
View File
@@ -0,0 +1,232 @@
BASE_URL="http://localhost:8080" poetry run pytest
/Users/enterxx/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
============================= test session starts ==============================
platform darwin -- Python 3.12.12, pytest-9.1.1, pluggy-1.6.0 -- /Users/enterxx/Desktop/university/4course/mtusi2026lab5/.venv/bin/python
cachedir: .pytest_cache
rootdir: /Users/enterxx/Desktop/university/4course/mtusi2026lab5
configfile: pyproject.toml
testpaths: student-tests
plugins: anyio-4.15.1
collecting ... collected 218 items
student-tests/test_attachment_failover.py::test_download_survives_stop_of_uploading_replica SKIPPED [ 0%]
student-tests/test_attachments.py::test_upload_and_download_byte_exact[png-fixture] PASSED [ 0%]
student-tests/test_attachments.py::test_upload_and_download_byte_exact[jpeg-baseline] PASSED [ 1%]
student-tests/test_attachments.py::test_upload_and_download_byte_exact[jpeg-progressive] PASSED [ 1%]
student-tests/test_attachments.py::test_public_api_does_not_expose_storage_details PASSED [ 2%]
student-tests/test_attachments.py::test_unicode_filename_is_preserved PASSED [ 2%]
student-tests/test_attachments.py::test_outsider_and_unknown_get_indistinguishable_404 PASSED [ 3%]
student-tests/test_attachments.py::test_outsider_cannot_upload_into_foreign_chat PASSED [ 3%]
student-tests/test_attachments.py::test_authentication_is_required PASSED [ 4%]
student-tests/test_attachments.py::test_variants_and_malformed_ids PASSED [ 4%]
student-tests/test_attachments.py::test_exactly_max_bytes_is_accepted PASSED [ 5%]
student-tests/test_attachments.py::test_too_large_file_is_rejected_by_api PASSED [ 5%]
student-tests/test_attachments.py::test_huge_body_is_rejected_by_balancer PASSED [ 5%]
student-tests/test_attachments.py::test_empty_body_is_rejected PASSED [ 6%]
student-tests/test_attachments.py::test_pixel_limit_applies_before_decoding[8000-5000-202] PASSED [ 6%]
student-tests/test_attachments.py::test_pixel_limit_applies_before_decoding[8000-5001-413] PASSED [ 7%]
student-tests/test_attachments.py::test_pixel_limit_applies_before_decoding[20000-20000-413] PASSED [ 7%]
student-tests/test_attachments.py::test_corrupted_image_is_rejected[png-truncated] PASSED [ 8%]
student-tests/test_attachments.py::test_corrupted_image_is_rejected[png-bit-flip-crc] PASSED [ 8%]
student-tests/test_attachments.py::test_corrupted_image_is_rejected[png-signature-garbage] PASSED [ 9%]
student-tests/test_attachments.py::test_corrupted_image_is_rejected[png-without-iend] PASSED [ 9%]
student-tests/test_attachments.py::test_corrupted_image_is_rejected[jpeg-truncated] PASSED [ 10%]
student-tests/test_attachments.py::test_corrupted_image_is_rejected[jpeg-signature-garbage] PASSED [ 10%]
student-tests/test_attachments.py::test_mime_spoofing_is_rejected[png-as-jpeg] PASSED [ 11%]
student-tests/test_attachments.py::test_mime_spoofing_is_rejected[jpeg-as-png] PASSED [ 11%]
student-tests/test_attachments.py::test_mime_spoofing_is_rejected[gif-as-png] PASSED [ 11%]
student-tests/test_attachments.py::test_mime_spoofing_is_rejected[svg-as-png] PASSED [ 12%]
student-tests/test_attachments.py::test_mime_spoofing_is_rejected[pdf-as-jpeg] PASSED [ 12%]
student-tests/test_attachments.py::test_mime_spoofing_is_rejected[octet-stream] PASSED [ 13%]
student-tests/test_attachments.py::test_mime_spoofing_is_rejected[image-gif] PASSED [ 13%]
student-tests/test_attachments.py::test_mime_spoofing_is_rejected[text-html] PASSED [ 14%]
student-tests/test_attachments.py::test_mime_spoofing_is_rejected[no-content-type] PASSED [ 14%]
student-tests/test_attachments.py::test_content_type_parameters_are_ignored PASSED [ 15%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[traversal] PASSED [ 15%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[slash] PASSED [ 16%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[backslash] PASSED [ 16%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[nul] PASSED [ 16%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[newline] PASSED [ 17%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[tab] PASSED [ 17%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[control] PASSED [ 18%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[bidi-override] PASSED [ 18%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[empty] PASSED [ 19%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[blank] PASSED [ 19%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[dot] PASSED [ 20%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[dotdot] PASSED [ 20%]
student-tests/test_attachments.py::test_dangerous_filename_is_rejected[too-long] PASSED [ 21%]
student-tests/test_attachments.py::test_missing_filename_is_rejected PASSED [ 21%]
student-tests/test_attachments.py::test_longest_filename_is_accepted PASSED [ 22%]
student-tests/test_attachments.py::test_same_filename_gets_separate_attachments PASSED [ 22%]
student-tests/test_auth.py::test_login_returns_opaque_bearer_session PASSED [ 22%]
student-tests/test_auth.py::test_wrong_password_and_unknown_user_are_indistinguishable PASSED [ 23%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[None] PASSED [ 23%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[] PASSED [ 24%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[Basic] PASSED [ 24%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[Basic !!!not-base64!!!] PASSED [ 25%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[Basic bm8tY29sb24taGVyZQ==] PASSED [ 25%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[Basic //46cGFzc3dvcmQ=] PASSED [ 26%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[Bearer some-token] PASSED [ 26%]
student-tests/test_auth.py::test_utf8_password_with_colon PASSED [ 27%]
student-tests/test_auth.py::test_basic_is_rejected_on_business_endpoints PASSED [ 27%]
student-tests/test_auth.py::test_logout_revokes_only_current_session PASSED [ 27%]
student-tests/test_auth.py::test_logout_without_token PASSED [ 28%]
student-tests/test_auth.py::test_relogin_after_logout PASSED [ 28%]
student-tests/test_auth.py::test_password_is_not_stored_in_plaintext PASSED [ 29%]
student-tests/test_balancing.py::test_one_session_is_served_by_several_replicas PASSED [ 29%]
student-tests/test_balancing.py::test_write_is_visible_through_every_replica PASSED [ 30%]
student-tests/test_balancing.py::test_logout_applies_to_all_replicas PASSED [ 30%]
student-tests/test_balancing.py::test_every_api_response_has_instance_id PASSED [ 31%]
student-tests/test_concurrency.py::test_parallel_messages_are_not_lost_or_duplicated PASSED [ 31%]
student-tests/test_dependency_failures.py::test_valkey_down_cache_is_bypassed SKIPPED [ 32%]
student-tests/test_dependency_failures.py::test_logout_during_valkey_outage_is_not_resurrected SKIPPED [ 32%]
student-tests/test_dependency_failures.py::test_postgres_down_returns_bounded_503_and_no_anonymous_access SKIPPED [ 33%]
student-tests/test_dependency_failures.py::test_session_survives_postgres_restart SKIPPED [ 33%]
student-tests/test_expiry.py::test_session_expires_after_short_ttl SKIPPED [ 33%]
student-tests/test_expiry.py::test_expires_at_matches_short_ttl SKIPPED [ 34%]
student-tests/test_foreign_chat.py::test_outsider_cannot_access_chat PASSED [ 34%]
student-tests/test_foreign_chat.py::test_foreign_and_missing_chat_are_indistinguishable PASSED [ 35%]
student-tests/test_foreign_chat.py::test_chat_list_contains_only_own_chats PASSED [ 35%]
student-tests/test_health.py::test_health_endpoints_have_request_id PASSED [ 36%]
student-tests/test_health.py::test_unknown_route_uses_error_format PASSED [ 36%]
student-tests/test_idempotency.py::test_replay_returns_same_message PASSED [ 37%]
student-tests/test_idempotency.py::test_replay_ignores_json_formatting PASSED [ 37%]
student-tests/test_idempotency.py::test_same_key_with_other_body_is_conflict PASSED [ 38%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_rejected[headers0] PASSED [ 38%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_rejected[headers1] PASSED [ 38%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_rejected[headers2] PASSED [ 39%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_rejected[headers3] PASSED [ 39%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_rejected[headers4] PASSED [ 40%]
student-tests/test_idempotency.py::test_missing_or_invalid_key_is_rejected[headers5] PASSED [ 40%]
student-tests/test_idempotency.py::test_key_boundaries_are_accepted[xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx] PASSED [ 41%]
student-tests/test_idempotency.py::test_key_boundaries_are_accepted[Az09._:-] PASSED [ 41%]
student-tests/test_idempotency.py::test_key_scope_is_user_and_chat PASSED [ 42%]
student-tests/test_idempotency.py::test_replay_rechecks_session_and_access PASSED [ 42%]
student-tests/test_idempotency.py::test_expired_key_can_be_reused PASSED [ 43%]
student-tests/test_idempotency.py::test_parallel_replays_through_replicas_create_one_message PASSED [ 43%]
student-tests/test_idempotency.py::test_parallel_same_key_with_different_bodies PASSED [ 44%]
student-tests/test_invalid_json.py::test_malformed_json_on_register[{"username": "abc",] PASSED [ 44%]
student-tests/test_invalid_json.py::test_malformed_json_on_register[not json at all] PASSED [ 44%]
student-tests/test_invalid_json.py::test_malformed_json_on_register[{"text": "\xff\xfe"}] PASSED [ 45%]
student-tests/test_invalid_json.py::test_malformed_json_on_register[] PASSED [ 45%]
student-tests/test_invalid_json.py::test_malformed_json_on_create_chat_and_message[{"username": "abc",] PASSED [ 46%]
student-tests/test_invalid_json.py::test_malformed_json_on_create_chat_and_message[not json at all] PASSED [ 46%]
student-tests/test_invalid_json.py::test_malformed_json_on_create_chat_and_message[{"text": "\xff\xfe"}] PASSED [ 47%]
student-tests/test_invalid_json.py::test_malformed_json_on_create_chat_and_message[] PASSED [ 47%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body0] PASSED [ 48%]
student-tests/test_invalid_json.py::test_invalid_user_payload[alice] PASSED [ 48%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body2] PASSED [ 49%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body3] PASSED [ 49%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body4] PASSED [ 50%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body5] PASSED [ 50%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body6] PASSED [ 50%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body7] PASSED [ 51%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body8] PASSED [ 51%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body9] PASSED [ 52%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body10] PASSED [ 52%]
student-tests/test_invalid_json.py::test_invalid_message_payload[body0] PASSED [ 53%]
student-tests/test_invalid_json.py::test_invalid_message_payload[body1] PASSED [ 53%]
student-tests/test_invalid_json.py::test_invalid_message_payload[body2] PASSED [ 54%]
student-tests/test_invalid_json.py::test_invalid_chat_payload PASSED [ 54%]
student-tests/test_message_attachments.py::test_message_with_attachment_is_readable_by_members PASSED [ 55%]
student-tests/test_message_attachments.py::test_any_member_may_reference_chat_attachment_and_order_is_kept PASSED [ 55%]
student-tests/test_message_attachments.py::test_text_message_has_empty_attachment_ids PASSED [ 55%]
student-tests/test_message_attachments.py::test_attachment_of_other_chat_is_rejected PASSED [ 56%]
student-tests/test_message_attachments.py::test_foreign_attachment_id_is_rejected PASSED [ 56%]
student-tests/test_message_attachments.py::test_invalid_attachment_ids_are_rejected[empty-text] PASSED [ 57%]
student-tests/test_message_attachments.py::test_invalid_attachment_ids_are_rejected[blank-text] PASSED [ 57%]
student-tests/test_message_attachments.py::test_invalid_attachment_ids_are_rejected[empty-both] PASSED [ 58%]
student-tests/test_message_attachments.py::test_invalid_attachment_ids_are_rejected[bad-uuid] PASSED [ 58%]
student-tests/test_message_attachments.py::test_invalid_attachment_ids_are_rejected[not-array] PASSED [ 59%]
student-tests/test_message_attachments.py::test_invalid_attachment_ids_are_rejected[null] PASSED [ 59%]
student-tests/test_message_attachments.py::test_invalid_attachment_ids_are_rejected[duplicates] PASSED [ 60%]
student-tests/test_message_attachments.py::test_invalid_attachment_ids_are_rejected[too-many] PASSED [ 60%]
student-tests/test_message_attachments.py::test_idempotent_replay_with_attachments PASSED [ 61%]
student-tests/test_message_attachments.py::test_missing_attachment_ids_equals_empty_list_for_idempotency PASSED [ 61%]
student-tests/test_messages.py::test_empty_or_blank_message_is_rejected[] PASSED [ 61%]
student-tests/test_messages.py::test_empty_or_blank_message_is_rejected[ ] PASSED [ 62%]
student-tests/test_messages.py::test_empty_or_blank_message_is_rejected[ \n\t ] PASSED [ 62%]
student-tests/test_messages.py::test_empty_or_blank_message_is_rejected[\u3000] PASSED [ 63%]
student-tests/test_messages.py::test_message_length_is_counted_in_code_points PASSED [ 63%]
student-tests/test_messages.py::test_unicode_is_preserved PASSED [ 64%]
student-tests/test_messages.py::test_nul_character_is_rejected PASSED [ 64%]
student-tests/test_messages.py::test_sender_is_taken_from_session PASSED [ 65%]
student-tests/test_pagination.py::test_walk_message_pages[7-3-3] PASSED [ 65%]
student-tests/test_pagination.py::test_walk_message_pages[6-3-2] PASSED [ 66%]
student-tests/test_pagination.py::test_walk_message_pages[5-1-5] PASSED [ 66%]
student-tests/test_pagination.py::test_walk_message_pages[3-100-1] PASSED [ 66%]
student-tests/test_pagination.py::test_limit_can_change_between_pages PASSED [ 67%]
student-tests/test_pagination.py::test_new_message_appears_after_cursor PASSED [ 67%]
student-tests/test_pagination.py::test_cursor_is_bound_to_chat PASSED [ 68%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params0] PASSED [ 68%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params1] PASSED [ 69%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params2] PASSED [ 69%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params3] PASSED [ 70%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params4] PASSED [ 70%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params5] PASSED [ 71%]
student-tests/test_pagination.py::test_walk_chat_list_pages PASSED [ 71%]
student-tests/test_pagination.py::test_chat_cursor_is_bound_to_user PASSED [ 72%]
student-tests/test_pipeline.py::test_variants_have_real_dimensions_checksums_and_no_metadata PASSED [ 72%]
student-tests/test_pipeline.py::test_orientation_and_no_upscale PASSED [ 72%]
student-tests/test_pipeline.py::test_permanent_failure_is_observable_and_not_linkable PASSED [ 73%]
student-tests/test_pipeline_failures.py::test_commit_publish_gap_worker_down_and_broker_volume SKIPPED [ 73%]
student-tests/test_pipeline_failures.py::test_crash_before_ack_does_not_duplicate_effect[after-objects] SKIPPED [ 74%]
student-tests/test_pipeline_failures.py::test_crash_before_ack_does_not_duplicate_effect[after-result] SKIPPED [ 74%]
student-tests/test_pipeline_failures.py::test_retry_exhaustion_and_safe_operator_replay SKIPPED [ 75%]
student-tests/test_pipeline_failures.py::test_publisher_crash_after_confirm_recovers_outbox SKIPPED [ 75%]
student-tests/test_pipeline_failures.py::test_staging_cleanup_retention_and_replay_guard SKIPPED [ 76%]
student-tests/test_pipeline_failures.py::test_worker_process_has_effective_memory_limit SKIPPED [ 76%]
student-tests/test_pipeline_races.py::test_replay_waiting_for_cleanup_rechecks_retired_source PASSED [ 77%]
student-tests/test_storage_consistency.py::test_janitor_cleans_only_stale_unaccounted_data SKIPPED [ 77%]
student-tests/test_storage_consistency.py::test_interrupted_upload_leaves_nothing SKIPPED [ 77%]
student-tests/test_storage_failures.py::test_s3_outage_is_isolated_and_leaves_no_garbage SKIPPED [ 78%]
student-tests/test_storage_security.py::test_anonymous_s3_access_is_denied SKIPPED [ 78%]
student-tests/test_storage_security.py::test_api_credentials_are_limited_to_own_bucket_objects SKIPPED [ 79%]
student-tests/test_storage_security.py::test_api_container_has_no_admin_credentials SKIPPED [ 79%]
student-tests/test_storage_security.py::test_admin_interfaces_are_not_reachable SKIPPED [ 80%]
student-tests/test_storage_security.py::test_balancer_network_cannot_reach_storage SKIPPED [ 80%]
student-tests/test_storage_security.py::test_bucket_bootstrap_is_idempotent SKIPPED [ 81%]
student-tests/test_transactions.py::test_same_username_race_creates_exactly_one_user PASSED [ 81%]
student-tests/test_transactions.py::test_failed_chat_creation_is_rolled_back PASSED [ 82%]
student-tests/test_transactions.py::test_successful_chat_creation_commits_all_members PASSED [ 82%]
student-tests/test_users.py::test_duplicate_username_is_conflict PASSED [ 83%]
student-tests/test_users.py::test_registration_never_returns_password PASSED [ 83%]
student-tests/test_users.py::test_invalid_password_is_rejected[None] PASSED [ 83%]
student-tests/test_users.py::test_invalid_password_is_rejected[] PASSED [ 84%]
student-tests/test_users.py::test_invalid_password_is_rejected[\u043a\u043e\u0440\u043e\u0442\u043a\u0438\u0439] PASSED [ 84%]
student-tests/test_users.py::test_invalid_password_is_rejected[xxxxxxxxxxx] PASSED [ 85%]
student-tests/test_users.py::test_invalid_password_is_rejected[xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx] PASSED [ 85%]
student-tests/test_users.py::test_invalid_password_is_rejected[123456789012] PASSED [ 86%]
student-tests/test_users.py::test_password_length_is_counted_in_code_points PASSED [ 86%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers0] PASSED [ 87%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers1] PASSED [ 87%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers2] PASSED [ 88%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers3] PASSED [ 88%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers4] PASSED [ 88%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers5] PASSED [ 89%]
student-tests/test_users.py::test_x_user_id_gives_no_access PASSED [ 89%]
student-tests/test_users.py::test_current_user PASSED [ 90%]
student-tests/unit/test_unit_attachment_service.py::test_success_stores_staging_and_queued_row PASSED [ 90%]
student-tests/unit/test_unit_attachment_service.py::test_s3_failure_after_write_is_compensated PASSED [ 91%]
student-tests/unit/test_unit_attachment_service.py::test_db_failure_between_s3_and_commit_is_compensated PASSED [ 91%]
student-tests/unit/test_unit_attachment_service.py::test_db_down_leaves_pending_row_that_janitor_cleans PASSED [ 92%]
student-tests/unit/test_unit_attachment_service.py::test_s3_down_during_compensation_leaves_deleting_row_for_janitor PASSED [ 92%]
student-tests/unit/test_unit_attachment_service.py::test_store_timeout_is_compensated PASSED [ 93%]
student-tests/unit/test_unit_attachment_service.py::test_cancelled_upload_is_compensated PASSED [ 93%]
student-tests/unit/test_unit_attachment_service.py::test_upload_claimed_by_janitor_is_not_confirmed PASSED [ 94%]
student-tests/unit/test_unit_attachment_service.py::test_validation_errors_store_nothing PASSED [ 94%]
student-tests/unit/test_unit_attachment_service.py::test_declared_length_over_limit_is_rejected_without_reading PASSED [ 94%]
student-tests/unit/test_unit_attachment_service.py::test_streamed_body_over_limit_stops_reading PASSED [ 95%]
student-tests/unit/test_unit_attachment_service.py::test_foreign_chat_is_404_before_reading_body PASSED [ 95%]
student-tests/unit/test_unit_attachment_service.py::test_missing_variant_is_404 PASSED [ 96%]
student-tests/unit/test_unit_broker.py::test_publish_recovers_after_connection_loss_during_binding[False] PASSED [ 96%]
student-tests/unit/test_unit_broker.py::test_publish_recovers_after_connection_loss_during_binding[True] PASSED [ 97%]
student-tests/unit/test_unit_image_pipeline.py::test_checksum_mismatch_cannot_publish_original PASSED [ 97%]
student-tests/unit/test_unit_image_pipeline.py::test_timeout_kills_child_and_leaves_no_effect PASSED [ 98%]
student-tests/unit/test_unit_storage_reconciler.py::test_reconcile_removes_only_stale_unaccounted_data PASSED [ 98%]
student-tests/unit/test_unit_storage_reconciler.py::test_dry_run_changes_nothing PASSED [ 99%]
student-tests/unit/test_unit_storage_reconciler.py::test_second_run_is_noop PASSED [ 99%]
student-tests/unit/test_unit_storage_reconciler.py::test_interrupted_cleanup_is_resumed PASSED [100%]
======================= 195 passed, 23 skipped in 46.24s =======================
+57
View File
@@ -0,0 +1,57 @@
-- Durable handoff: staging + queued/job/outbox фиксируются до ответа 202.
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check
CHECK (status IN ('pending', 'queued', 'processing', 'ready', 'failed', 'deleting'));
ALTER TABLE attachments ADD COLUMN staging_key text;
ALTER TABLE attachments ADD COLUMN error_code text;
UPDATE attachments SET staging_key = object_key WHERE status IN ('pending', 'deleting');
CREATE TABLE attachment_jobs (
id uuid PRIMARY KEY DEFAULT uuidv7(),
attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id),
pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version = 1),
attempt integer NOT NULL DEFAULT 1 CHECK (attempt > 0),
failures integer NOT NULL DEFAULT 0 CHECK (failures >= 0),
available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
lease_token uuid,
lease_until timestamptz,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX attachment_jobs_lease_idx ON attachment_jobs (lease_until)
WHERE lease_until IS NOT NULL;
CREATE TABLE attachment_outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs(id),
attempt integer NOT NULL CHECK (attempt > 0),
available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
published_at timestamptz,
claim_token uuid,
claim_until timestamptz,
UNIQUE (job_id, attempt)
);
CREATE INDEX attachment_outbox_pending_idx ON attachment_outbox (available_at, id)
WHERE published_at IS NULL;
CREATE TABLE attachment_variants (
attachment_id uuid NOT NULL REFERENCES attachments(id),
pipeline_version integer NOT NULL CHECK (pipeline_version = 1),
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
object_key text NOT NULL UNIQUE,
content_type text NOT NULL,
size_bytes integer NOT NULL CHECK (size_bytes > 0),
width integer NOT NULL CHECK (width > 0),
height integer NOT NULL CHECK (height > 0),
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
PRIMARY KEY (attachment_id, pipeline_version, name)
);
-- failed + error_code в attachments — устойчивый реестр ошибок вместо DLQ.
CREATE TABLE attachment_replays (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs(id),
attempt integer NOT NULL,
operator text NOT NULL CHECK (char_length(operator) BETWEEN 1 AND 128),
reason text NOT NULL CHECK (char_length(reason) BETWEEN 1 AND 512),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
+2
View File
@@ -0,0 +1,2 @@
-- Сохраняем безопасную причину временной ошибки после retry_exhausted.
ALTER TABLE attachment_jobs ADD COLUMN last_error_code text;
Generated
+49 -1
View File
@@ -1,5 +1,21 @@
# This file is automatically @generated by Poetry 2.2.1 and should not be changed by hand.
[[package]]
name = "aio-pika"
version = "9.5.8"
description = "Wrapper around the aiormq for asyncio and humans"
optional = false
python-versions = "<4.0,>=3.10"
groups = ["main"]
files = [
{file = "aio_pika-9.5.8-py3-none-any.whl", hash = "sha256:f4c6cb8a6c5176d00f39fd7431e9702e638449bc6e86d1769ad7548b2a506a8d"},
{file = "aio_pika-9.5.8.tar.gz", hash = "sha256:7c36874115f522bbe7486c46d8dd711a4dbedd67c4e8a8c47efe593d01862c62"},
]
[package.dependencies]
aiormq = ">=6.8,<7.0"
yarl = "*"
[[package]]
name = "aiobotocore"
version = "3.9.1"
@@ -233,6 +249,22 @@ files = [
{file = "aioitertools-0.13.0.tar.gz", hash = "sha256:620bd241acc0bbb9ec819f1ab215866871b4bbd1f73836a55f799200ee86950c"},
]
[[package]]
name = "aiormq"
version = "6.9.4"
description = "Pure python AMQP asynchronous client library"
optional = false
python-versions = "<4,>=3.10"
groups = ["main"]
files = [
{file = "aiormq-6.9.4-py3-none-any.whl", hash = "sha256:726a8586695e863fba68cf88842065ab12348c9438dcebdfc9d0bddaf6083277"},
{file = "aiormq-6.9.4.tar.gz", hash = "sha256:0e7c01b662804e1cc7ace9a17794e8c1192a27fc2afa96162362a6e61ae8e8ef"},
]
[package.dependencies]
pamqp = "3.3.0"
yarl = "*"
[[package]]
name = "aiosignal"
version = "1.4.0"
@@ -1118,6 +1150,22 @@ files = [
{file = "packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79"},
]
[[package]]
name = "pamqp"
version = "3.3.0"
description = "RabbitMQ Focused AMQP low-level library"
optional = false
python-versions = ">=3.7"
groups = ["main"]
files = [
{file = "pamqp-3.3.0-py2.py3-none-any.whl", hash = "sha256:c901a684794157ae39b52cbf700db8c9aae7a470f13528b9d7b4e5f7202f8eb0"},
{file = "pamqp-3.3.0.tar.gz", hash = "sha256:40b8795bd4efcf2b0f8821c1de83d12ca16d5760f4507836267fd7a02b06763b"},
]
[package.extras]
codegen = ["lxml", "requests", "yapf"]
testing = ["coverage", "flake8", "flake8-comprehensions", "flake8-deprecated", "flake8-import-order", "flake8-print", "flake8-quotes", "flake8-rst-docstrings", "flake8-tuple", "yapf"]
[[package]]
name = "pillow"
version = "12.3.0"
@@ -2005,4 +2053,4 @@ propcache = ">=0.2.1"
[metadata]
lock-version = "2.1"
python-versions = ">=3.12,<3.13"
content-hash = "f1acc20bff882992d1b301bd15eeb72e0d6b54e0e7419cf564876807ffbfcb39"
content-hash = "69933c0954709c4398ecd965170999e4a57c4fb1738dac53d799e2741e0db2e8"
+3 -2
View File
@@ -1,7 +1,7 @@
[tool.poetry]
name = "max2"
version = "1.2.0"
description = "Мессенджер на PostgreSQL и Valkey, лабораторная 3"
version = "1.5.0"
description = "Мессенджер с RabbitMQ и асинхронной обработкой изображений, лабораторная 5"
authors = ["Саватеев Артём"]
package-mode = false
@@ -17,6 +17,7 @@ redis = "6.4.0"
argon2-cffi = "25.1.0"
aiobotocore = "3.9.1"
pillow = "12.3.0"
aio-pika = "9.5.8"
[tool.poetry.group.dev.dependencies]
pytest = "9.1.1"
+15
View File
@@ -71,3 +71,18 @@ cat >secrets/s3_identities.json <<EOF
EOF
chmod 644 secrets/s3_identities.json
echo "secrets ready in secrets/ (values are not printed)"
# URL хранится в файле и монтируется только dispatcher/worker.
if [ ! -s secrets/broker_url ]; then
python3 - <<'PYTHON'
from pathlib import Path
from urllib.parse import quote
values = dict(line.split("=", 1) for line in Path(".env").read_text().splitlines()
if "=" in line and not line.startswith("#"))
user = quote(values.get("RABBITMQ_USER", "test"), safe="")
password = quote(values.get("RABBITMQ_PASS", "test"), safe="")
Path("secrets/broker_url").write_text(f"amqp://{user}:{password}@broker:5672/")
PYTHON
echo "created secrets/broker_url"
fi
chmod 644 secrets/broker_url
+3 -3
View File
@@ -1,12 +1,12 @@
#!/bin/sh
set -eu
# Перезапуск всего стенда с сохранением volumes: хранилища (PostgreSQL, Valkey,
# S3), затем все API-реплики, janitor и балансировщик. Никаких down -v, flush
# S3, RabbitMQ), затем API, worker, dispatcher, janitor и балансировщик. Никаких down -v, flush
# или повторного seed; migrate и s3-bootstrap не запускаются — схема и bucket
# уже в volumes. Готовность ждёт тест.
cd "$(dirname "$0")/.."
ENV_FILE="${ENV_FILE:-.env}"
docker compose --env-file "$ENV_FILE" restart --no-deps postgres valkey s3
docker compose --env-file "$ENV_FILE" restart --no-deps api janitor
docker compose --env-file "$ENV_FILE" restart --no-deps postgres valkey s3 broker
docker compose --env-file "$ENV_FILE" restart --no-deps api janitor worker dispatcher
docker compose --env-file "$ENV_FILE" restart --no-deps nginx
+3 -2
View File
@@ -174,7 +174,7 @@ def upload_once(base: str, token: str, chat_id: str, content: bytes, content_typ
except OSError as error:
return {"status": None, "error": type(error).__name__, "seconds": time.monotonic() - started}
result = {"status": status, "instance": instance, "seconds": time.monotonic() - started}
if status == 201:
if status == 202:
result["id"] = json.loads(body)["id"]
return result
@@ -218,10 +218,11 @@ def run_round(client: Client, actor: dict, chat: dict, profile: str, content: by
sampler.stop()
after = {container_name(c): process_status(c) for c in containers}
ok = [r for r in results if r.get("status") == 201]
ok = [r for r in results if r.get("status") == 202]
sample = ok[0]["id"] if ok else None
checksum_ok = None
if sample:
client.wait_ready(actor, {"id": sample})
downloaded = client.call("GET", f"/api/v1/attachments/{sample}/content", actor=actor)["bytes"]
checksum_ok = hashlib.sha256(downloaded).digest() == hashlib.sha256(content).digest()
seconds = [r["seconds"] for r in ok]
@@ -27,7 +27,7 @@ IMAGE_BODY = {
@attachments_router.post(
"/chats/{chat_id}/attachments",
status_code=status.HTTP_201_CREATED,
status_code=status.HTTP_202_ACCEPTED,
response_model=AttachmentSchema,
openapi_extra={"requestBody": {"required": True, "content": IMAGE_BODY}},
)
@@ -41,8 +41,7 @@ async def upload_attachment(
service: AttachmentService = Depends(ServiceCreator.get_attachment_service),
) -> AttachmentSchema:
"""
Сырые байты одного PNG/JPEG, не multipart. 201 ready — только после
сохранения оригинала в S3 и метаданных в PostgreSQL.
Сырые байты одного PNG/JPEG, не multipart. 202 queued — после staging и транзакции job/outbox; resize выполняет worker.
"""
return await service.upload(
current_user,
+12
View File
@@ -74,3 +74,15 @@ INSTANCE_ID = secrets.token_hex(6)
INSTANCE_ID_FILE = Path(tempfile.gettempdir()) / "instance-id"
# Время последней успешной сверки janitor — для healthcheck его контейнера
JANITOR_HEARTBEAT_FILE = Path(tempfile.gettempdir()) / "janitor-heartbeat"
BROKER_URL_FILE = Path(env.str("BROKER_URL_FILE"))
WORKER_CONCURRENCY = env.int("WORKER_CONCURRENCY")
WORKER_PREFETCH = env.int("WORKER_PREFETCH")
JOB_MAX_ATTEMPTS = env.int("JOB_MAX_ATTEMPTS")
JOB_TIMEOUT_SECONDS = env.int("JOB_TIMEOUT_SECONDS")
JOB_LEASE_SECONDS = env.int("JOB_LEASE_SECONDS")
JOB_RETRY_BASE_SECONDS = env.float("JOB_RETRY_BASE_SECONDS")
JOB_RETRY_MAX_SECONDS = env.float("JOB_RETRY_MAX_SECONDS")
IMAGE_PROCESS_MEMORY_MB = env.int("IMAGE_PROCESS_MEMORY_MB")
STAGING_RETENTION_SECONDS = env.int("STAGING_RETENTION_SECONDS")
OUTBOX_POLL_SECONDS = env.float("OUTBOX_POLL_SECONDS")
+52
View File
@@ -0,0 +1,52 @@
import asyncio
import random
import signal
from pathlib import Path
from config import DB_STARTUP_TIMEOUT_SEC, LOGGER
from config.settings import BROKER_URL_FILE, OUTBOX_POLL_SECONDS, WORKER_PREFETCH
from infrastructure import database_pool_manager
from infrastructure.broker import RabbitBrokerManager
from infrastructure.dependencies.jobs import create_job_repository
from infrastructure.utils.faults import crash_once
async def main() -> None:
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for signum in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(signum, stop.set)
await database_pool_manager.create_pool(DB_STARTUP_TIMEOUT_SEC)
await database_pool_manager.check_migrations()
jobs = create_job_repository()
broker = RabbitBrokerManager(BROKER_URL_FILE, WORKER_PREFETCH)
failures = 0
try:
while not stop.is_set():
delay = OUTBOX_POLL_SECONDS
try:
await jobs.recover_expired()
event = await jobs.claim_event()
if event is not None:
await broker.publish(event.message)
crash_once("after-publish")
await jobs.mark_published(event)
delay = 0
failures = 0
Path("/tmp/dispatcher-heartbeat").touch()
except Exception as error:
failures += 1
LOGGER.warning(f"Outbox: {type(error).__name__}, намерение сохранено")
delay = random.uniform(0.5, min(10, 2 ** min(failures, 4)))
if delay:
try:
await asyncio.wait_for(stop.wait(), delay)
except TimeoutError:
pass
finally:
await broker.close()
await database_pool_manager.close()
if __name__ == "__main__":
asyncio.run(main())
+17 -14
View File
@@ -14,9 +14,7 @@ ORIGINAL_OBJECT_PREFIX = "originals/"
# Невидимое управление направлением текста: «photo‮gnp.exe» отображается
# как «photoexe.png»
BIDI_CONTROL_CHARACTERS = frozenset(
"‎‏‪‫‬‭‮⁦⁧⁨⁩"
)
BIDI_CONTROL_CHARACTERS = frozenset("‎‏‪‫‬‭‮⁦⁧⁨⁩")
def ensure_safe_filename(value: str) -> str:
@@ -51,23 +49,18 @@ class AttachmentContentType(StrEnum):
class AttachmentStatus(StrEnum):
"""
Состояние строки вложения в БД.
pending — строка записана до PUT в S3; объект мог не дойти до S3
или остаться без подтверждения (сбой между S3 и БД)
ready — оригинал в S3 и метаданные подтверждены; только его видит API
deleting — незавершённая загрузка забрана на очистку: сначала удаляется
объект S3, затем строка
"""
"""Публичные состояния pipeline и внутренние состояния приёма/очистки"""
PENDING = "pending"
QUEUED = "queued"
PROCESSING = "processing"
READY = "ready"
FAILED = "failed"
DELETING = "deleting"
class AttachmentVariant(StrEnum):
"""Имена вариантов из контракта; в lab4 существует только original"""
"""Имена вариантов из контракта; original и производные pipeline v1"""
ORIGINAL = "original"
THUMBNAIL = "thumbnail"
@@ -100,7 +93,7 @@ class AttachmentSchema(BaseModel):
content_type: AttachmentContentType
size_bytes: int
sha256: str
status: Literal["ready"] = "ready"
status: Literal["queued", "processing", "ready", "failed"] = "ready"
variants: list[AttachmentVariantSchema] = Field(default_factory=list)
error_code: str | None = None
created_at: UtcDateTime
@@ -128,6 +121,7 @@ class StoredAttachmentSchema(BaseModel):
attachment: AttachmentSchema
object_key: str
variant_keys: dict[str, str] = Field(default_factory=dict)
class UnfinishedUploadSchema(BaseModel):
@@ -159,3 +153,12 @@ class ReconcileReportSchema(BaseModel):
objects_scanned: int = 0
orphan_objects_found: int = 0
orphan_objects_deleted: int = 0
class AttachmentDownloadSchema(BaseModel):
"""Метаданные HTTP-выдачи original либо производного варианта"""
model_config = ConfigDict(frozen=True)
filename: str
content_type: str
+15
View File
@@ -0,0 +1,15 @@
from .schemas import (
ClaimedJobSchema,
JobMessageSchema,
OutboxEventSchema,
ProcessedVariantSchema,
ProcessingError,
)
__all__ = [
"ClaimedJobSchema",
"JobMessageSchema",
"OutboxEventSchema",
"ProcessedVariantSchema",
"ProcessingError",
]
+59
View File
@@ -0,0 +1,59 @@
from datetime import datetime
from typing import Literal
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field
from domain.attachments import AttachmentVariantSchema
class JobMessageSchema(BaseModel):
"""Сообщение соответствует contracts/jobs.schema.json; байтов и адресов нет"""
model_config = ConfigDict(frozen=True, extra="forbid")
schema_version: Literal[1] = 1
job_id: UUID
type: Literal["attachment.process.v1"] = "attachment.process.v1"
attachment_id: UUID
pipeline_version: Literal[1] = 1
attempt: int = Field(ge=1)
created_at: datetime
traceparent: str | None = Field(
default=None, pattern=r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$"
)
tracestate: str | None = Field(default=None, max_length=512)
class ClaimedJobSchema(BaseModel):
model_config = ConfigDict(frozen=True)
message: JobMessageSchema
lease_token: UUID
object_key: str
staging_key: str
size_bytes: int
sha256: str
content_type: str
class OutboxEventSchema(BaseModel):
model_config = ConfigDict(frozen=True)
id: int
claim_token: UUID
message: JobMessageSchema
class ProcessedVariantSchema(AttachmentVariantSchema):
"""Метаданные эффекта; object_key не попадает в публичный ответ"""
object_key: str
class ProcessingError(Exception):
"""Безопасная постоянная ошибка: повтор с теми же данными не поможет"""
def __init__(self, code: str) -> None:
self.code = code
super().__init__(code)
+1 -1
View File
@@ -78,7 +78,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
app = FastAPI(
title="mtuci-labs-messanger",
description="мессенджер-конкурент-максу",
version="1.4.0",
version="1.5.0",
lifespan=lifespan,
)
+8
View File
@@ -1,6 +1,7 @@
import sys
import time
import urllib.request
from pathlib import Path
from config import APP_PORT, JANITOR_HEARTBEAT_FILE, JANITOR_INTERVAL_SEC
@@ -30,4 +31,11 @@ def janitor() -> int:
if __name__ == "__main__":
if sys.argv[1:] and sys.argv[1] in {"worker", "dispatcher"}:
try:
age = time.time() - Path(f"/tmp/{sys.argv[1]}-heartbeat").stat().st_mtime
except OSError:
sys.exit(1)
sys.exit(0 if age < 30 else 1)
sys.exit(janitor() if sys.argv[1:] == ["janitor"] else api())
+3
View File
@@ -0,0 +1,3 @@
from .rabbit import RabbitBrokerManager
__all__ = ["RabbitBrokerManager"]
+92
View File
@@ -0,0 +1,92 @@
import asyncio
import aio_pika
from aio_pika.abc import AbstractRobustConnection
from aiormq import spec
from domain.jobs import JobMessageSchema
from infrastructure.security.secrets import read_secret
from interfaces.job_repository import JobPublisher
EXCHANGE = "attachments.v1"
QUEUE = "attachments.process.v1"
DEAD_QUEUE = "attachments.invalid.v1"
ROUTING_KEY = "attachment.process.v1"
PUBLISH_TIMEOUT_SECONDS = 5
class RabbitBrokerManager(JobPublisher):
"""Durable topology, reconnect, publisher confirms и явные consumer ack"""
def __init__(self, url_file, prefetch: int) -> None:
self._url_file = url_file
self._prefetch = prefetch
self._connection: AbstractRobustConnection | None = None
self.channel = None
self.queue = None
self._exchange = None
async def connect(self) -> None:
if self._connection is not None and self.queue is not None:
await self._connection.ready()
return
if self._connection is not None:
await self.close()
self._connection = await aio_pika.connect_robust(
read_secret(self._url_file),
timeout=PUBLISH_TIMEOUT_SECONDS,
reconnect_interval=2,
client_properties={"connection_name": "messenger-lab5"},
)
self.channel = await self._connection.channel(
publisher_confirms=True,
on_return_raises=True,
)
await self.channel.set_qos(prefetch_count=self._prefetch)
self._exchange = await self.channel.declare_exchange(
EXCHANGE,
aio_pika.ExchangeType.DIRECT,
durable=True,
)
await self.channel.declare_queue(DEAD_QUEUE, durable=True)
queue = await self.channel.declare_queue(
QUEUE,
durable=True,
arguments={
"x-dead-letter-exchange": "",
"x-dead-letter-routing-key": DEAD_QUEUE,
},
)
await queue.bind(self._exchange, routing_key=ROUTING_KEY)
self.queue = queue
async def publish(self, message: JobMessageSchema) -> None:
async with asyncio.timeout(PUBLISH_TIMEOUT_SECONDS):
await self.connect()
confirmation = await self._exchange.publish(
aio_pika.Message(
body=message.model_dump_json(exclude_none=True).encode(),
content_type="application/json",
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
message_id=str(message.job_id),
type=message.type,
headers={
"pipeline_version": message.pipeline_version,
"attempt": message.attempt,
},
),
routing_key=ROUTING_KEY,
mandatory=True,
timeout=PUBLISH_TIMEOUT_SECONDS,
)
if not isinstance(confirmation, spec.Basic.Ack):
raise ConnectionError("RabbitMQ не подтвердил публикацию")
async def close(self) -> None:
connection = self._connection
self._connection = None
self.channel = None
self.queue = None
self._exchange = None
if connection is not None:
await connection.close()
+18
View File
@@ -0,0 +1,18 @@
from config.settings import (
JOB_LEASE_SECONDS,
JOB_MAX_ATTEMPTS,
JOB_RETRY_BASE_SECONDS,
JOB_RETRY_MAX_SECONDS,
)
from infrastructure.dependencies.database import database_pool_manager
from infrastructure.repositories.job_repository import PostgresJobRepository
def create_job_repository() -> PostgresJobRepository:
return PostgresJobRepository(
database_pool_manager,
JOB_MAX_ATTEMPTS,
JOB_LEASE_SECONDS,
JOB_RETRY_BASE_SECONDS,
JOB_RETRY_MAX_SECONDS,
)
@@ -0,0 +1,99 @@
"""Изолированный процесс Pillow: полный decode, лимиты памяти/CPU, без S3/БД"""
import hashlib
import json
import resource
import sys
import warnings
from pathlib import Path
from PIL import Image, ImageOps, UnidentifiedImageError
def fit_size(size: tuple[int, int], bound: int) -> tuple[int, int]:
width, height = size
longest = max(width, height)
if longest <= bound:
return size
return max(1, width * bound // longest), max(1, height * bound // longest)
def transform(source: Path, target: Path, max_pixels: int) -> list[dict]:
Image.MAX_IMAGE_PIXELS = max_pixels
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(source) as image:
if image.format not in {"PNG", "JPEG"}:
raise UnidentifiedImageError("format")
if image.width * image.height > max_pixels:
raise Image.DecompressionBombError("pixels")
image.load() # Включая IDAT PNG: заголовка и CRC недостаточно.
oriented = ImageOps.exif_transpose(image)
try:
if oriented.mode in {"RGBA", "LA"} or "transparency" in oriented.info:
rgba = oriented.convert("RGBA")
clean = Image.new("RGB", rgba.size, "white")
clean.paste(rgba, mask=rgba.getchannel("A"))
rgba.close()
else:
clean = oriented.convert("RGB")
finally:
oriented.close()
clean.info.clear() # EXIF, XMP, ICC не наследуются производными.
result = []
try:
for name, bound, format_, mime, quality in (
("thumbnail", 256, "JPEG", "image/jpeg", 85),
("crop", 128, "JPEG", "image/jpeg", 85),
("optimized", 1280, "WEBP", "image/webp", 80),
):
derived = (
ImageOps.fit(
clean,
(bound, bound),
method=Image.Resampling.LANCZOS,
centering=(0.5, 0.5),
)
if name == "crop"
else clean.resize(fit_size(clean.size, bound), Image.Resampling.LANCZOS)
)
try:
file = target / name
derived.save(file, format_, quality=quality, exif=b"", icc_profile=None)
data = file.read_bytes()
result.append(
dict(
name=name,
content_type=mime,
width=derived.width,
height=derived.height,
size_bytes=len(data),
sha256=hashlib.sha256(data).hexdigest(),
)
)
finally:
derived.close()
finally:
clean.close()
return result
def main() -> int:
source, target, pixels, memory, seconds = sys.argv[1:]
if sys.platform == "linux":
limit = int(memory) * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
resource.setrlimit(resource.RLIMIT_CPU, (int(seconds), int(seconds) + 1))
try:
variants = transform(Path(source), Path(target), int(pixels))
except (Image.DecompressionBombError, Image.DecompressionBombWarning, MemoryError):
print("image_resource_limit")
return 2
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
print("invalid_image")
return 2
print(json.dumps(variants))
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -1,3 +1,4 @@
import json
from uuid import UUID
import asyncpg
@@ -34,7 +35,8 @@ class PostgresAttachmentRepository(AttachmentRepository):
size_bytes,
sha256,
object_key,
status
status,
staging_key
)
VALUES
(
@@ -45,7 +47,8 @@ class PostgresAttachmentRepository(AttachmentRepository):
$5,
$6,
$7,
$8
$8,
'staging/' || $7
)
RETURNING id;
"""
@@ -67,43 +70,32 @@ class PostgresAttachmentRepository(AttachmentRepository):
return attachment_id
@repository_logs
async def mark_ready(
async def mark_queued(
self, attachment_id: UUID, grace_seconds: int
) -> AttachmentSchema | None:
"""
Условие по возрасту на часах БД — тех же, по которым janitor отбирает
строки: загрузка, которую janitor уже может очищать, не подтверждается.
Одновременный claim janitor и это UPDATE сериализует блокировка строки.
"""
query = """
UPDATE attachments
SET
status = $2,
updated_at = clock_timestamp()
WHERE
id = $1
AND status = $3
AND created_at > clock_timestamp() - make_interval(secs => $4::integer)
RETURNING
id,
chat_id,
owner_id,
filename,
content_type,
size_bytes,
sha256,
created_at,
updated_at;
"""
async with self._pool.acquire() as conn:
"""Одна транзакция: принятие upload, логическая job и событие outbox"""
async with self._pool.acquire() as conn, conn.transaction():
row = await conn.fetchrow(
query,
"""
UPDATE attachments SET status = 'queued', updated_at = clock_timestamp()
WHERE id = $1 AND status = 'pending'
AND created_at > clock_timestamp() - make_interval(secs => $2::integer)
RETURNING *;
""",
attachment_id,
AttachmentStatus.READY,
AttachmentStatus.PENDING,
grace_seconds,
)
return self._row_to_attachment(row) if row is not None else None
if row is None:
return None
job_id = await conn.fetchval(
"INSERT INTO attachment_jobs (attachment_id) VALUES ($1) RETURNING id;",
attachment_id,
)
await conn.execute(
"INSERT INTO attachment_outbox (job_id, attempt) VALUES ($1, 1);",
job_id,
)
return self._row_to_attachment(row)
@repository_logs
async def claim_pending(self, attachment_id: UUID) -> UnfinishedUploadSchema | None:
@@ -115,7 +107,7 @@ class PostgresAttachmentRepository(AttachmentRepository):
WHERE
id = $1
AND status = $3
RETURNING id, object_key;
RETURNING id, COALESCE(staging_key, object_key) AS object_key;
"""
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
@@ -131,7 +123,7 @@ class PostgresAttachmentRepository(AttachmentRepository):
self, grace_seconds: int, limit: int
) -> list[UnfinishedUploadSchema]:
"""
Перевод pending → deleting атомарен: после него mark_ready этой строки
Перевод pending → deleting атомарен: после него mark_queued этой строки
невозможен. SKIP LOCKED — строку, которую сейчас подтверждает API,
janitor не ждёт и не забирает. deleting-строки возвращаются независимо
от возраста: их очистка прервалась и повторяется.
@@ -158,7 +150,7 @@ class PostgresAttachmentRepository(AttachmentRepository):
updated_at = clock_timestamp()
FROM stale
WHERE attachment.id = stale.id
RETURNING attachment.id, attachment.object_key;
RETURNING attachment.id, COALESCE(attachment.staging_key, attachment.object_key) AS object_key;
"""
async with self._pool.acquire() as conn:
rows = await conn.fetch(
@@ -177,7 +169,7 @@ class PostgresAttachmentRepository(AttachmentRepository):
query = """
SELECT
id,
object_key
COALESCE(staging_key, object_key) AS object_key
FROM attachments
WHERE
status IN ($2, $3)
@@ -228,11 +220,18 @@ class PostgresAttachmentRepository(AttachmentRepository):
attachment.sha256,
attachment.object_key,
attachment.created_at,
attachment.updated_at
attachment.updated_at,
attachment.status,
attachment.error_code,
COALESCE((SELECT json_agg(json_build_object(
'name', v.name, 'content_type', v.content_type, 'size_bytes', v.size_bytes,
'width', v.width, 'height', v.height, 'sha256', v.sha256,
'object_key', v.object_key) ORDER BY v.name)
FROM attachment_variants v WHERE v.attachment_id = attachment.id), '[]') AS variants
FROM attachments attachment
WHERE
attachment.id = $1
AND attachment.status = $3
AND attachment.status IN ('queued', 'processing', 'ready', 'failed')
AND EXISTS
(
SELECT 1
@@ -241,22 +240,28 @@ class PostgresAttachmentRepository(AttachmentRepository):
);
"""
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
query, attachment_id, member_id, AttachmentStatus.READY
)
row = await conn.fetchrow(query, attachment_id, member_id)
if row is None:
return None
return StoredAttachmentSchema(
attachment=self._row_to_attachment(row), object_key=row["object_key"]
attachment=self._row_to_attachment(row),
object_key=row["object_key"],
variant_keys={
v["name"]: v["object_key"] for v in json.loads(row["variants"])
},
)
@repository_logs
async def find_known_keys(self, object_keys: list[str]) -> set[str]:
"""Поиск по уникальному индексу object_key"""
"""Ключи staging/результатов активных jobs и опубликованных вариантов"""
query = """
SELECT object_key
FROM attachments
WHERE object_key = ANY($1::text[]);
SELECT key AS object_key FROM attachments a
CROSS JOIN LATERAL unnest(ARRAY[a.object_key, a.staging_key,
a.object_key || '/thumbnail', a.object_key || '/crop',
a.object_key || '/optimized']) AS key
WHERE key = ANY($1::text[]) AND (a.status <> 'failed' OR a.staging_key IS NOT NULL)
UNION
SELECT object_key FROM attachment_variants WHERE object_key = ANY($1::text[]);
"""
async with self._pool.acquire() as conn:
rows = await conn.fetch(query, object_keys)
@@ -272,6 +277,14 @@ class PostgresAttachmentRepository(AttachmentRepository):
content_type=row["content_type"],
size_bytes=row["size_bytes"],
sha256=row["sha256"].hex(),
status=row["status"] if "status" in row else "ready",
error_code=row["error_code"] if "error_code" in row else None,
variants=[
{k: v for k, v in item.items() if k != "object_key"}
for item in json.loads(row["variants"])
]
if "variants" in row
else [],
created_at=row["created_at"],
updated_at=row["updated_at"],
)
@@ -0,0 +1,3 @@
from .postgres import PostgresJobRepository
__all__ = ["PostgresJobRepository"]
@@ -0,0 +1,293 @@
import random
from uuid import UUID, uuid4
from domain.errors import ConflictError
from domain.jobs import (
ClaimedJobSchema,
JobMessageSchema,
OutboxEventSchema,
ProcessedVariantSchema,
)
from infrastructure.utils import Pool, repository_logs
from interfaces.job_repository import JobRepository
class PostgresJobRepository(JobRepository):
"""Job, outbox, lease и реестр failed; транзакции не держат сетевые операции"""
def __init__(
self,
pool: Pool,
max_attempts: int,
lease_seconds: int,
retry_base: float,
retry_max: float,
) -> None:
self._pool = pool
self._max_attempts = max_attempts
self._lease_seconds = lease_seconds
self._retry_base = retry_base
self._retry_max = retry_max
@repository_logs
async def claim(self, message: JobMessageSchema) -> ClaimedJobSchema | None:
token = uuid4()
async with self._pool.acquire() as conn, conn.transaction():
row = await conn.fetchrow(
"""
UPDATE attachment_jobs j SET lease_token = $5,
lease_until = clock_timestamp() + make_interval(secs => $6::integer)
FROM attachments a
WHERE j.id = $1 AND j.attachment_id = $2 AND j.pipeline_version = $3
AND j.attempt = $4 AND j.lease_token IS NULL
AND j.available_at <= clock_timestamp()
AND a.id = j.attachment_id AND a.status = 'queued'
RETURNING a.object_key, a.staging_key, a.size_bytes, a.sha256, a.content_type;
""",
message.job_id,
message.attachment_id,
message.pipeline_version,
message.attempt,
token,
self._lease_seconds,
)
if row is None:
return None
await conn.execute(
"UPDATE attachments SET status = 'processing', updated_at = clock_timestamp() WHERE id = $1;",
message.attachment_id,
)
return ClaimedJobSchema(
message=message,
lease_token=token,
object_key=row["object_key"],
staging_key=row["staging_key"],
size_bytes=row["size_bytes"],
sha256=row["sha256"].hex(),
content_type=row["content_type"],
)
@repository_logs
async def complete(
self, job: ClaimedJobSchema, variants: list[ProcessedVariantSchema]
) -> bool:
if {v.name for v in variants} != {"thumbnail", "crop", "optimized"} or len(
variants
) != 3:
raise ValueError("Pipeline v1 требует три разных варианта")
async with self._pool.acquire() as conn, conn.transaction():
owned = await conn.fetchval(
"""SELECT id FROM attachment_jobs WHERE id = $1 AND lease_token = $2
AND lease_until > clock_timestamp() FOR UPDATE;""",
job.message.job_id,
job.lease_token,
)
if owned is None:
return False
for variant in variants:
await conn.execute(
"""INSERT INTO attachment_variants
(attachment_id, pipeline_version, name, object_key, content_type,
size_bytes, width, height, sha256)
VALUES ($1, 1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING;""",
job.message.attachment_id,
variant.name,
variant.object_key,
variant.content_type,
variant.size_bytes,
variant.width,
variant.height,
variant.sha256,
)
await conn.execute(
"""UPDATE attachments SET status = 'ready', error_code = NULL,
updated_at = clock_timestamp() WHERE id = $1;
""",
job.message.attachment_id,
)
await conn.execute(
"UPDATE attachment_jobs SET lease_token = NULL, lease_until = NULL WHERE id = $1;",
job.message.job_id,
)
return True
async def _reschedule(self, conn, row, code: str, permanent: bool) -> None:
failures = row["failures"] + 1
terminal = permanent or failures >= self._max_attempts
# Equal jitter: нижняя половина задержки гарантирована, верхняя случайна.
ceiling = min(self._retry_max, self._retry_base * 2 ** min(failures - 1, 20))
delay = random.uniform(ceiling / 2, ceiling)
await conn.execute(
"""UPDATE attachments SET status = $2, error_code = $3,
updated_at = clock_timestamp() WHERE id = $1;""",
row["attachment_id"],
"failed" if terminal else "queued",
code if permanent else ("retry_exhausted" if terminal else None),
)
await conn.execute(
"""UPDATE attachment_jobs SET failures = $2, attempt = attempt + $3, last_error_code = $5,
lease_token = NULL, lease_until = NULL,
available_at = clock_timestamp() + make_interval(secs => $4::double precision)
WHERE id = $1;""",
row["id"],
failures,
0 if terminal else 1,
delay,
code,
)
if not terminal:
await conn.execute(
"""INSERT INTO attachment_outbox (job_id, attempt, available_at)
SELECT id, attempt, available_at FROM attachment_jobs WHERE id = $1;""",
row["id"],
)
@repository_logs
async def fail(self, job: ClaimedJobSchema, code: str, permanent: bool) -> None:
async with self._pool.acquire() as conn, conn.transaction():
row = await conn.fetchrow(
"""SELECT * FROM attachment_jobs WHERE id = $1 AND lease_token = $2
AND lease_until > clock_timestamp() FOR UPDATE;""",
job.message.job_id,
job.lease_token,
)
if row is not None:
await self._reschedule(conn, row, code, permanent)
@repository_logs
async def recover_expired(self) -> int:
async with self._pool.acquire() as conn, conn.transaction():
rows = await conn.fetch(
"""SELECT * FROM attachment_jobs WHERE lease_until < clock_timestamp()
ORDER BY lease_until LIMIT 100 FOR UPDATE SKIP LOCKED;"""
)
for row in rows:
await self._reschedule(conn, row, "worker_lost", False)
return len(rows)
@repository_logs
async def claim_event(self) -> OutboxEventSchema | None:
token = uuid4()
async with self._pool.acquire() as conn, conn.transaction():
row = await conn.fetchrow(
"""WITH next AS (
SELECT id FROM attachment_outbox WHERE published_at IS NULL
AND available_at <= clock_timestamp()
AND (claim_until IS NULL OR claim_until < clock_timestamp())
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED
)
UPDATE attachment_outbox o SET claim_token = $1,
claim_until = clock_timestamp() + interval '15 seconds'
FROM next, attachment_jobs j WHERE o.id = next.id AND j.id = o.job_id
RETURNING o.id, o.attempt, j.id AS job_id, j.attachment_id, j.pipeline_version, j.created_at;
""",
token,
)
if row is None:
return None
return OutboxEventSchema(
id=row["id"],
claim_token=token,
message=JobMessageSchema(
**{
k: row[k]
for k in (
"job_id",
"attachment_id",
"pipeline_version",
"attempt",
"created_at",
)
}
),
)
@repository_logs
async def mark_published(self, event: OutboxEventSchema) -> None:
async with self._pool.acquire() as conn:
await conn.execute(
"""UPDATE attachment_outbox SET published_at = clock_timestamp(),
claim_token = NULL, claim_until = NULL WHERE id = $1 AND claim_token = $2;""",
event.id,
event.claim_token,
)
@repository_logs
async def cleanup_candidates(self, retention: int) -> list[tuple[UUID, str, bool]]:
async with self._pool.acquire() as conn, conn.transaction():
# Блокируем job и attachment в общем порядке. После ожидания lock
# нельзя принимать решение по устаревшему staging_key/status из JOIN.
rows = await conn.fetch(
"""SELECT a.id, a.staging_key, a.status, a.object_key FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id WHERE a.staging_key IS NOT NULL
AND (a.status = 'ready' OR (a.status = 'failed'
AND a.updated_at < clock_timestamp() - make_interval(secs => $1::integer)))
LIMIT 100 FOR UPDATE OF j, a SKIP LOCKED;""",
retention,
)
for row in rows:
if row["status"] == "failed":
# После retirement replay запрещён: исходник больше не обещается.
await conn.execute(
"UPDATE attachments SET staging_key = NULL WHERE id = $1;",
row["id"],
)
return [(r["id"], r["staging_key"], r["status"] == "failed") for r in rows]
@repository_logs
async def clear_staging(self, attachment_id: UUID, key: str) -> None:
async with self._pool.acquire() as conn:
await conn.execute(
"UPDATE attachments SET staging_key = NULL WHERE id = $1 AND staging_key = $2 AND status = 'ready';",
attachment_id,
key,
)
@repository_logs
async def replay(self, job_id: UUID, operator: str, reason: str) -> bool:
if not 1 <= len(operator) <= 128 or not 1 <= len(reason) <= 512:
raise ValueError("Укажите operator (1–128) и reason (1–512)")
async with self._pool.acquire() as conn, conn.transaction():
row = await conn.fetchrow(
"""SELECT j.*, a.status, a.staging_key FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id WHERE j.id = $1 FOR UPDATE OF j, a;""",
job_id,
)
if row is None or row["status"] != "failed":
return False
if row["staging_key"] is None:
raise ConflictError("Retention исходника истёк; загрузите файл заново")
await conn.execute(
"""UPDATE attachment_jobs SET attempt = attempt + 1, failures = 0,
available_at = clock_timestamp() WHERE id = $1;""",
job_id,
)
await conn.execute(
"UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() WHERE id = $1;",
row["attachment_id"],
)
await conn.execute(
"INSERT INTO attachment_outbox (job_id, attempt) SELECT id, attempt FROM attachment_jobs WHERE id = $1;",
job_id,
)
await conn.execute(
"""INSERT INTO attachment_replays (job_id, attempt, operator, reason)
SELECT id, attempt, $2, $3 FROM attachment_jobs WHERE id = $1;""",
job_id,
operator,
reason,
)
return True
@repository_logs
async def list_failed(self) -> list[dict]:
async with self._pool.acquire() as conn:
rows = await conn.fetch(
"""SELECT j.id AS job_id, j.attachment_id, j.attempt, j.failures,
j.last_error_code, a.error_code, a.updated_at,
a.staging_key IS NOT NULL AS replay_available
FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id
WHERE a.status = 'failed' ORDER BY a.updated_at DESC LIMIT 100;"""
)
return [dict(row) for row in rows]
@@ -107,7 +107,7 @@ class PostgresMessageRepository(MessageRepository):
JOIN attachments attachment
ON attachment.id = item.attachment_id
AND attachment.chat_id = $2
AND attachment.status = 'ready';
AND attachment.status IN ('queued', 'processing', 'ready');
"""
save_key_query = """
@@ -150,6 +150,17 @@ class PostgresMessageRepository(MessageRepository):
row = await conn.fetchrow(insert_query, chat_id, sender_id, text)
assert row is not None
if attachment_ids:
attachments = await conn.fetch(
"""SELECT id, status FROM attachments WHERE id = ANY($1::uuid[])
AND chat_id = $2 AND status IN ('queued', 'processing', 'ready', 'failed')
ORDER BY id FOR SHARE;""",
attachment_ids,
chat_id,
)
if len(attachments) != len(attachment_ids):
raise NotFoundError("Вложение не найдено")
if any(a["status"] == "failed" for a in attachments):
raise ConflictError("Обработка вложения завершилась ошибкой")
status = await conn.execute(
attachments_query, row["id"], chat_id, attachment_ids
)
@@ -14,8 +14,10 @@ from domain import (
StoredAttachmentSchema,
UserSchema,
)
from domain.attachments.schemas import AttachmentDownloadSchema
from domain.errors import (
AppError,
ConflictError,
NotFoundError,
PayloadTooLargeError,
UnavailableError,
@@ -29,16 +31,7 @@ OBJECT_KEY_RANDOM_BYTES = 16
class AttachmentService:
"""
Вложения: оригинал в приватном S3, метаданные в PostgreSQL.
Порядок записи: строка pending → PUT в S3 → pending → ready → 201.
201 возвращается только после того, как и объект, и подтверждённые
метаданные сохранены. Сбой после записи строки компенсируется сразу:
строка забирается в deleting, объект удаляется, затем строка. Если
компенсация сама не удалась (S3/БД недоступны, процесс упал), строку
pending дочищает janitor после grace period.
"""
"""Приём: pending → устойчивый S3 staging → queued/job/outbox → 202"""
def __init__(
self,
@@ -70,7 +63,7 @@ class AttachmentService:
chunks: AsyncIterator[bytes],
) -> AttachmentSchema:
"""
Синхронная загрузка оригинала. Дешёвые проверки (доступ, Content-Type,
Устойчивый приём оригинала без resize. Дешёвые проверки (доступ, Content-Type,
Content-Length) выполняются до чтения тела; тело читается потоком
с лимитом байт, изображение проверяется до записи в S3.
@@ -116,7 +109,7 @@ class AttachmentService:
current_user: UserSchema,
attachment_id: UUID,
variant: AttachmentVariant,
) -> tuple[AttachmentSchema, StoredObject]:
) -> tuple[AttachmentDownloadSchema, StoredObject]:
"""
Объект открывается до ответа: недоступность S3 — 503 в общем формате
ошибки, а не оборванный 200.
@@ -126,18 +119,32 @@ class AttachmentService:
UnavailableError: S3 недоступен
"""
stored = await self._get_stored(current_user, attachment_id)
if stored.attachment.status != "ready":
raise ConflictError(
"Изображение ещё не готово или обработка завершилась ошибкой"
)
key = stored.object_key
content_type = stored.attachment.content_type
if variant is not AttachmentVariant.ORIGINAL:
raise NotFoundError("Вариант изображения не найден")
content = await self._storage.open(stored.object_key)
key = stored.variant_keys.get(variant)
if key is None:
raise NotFoundError("Вариант изображения не найден")
item = next(v for v in stored.attachment.variants if v.name == variant)
content_type = item.content_type
content = await self._storage.open(key)
if content is None:
LOGGER.error(
f"Нарушена согласованность: объект готового вложения "
f"{attachment_id} отсутствует в S3"
)
raise AppError()
return stored.attachment, content
return AttachmentDownloadSchema(
filename=stored.attachment.filename, content_type=content_type
), content
async def _store(self, new: NewAttachmentSchema, body: IO[bytes]) -> AttachmentSchema:
async def _store(
self, new: NewAttachmentSchema, body: IO[bytes]
) -> AttachmentSchema:
"""
Запись объекта и подтверждение метаданных с жёстким сроком
store_timeout ≪ grace period: janitor не может забрать загрузку,
@@ -148,13 +155,13 @@ class AttachmentService:
async with asyncio.timeout(self._store_timeout):
body.seek(0)
await self._storage.put(
new.object_key,
"staging/" + new.object_key,
body,
new.size_bytes,
new.content_type,
new.sha256,
)
attachment = await self._attachments.mark_ready(
attachment = await self._attachments.mark_queued(
attachment_id, self._pending_grace
)
except BaseException as error:
@@ -175,8 +182,8 @@ class AttachmentService:
async def _compensate(self, attachment_id: UUID) -> None:
"""
Best effort: pending → deleting → удалить объект → удалить строку.
Строку сначала забирают: если в неизвестном исходе UPDATE в ready
всё же прошёл, claim не сработает, и объект готового вложения цел.
Строку сначала забирают: если в неизвестном исходе COMMIT queued/job/outbox
всё же прошёл, claim не сработает, и принятый исходник цел.
Любой сбой здесь только журналируется: остаток дочистит janitor.
"""
try:
@@ -194,7 +201,7 @@ class AttachmentService:
async def _get_stored(
self, current_user: UserSchema, attachment_id: UUID
) -> StoredAttachmentSchema:
"""Чужое, неизвестное и незавершённое вложение неразличимы: 404"""
"""Чужое, неизвестное и ещё не принятое вложение неразличимы: 404"""
stored = await self._attachments.get_for_member(attachment_id, current_user.id)
if stored is None:
raise NotFoundError()
@@ -0,0 +1,3 @@
from .pipeline import ImagePipeline
__all__ = ["ImagePipeline"]
@@ -0,0 +1,100 @@
import asyncio
import hashlib
import json
import sys
import tempfile
from pathlib import Path
from domain.jobs import ClaimedJobSchema, ProcessedVariantSchema, ProcessingError
from interfaces import ObjectStorage
from interfaces.job_repository import JobRepository
TRANSFORM_SCRIPT = Path(__file__).resolve().parents[2] / "media" / "image_transform.py"
class ImagePipeline:
"""Worker side effect: неизменный original + детерминированные ключи вариантов"""
def __init__(
self,
repository: JobRepository,
storage: ObjectStorage,
max_bytes: int,
max_pixels: int,
memory_mb: int,
timeout: int,
) -> None:
self._jobs = repository
self._storage = storage
self._max_bytes = max_bytes
self._max_pixels = max_pixels
self._memory_mb = memory_mb
self._timeout = timeout
async def process(self, job: ClaimedJobSchema) -> bool:
with tempfile.TemporaryDirectory(prefix="attachment-") as directory:
target = Path(directory)
original = target / "original"
content = await self._storage.open(job.staging_key)
if content is None:
raise ProcessingError("staging_missing")
digest = hashlib.sha256()
size = 0
try:
with original.open("wb") as file:
async for chunk in content.iter_chunks():
size += len(chunk)
if size > self._max_bytes:
raise ProcessingError("image_resource_limit")
digest.update(chunk)
file.write(chunk)
finally:
await content.close()
if size != job.size_bytes or digest.hexdigest() != job.sha256:
raise ProcessingError("checksum_mismatch")
process = await asyncio.create_subprocess_exec(
sys.executable,
str(TRANSFORM_SCRIPT),
str(original),
str(target),
str(self._max_pixels),
str(self._memory_mb),
str(self._timeout),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
try:
output, _ = await process.communicate()
except BaseException:
if process.returncode is None:
process.kill()
await process.wait()
raise
if process.returncode == 2:
raise ProcessingError(output.decode().strip())
if process.returncode != 0:
raise ProcessingError("image_resource_limit")
variants = [
ProcessedVariantSchema(**v, object_key=job.object_key + "/" + v["name"])
for v in json.loads(output)
]
with original.open("rb") as file:
await self._storage.put(
job.object_key, file, size, job.content_type, digest.digest()
)
for variant in variants:
with (target / variant.name).open("rb") as file:
await self._storage.put(
variant.object_key,
file,
variant.size_bytes,
variant.content_type,
bytes.fromhex(variant.sha256),
)
from infrastructure.utils.faults import crash_once
crash_once("after-objects")
completed = await self._jobs.complete(job, variants)
if completed:
crash_once("after-result")
return completed
@@ -74,14 +74,13 @@ class StorageReconciler:
async def _clean_orphans(self, report: ReconcileReportSchema) -> None:
threshold = datetime.now(UTC) - timedelta(seconds=self._grace_seconds)
batch: list[tuple[str, datetime]] = []
async for key, modified_at in self._storage.list_objects(
ORIGINAL_OBJECT_PREFIX
):
report.objects_scanned += 1
batch.append((key, modified_at))
if len(batch) >= ORPHAN_SCAN_BATCH_SIZE:
await self._clean_orphan_batch(batch, threshold, report)
batch = []
for prefix in (ORIGINAL_OBJECT_PREFIX, "staging/"):
async for key, modified_at in self._storage.list_objects(prefix):
report.objects_scanned += 1
batch.append((key, modified_at))
if len(batch) >= ORPHAN_SCAN_BATCH_SIZE:
await self._clean_orphan_batch(batch, threshold, report)
batch = []
if batch:
await self._clean_orphan_batch(batch, threshold, report)
+12
View File
@@ -0,0 +1,12 @@
import os
from pathlib import Path
def crash_once(point: str) -> None:
"""Точка защиты: оператор явно создаёт /tmp/lab5-crash-<point> внутри контейнера"""
marker = Path("/tmp") / ("lab5-crash-" + point)
try:
marker.unlink()
except FileNotFoundError:
return
os._exit(71)
+6 -6
View File
@@ -14,9 +14,9 @@ class AttachmentRepository(ABC):
Слой абстракции метаданных вложений — источника истины о том, какие
объекты S3 принадлежат приложению.
Инвариант: у каждого объекта под ORIGINAL_OBJECT_PREFIX есть строка
(pending, ready или deleting). Строка записывается до PUT в S3,
а удаляется только после удаления объекта.
Инвариант: staging и конечные ключи назначены строкой до PUT в S3.
Публичные состояния — queued/processing/ready/failed; pending/deleting
используются только при приёме и компенсации до 202.
"""
@abstractmethod
@@ -28,11 +28,11 @@ class AttachmentRepository(ABC):
pass
@abstractmethod
async def mark_ready(
async def mark_queued(
self, attachment_id: UUID, grace_seconds: int
) -> AttachmentSchema | None:
"""
Подтверждение загрузки: pending → ready.
Подтверждение загрузки: pending → queued + job + outbox.
None, если строка уже не pending или старше grace period: janitor
мог забрать её на очистку, такая загрузка подтверждаться не должна.
@@ -74,7 +74,7 @@ class AttachmentRepository(ABC):
self, attachment_id: UUID, member_id: UUID
) -> StoredAttachmentSchema | None:
"""
Готовое вложение, только если пользователь — участник его чата.
Принятое вложение, только если пользователь — участник его чата.
"""
pass
+53
View File
@@ -0,0 +1,53 @@
from abc import ABC, abstractmethod
from uuid import UUID
from domain.jobs import (
ClaimedJobSchema,
JobMessageSchema,
OutboxEventSchema,
ProcessedVariantSchema,
)
class JobRepository(ABC):
"""Устойчивое состояние pipeline; lease_token защищает фиксацию от старого worker"""
@abstractmethod
async def claim(self, message: JobMessageSchema) -> ClaimedJobSchema | None:
pass
@abstractmethod
async def complete(
self, job: ClaimedJobSchema, variants: list[ProcessedVariantSchema]
) -> bool:
pass
@abstractmethod
async def fail(self, job: ClaimedJobSchema, code: str, permanent: bool) -> None:
pass
@abstractmethod
async def recover_expired(self) -> int:
pass
@abstractmethod
async def claim_event(self) -> OutboxEventSchema | None:
pass
@abstractmethod
async def mark_published(self, event: OutboxEventSchema) -> None:
pass
@abstractmethod
async def cleanup_candidates(self, retention: int) -> list[tuple[UUID, str, bool]]:
pass
@abstractmethod
async def clear_staging(self, attachment_id: UUID, key: str) -> None:
pass
class JobPublisher(ABC):
@abstractmethod
async def publish(self, message: JobMessageSchema) -> None:
pass
+11 -16
View File
@@ -1,19 +1,3 @@
"""
Janitor: периодическая сверка S3 и PostgreSQL (сервис janitor).
Дочищает незавершённые загрузки старше grace period и объекты S3 без строки
в БД; готовые и свежие вложения не трогает. Работает с теми же ограниченными
S3-ключами, что и API. Несколько одновременных janitor безопасны: строки
забираются через FOR UPDATE SKIP LOCKED, удаление объекта идемпотентно.
python src/janitor.py # цикл раз в JANITOR_INTERVAL_SEC
python src/janitor.py --once --dry-run # один проход, только отчёт
После каждого успешного прохода цикла обновляется JANITOR_HEARTBEAT_FILE:
по его возрасту healthcheck контейнера (src/healthcheck.py janitor) видит,
что janitor не завис и его зависимости доступны.
"""
import argparse
import asyncio
import signal
@@ -27,8 +11,10 @@ from config import (
JANITOR_INTERVAL_SEC,
LOGGER,
)
from config.settings import STAGING_RETENTION_SECONDS
from domain.errors import UnavailableError
from infrastructure import database_pool_manager, storage_manager
from infrastructure.dependencies.jobs import create_job_repository
from infrastructure.repositories import PostgresAttachmentRepository, S3ObjectStorage
from infrastructure.services import StorageReconciler
@@ -60,6 +46,8 @@ async def main(args: argparse.Namespace) -> int:
S3ObjectStorage(storage_manager),
args.grace_seconds,
)
jobs = create_job_repository()
storage = S3ObjectStorage(storage_manager)
LOGGER.info(
f"Janitor запущен: grace {args.grace_seconds} с, "
f"интервал {JANITOR_INTERVAL_SEC} с, dry-run: {args.dry_run}"
@@ -68,6 +56,13 @@ async def main(args: argparse.Namespace) -> int:
try:
while not stop.is_set():
try:
if not args.dry_run:
for attachment_id, key, retired in await jobs.cleanup_candidates(
STAGING_RETENTION_SECONDS
):
await storage.delete(key)
if not retired:
await jobs.clear_staging(attachment_id, key)
report = await reconciler.run_once(args.dry_run)
exit_code = 0
if not args.once:
+44
View File
@@ -0,0 +1,44 @@
import argparse
import asyncio
import json
from uuid import UUID
from config import DB_STARTUP_TIMEOUT_SEC
from domain.errors import AppError
from infrastructure import database_pool_manager
from infrastructure.dependencies.jobs import create_job_repository
async def main(args) -> None:
await database_pool_manager.create_pool(DB_STARTUP_TIMEOUT_SEC)
try:
repository = create_job_repository()
if args.command == "failed":
print(
json.dumps(
await repository.list_failed(), ensure_ascii=False, default=str
)
)
else:
changed = await repository.replay(args.job_id, args.operator, args.reason)
print(
"queued: replay записан в аудит"
if changed
else "no-op: job не в failed"
)
finally:
await database_pool_manager.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
commands.add_parser("failed")
replay = commands.add_parser("replay")
replay.add_argument("--job-id", type=UUID, required=True)
replay.add_argument("--operator", required=True)
replay.add_argument("--reason", required=True)
try:
asyncio.run(main(parser.parse_args()))
except (AppError, ValueError) as error:
parser.exit(2, f"{error}\n")
-7
View File
@@ -1,10 +1,3 @@
"""
Однократное применение миграций до запуска API-реплик.
Запускается сервисом migrate (compose) и завершается; реплики стартуют
после его успешного завершения и только проверяют версию схемы.
"""
import asyncio
from config import DB_STARTUP_TIMEOUT_SEC, LOGGER
-8
View File
@@ -1,11 +1,3 @@
"""
Однократная подготовка bucket до запуска API-реплик (сервис s3-bootstrap).
Работает с административными ключами, которых у API нет. Идемпотентен:
повторный запуск находит bucket и ничего не меняет. Завершается ошибкой,
если bucket доступен анонимно, — тогда API-реплики не стартуют.
"""
import asyncio
from config import (
+104
View File
@@ -0,0 +1,104 @@
import asyncio
import signal
from pathlib import Path
from pydantic import ValidationError
from config import DB_STARTUP_TIMEOUT_SEC, LOGGER, MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES
from config.settings import (
BROKER_URL_FILE,
IMAGE_PROCESS_MEMORY_MB,
JOB_TIMEOUT_SECONDS,
WORKER_CONCURRENCY,
WORKER_PREFETCH,
)
from domain.jobs import JobMessageSchema, ProcessingError
from infrastructure import database_pool_manager, storage_manager
from infrastructure.broker import RabbitBrokerManager
from infrastructure.dependencies.jobs import create_job_repository
from infrastructure.repositories import S3ObjectStorage
from infrastructure.services.image_pipeline import ImagePipeline
async def main() -> None:
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for signum in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(signum, stop.set)
await database_pool_manager.create_pool(DB_STARTUP_TIMEOUT_SEC)
await database_pool_manager.check_migrations()
await storage_manager.create_client()
jobs = create_job_repository()
pipeline = ImagePipeline(
jobs,
S3ObjectStorage(storage_manager),
MAX_UPLOAD_BYTES,
MAX_IMAGE_PIXELS,
IMAGE_PROCESS_MEMORY_MB,
JOB_TIMEOUT_SECONDS,
)
broker = RabbitBrokerManager(BROKER_URL_FILE, WORKER_PREFETCH)
slots = asyncio.Semaphore(WORKER_CONCURRENCY)
tasks = set()
async def consume(message) -> None:
task = asyncio.current_task()
tasks.add(task)
try:
try:
data = JobMessageSchema.model_validate_json(message.body)
except ValidationError:
await message.reject(requeue=False)
LOGGER.warning("Невалидное сообщение отправлено в quarantine")
return
async with slots:
job = await jobs.claim(data)
if job is not None:
try:
async with asyncio.timeout(JOB_TIMEOUT_SECONDS):
await pipeline.process(job)
except ProcessingError as error:
await jobs.fail(job, error.code, permanent=True)
except Exception as error:
LOGGER.warning(
f"Job {data.job_id}: {type(error).__name__}, retry"
)
await jobs.fail(job, "processing_failed", permanent=False)
await message.ack()
except asyncio.CancelledError:
raise
except Exception as error:
LOGGER.warning(
f"Consumer: {type(error).__name__}; сообщение не подтверждено"
)
await asyncio.sleep(1)
if not message.processed and not message.channel.is_closed:
await message.nack(requeue=True)
finally:
tasks.discard(task)
try:
await broker.connect()
tag = await broker.queue.consume(consume, no_ack=False)
LOGGER.info(
f"Worker запущен: concurrency={WORKER_CONCURRENCY}, prefetch={WORKER_PREFETCH}"
)
while not stop.is_set():
if broker.channel is not None and not broker.channel.is_closed:
Path("/tmp/worker-heartbeat").touch()
try:
await asyncio.wait_for(stop.wait(), 2)
except TimeoutError:
pass
await broker.queue.cancel(tag)
finally:
for task in list(tasks):
task.cancel()
await asyncio.gather(*list(tasks), return_exceptions=True)
await broker.close()
await storage_manager.close()
await database_pool_manager.close()
if __name__ == "__main__":
asyncio.run(main())
+6 -3
View File
@@ -86,7 +86,7 @@ def send_message(api: httpx.Client) -> Callable[..., dict]:
@pytest.fixture
def upload(api: httpx.Client) -> Callable[..., dict]:
"""Успешная загрузка вложения: 201 и Attachment"""
"""Приём 202 queued и ожидание ready для прежних сквозных проверок"""
def create(
user: dict,
@@ -98,8 +98,11 @@ def upload(api: httpx.Client) -> Callable[..., dict]:
response = upload_raw(
api, user, chat["id"], content or png_bytes(), content_type, filename
)
assert response.status_code == 201, response.text
return response.json()
assert response.status_code == 202, response.text
assert response.json()["status"] == "queued"
from helpers import wait_attachment
return wait_attachment(api, user, response.json()["id"])
return create
+25 -2
View File
@@ -1,8 +1,8 @@
"""Общие проверки для собственных black-box тестов"""
import base64
import json
import io
import json
import struct
import subprocess
import uuid
@@ -212,5 +212,28 @@ def container_json(service: str, script: str) -> dict:
def run_janitor(*args: str) -> dict:
"""Один проход janitor внутри его контейнера; отчёт сверки"""
output = compose("exec", "-T", "janitor", "python", "src/janitor.py", "--once", *args)
output = compose(
"exec", "-T", "janitor", "python", "src/janitor.py", "--once", *args
)
return last_json_line(output)
def wait_attachment(
api: httpx.Client,
user: dict,
attachment_id: str,
terminal: str = "ready",
timeout: float = 60,
) -> dict:
import time
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
response = api.get(f"/api/v1/attachments/{attachment_id}", headers=auth(user))
assert response.status_code == 200, response.text
result = response.json()
if result["status"] in {"ready", "failed"}:
assert result["status"] == terminal, result
return result
time.sleep(0.1)
raise AssertionError(f"Вложение {attachment_id} не достигло {terminal}")
+3 -2
View File
@@ -13,7 +13,7 @@ import subprocess
import httpx
import pytest
from helpers import ROOT, auth, png_bytes, upload_raw
from helpers import ROOT, auth, png_bytes, upload_raw, wait_attachment
pytestmark = pytest.mark.skipif(
os.environ.get("RUN_FAILURE_TESTS") != "1",
@@ -44,12 +44,13 @@ def test_download_survives_stop_of_uploading_replica(
content = png_bytes(800, 600, noise=True)
uploaded = upload_raw(api, alice, chat["id"], content)
assert uploaded.status_code == 201, uploaded.text
assert uploaded.status_code == 202, uploaded.text
attachment = uploaded.json()
uploader = uploaded.headers["X-Instance-Id"]
run_script("stop-one.sh", TARGET_INSTANCE_ID=uploader)
try:
attachment = wait_attachment(api, bob, attachment["id"])
served_by = set()
for _ in range(DOWNLOADS_AFTER_STOP):
response = api.get(
+41 -16
View File
@@ -63,7 +63,12 @@ def test_upload_and_download_byte_exact(
assert set(attachment) == ATTACHMENT_FIELDS
assert attachment["status"] == "ready"
assert attachment["variants"] == [] and attachment["error_code"] is None
assert {v["name"] for v in attachment["variants"]} == {
"thumbnail",
"crop",
"optimized",
}
assert attachment["error_code"] is None
assert attachment["chat_id"] == chat["id"] and attachment["owner_id"] == alice["id"]
assert attachment["content_type"] == content_type
assert attachment["size_bytes"] == len(content)
@@ -118,8 +123,12 @@ def test_outsider_and_unknown_get_indistinguishable_404(
attachment = upload(alice, chat)
for suffix in ("", "/content"):
foreign = api.get(f"/api/v1/attachments/{attachment['id']}{suffix}", headers=auth(eve))
missing = api.get(f"/api/v1/attachments/{uuid.uuid4()}{suffix}", headers=auth(eve))
foreign = api.get(
f"/api/v1/attachments/{attachment['id']}{suffix}", headers=auth(eve)
)
missing = api.get(
f"/api/v1/attachments/{uuid.uuid4()}{suffix}", headers=auth(eve)
)
assert_error(foreign, 404, "not_found")
assert_error(missing, 404, "not_found")
assert foreign.json()["error"]["message"] == missing.json()["error"]["message"]
@@ -135,7 +144,9 @@ def test_outsider_cannot_upload_into_foreign_chat(
assert_error(upload_raw(api, eve, str(uuid.uuid4()), png_bytes()), 404, "not_found")
def test_authentication_is_required(api: httpx.Client, make_user, make_chat, upload) -> None:
def test_authentication_is_required(
api: httpx.Client, make_user, make_chat, upload
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
attachment = upload(alice, chat)
@@ -153,7 +164,9 @@ def test_authentication_is_required(api: httpx.Client, make_user, make_chat, upl
assert_error(response, 401, "unauthorized")
def test_variants_and_malformed_ids(api: httpx.Client, make_user, make_chat, upload) -> None:
def test_variants_and_malformed_ids(
api: httpx.Client, make_user, make_chat, upload
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
attachment = upload(alice, chat)
@@ -161,9 +174,10 @@ def test_variants_and_malformed_ids(api: httpx.Client, make_user, make_chat, upl
original = api.get(path, params={"variant": "original"}, headers=auth(alice))
assert original.status_code == 200
# Вариант из контракта, но в lab4 его нет у ready-вложения
missing = api.get(path, params={"variant": "thumbnail"}, headers=auth(alice))
assert_error(missing, 404, "not_found")
# Производный вариант pipeline v1 доступен через авторизованный API
thumbnail = api.get(path, params={"variant": "thumbnail"}, headers=auth(alice))
assert thumbnail.status_code == 200
assert thumbnail.headers["content-type"] == "image/jpeg"
unknown = api.get(path, params={"variant": "../../etc"}, headers=auth(alice))
assert_error(unknown, 400, "invalid_request")
malformed = api.get("/api/v1/attachments/not-a-uuid", headers=auth(alice))
@@ -173,7 +187,9 @@ def test_variants_and_malformed_ids(api: httpx.Client, make_user, make_chat, upl
# --- Размер ---
def test_exactly_max_bytes_is_accepted(api: httpx.Client, make_user, make_chat, upload) -> None:
def test_exactly_max_bytes_is_accepted(
api: httpx.Client, make_user, make_chat, upload
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
content = png_of_size(MAX_UPLOAD_BYTES)
@@ -182,7 +198,9 @@ def test_exactly_max_bytes_is_accepted(api: httpx.Client, make_user, make_chat,
assert download(api, alice, attachment["id"]).content == content
def test_too_large_file_is_rejected_by_api(api: httpx.Client, make_user, make_chat) -> None:
def test_too_large_file_is_rejected_by_api(
api: httpx.Client, make_user, make_chat
) -> None:
"""10 MiB + 1 байт отклоняет реплика (X-Instance-Id), а не только LB"""
alice = make_user("alice")
chat = make_chat(alice, [alice])
@@ -191,7 +209,9 @@ def test_too_large_file_is_rejected_by_api(api: httpx.Client, make_user, make_ch
assert response.headers["X-Instance-Id"]
def test_huge_body_is_rejected_by_balancer(api: httpx.Client, make_user, make_chat) -> None:
def test_huge_body_is_rejected_by_balancer(
api: httpx.Client, make_user, make_chat
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = upload_raw(api, alice, chat["id"], b"\x00" * (12 * 1024 * 1024))
@@ -207,7 +227,7 @@ def test_empty_body_is_rejected(api: httpx.Client, make_user, make_chat) -> None
@pytest.mark.parametrize(
("width", "height", "status"),
[
(8000, 5000, 201),
(8000, 5000, 202),
(8000, 5001, 413),
(20000, 20000, 413),
],
@@ -221,9 +241,9 @@ def test_pixel_limit_applies_before_decoding(
content = bilevel_png(width, height)
assert len(content) < 1024 * 1024
response = upload_raw(api, alice, chat["id"], content)
if status == 201:
if status == 202:
assert width * height == MAX_IMAGE_PIXELS
assert response.status_code == 201, response.text
assert response.status_code == 202, response.text
else:
assert_error(response, 413, "payload_too_large")
@@ -252,7 +272,12 @@ def corrupted_payloads() -> list[tuple[str, bytes, str]]:
ids=[item[0] for item in corrupted_payloads()],
)
def test_corrupted_image_is_rejected(
api: httpx.Client, make_user, make_chat, name: str, content: bytes, content_type: str
api: httpx.Client,
make_user,
make_chat,
name: str,
content: bytes,
content_type: str,
) -> None:
alice = make_user("alice")
chat = make_chat(alice, [alice])
@@ -302,7 +327,7 @@ def test_content_type_parameters_are_ignored(
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = upload_raw(api, alice, chat["id"], png_bytes(), "Image/PNG; foo=bar")
assert response.status_code == 201, response.text
assert response.status_code == 202, response.text
assert response.json()["content_type"] == "image/png"
+111
View File
@@ -0,0 +1,111 @@
"""Сквозные свойства pipeline v1 без остановки сервисов"""
import hashlib
import io
import json
import struct
import zlib
from helpers import assert_error, auth, png_bytes, psql, upload_raw, wait_attachment
from PIL import Image
def test_variants_have_real_dimensions_checksums_and_no_metadata(
api, make_user, make_chat, upload
):
alice = make_user("pipeline")
chat = make_chat(alice, [alice])
image = Image.new("RGBA", (320, 200), (255, 0, 0, 0))
source = io.BytesIO()
image.save(source, "PNG")
ready = upload(alice, chat, source.getvalue())
expected = {
"thumbnail": ((256, 160), "JPEG"),
"crop": ((128, 128), "JPEG"),
"optimized": ((320, 200), "WEBP"),
}
for variant in ready["variants"]:
response = api.get(
f"/api/v1/attachments/{ready['id']}/content",
params={"variant": variant["name"]},
headers=auth(alice),
)
assert response.status_code == 200
assert len(response.content) == variant["size_bytes"]
assert hashlib.sha256(response.content).hexdigest() == variant["sha256"]
assert response.headers["content-type"] == variant["content_type"]
with Image.open(io.BytesIO(response.content)) as actual:
assert (actual.size, actual.format) == expected[variant["name"]]
assert actual.size == (variant["width"], variant["height"])
assert not actual.getexif() and not actual.info.get("icc_profile")
assert min(actual.convert("RGB").getpixel((0, 0))) >= 250 # alpha → белый
def test_orientation_and_no_upscale(api, make_user, make_chat, upload):
alice = make_user("orientation")
chat = make_chat(alice, [alice])
source = io.BytesIO()
image = Image.new("RGB", (12, 24), "red")
exif = Image.Exif()
exif[274] = 6
exif[315] = "must be stripped"
image.save(source, "JPEG", exif=exif)
ready = upload(alice, chat, source.getvalue(), "image/jpeg")
by_name = {v["name"]: v for v in ready["variants"]}
for name in ("thumbnail", "optimized"):
assert (by_name[name]["width"], by_name[name]["height"]) == (24, 12)
response = api.get(
f"/api/v1/attachments/{ready['id']}/content?variant={name}",
headers=auth(alice),
)
with Image.open(io.BytesIO(response.content)) as actual:
assert not actual.getexif()
assert (by_name["crop"]["width"], by_name["crop"]["height"]) == (128, 128)
original = api.get(
f"/api/v1/attachments/{ready['id']}/content", headers=auth(alice)
)
assert original.content == source.getvalue()
def broken_idat() -> bytes:
"""Корректная структура/CRC, но недекодируемый zlib: обнаруживает именно worker"""
data = png_bytes(32, 32)
result = bytearray(data[:8])
offset = 8
while offset < len(data):
size = struct.unpack(">I", data[offset : offset + 4])[0]
kind = data[offset + 4 : offset + 8]
body = data[offset + 8 : offset + 8 + size]
if kind == b"IDAT":
body = b"invalid zlib"
result += (
struct.pack(">I", len(body))
+ kind
+ body
+ struct.pack(">I", zlib.crc32(kind + body))
)
offset += size + 12
return bytes(result)
def test_permanent_failure_is_observable_and_not_linkable(
api, make_user, make_chat, send_attachments
):
alice = make_user("invalid")
chat = make_chat(alice, [alice])
response = upload_raw(api, alice, chat["id"], broken_idat())
assert response.status_code == 202 and response.json()["status"] == "queued"
attachment = wait_attachment(api, alice, response.json()["id"], terminal="failed")
assert attachment["error_code"] == "invalid_image" and not attachment["variants"]
assert_error(
api.get(f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice)),
409,
"conflict",
)
assert_error(send_attachments(alice, chat, [attachment["id"]]), 409, "conflict")
row = json.loads(
psql(
f"SELECT json_build_object('attempt', attempt, 'failures', failures) FROM attachment_jobs WHERE attachment_id = '{attachment['id']}';"
)
)
assert row == {"attempt": 1, "failures": 1}
+390
View File
@@ -0,0 +1,390 @@
"""Остановка именно своего стенда; запуск: make test-pipeline-failures"""
import hashlib
import json
import os
import time
import uuid
from subprocess import CalledProcessError
import pytest
from helpers import (
auth,
compose,
message_headers,
png_bytes,
psql,
upload_raw,
wait_attachment,
)
pytestmark = pytest.mark.skipif(
os.getenv("RUN_PIPELINE_FAILURE_TESTS") != "1",
reason="явные остановки/инъекции: make test-pipeline-failures",
)
def wait_for(check, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
value = check()
except CalledProcessError:
value = False
if value:
return value
time.sleep(0.2)
raise AssertionError("Состояние не достигнуто вовремя")
def wait_queue_empty():
wait_for(
lambda: "attachments.process.v1\t0"
in compose(
"exec", "-T", "broker", "rabbitmqctl", "list_queues", "name", "messages"
)
)
def job_row(attachment_id):
return json.loads(
psql(f"""SELECT row_to_json(r) FROM (
SELECT j.id, j.attempt, j.failures, j.lease_until, a.status, a.staging_key,
(SELECT count(*) FROM attachment_variants WHERE attachment_id = a.id) AS variants
FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id
WHERE a.id = '{attachment_id}') r;""")
)
def accept(api, alice, chat, content=None):
response = upload_raw(
api, alice, chat["id"], content if content is not None else png_bytes(320, 200)
)
assert response.status_code == 202, response.text
assert response.json()["status"] == "queued"
return response.json()
def test_commit_publish_gap_worker_down_and_broker_volume(api, make_user, make_chat):
alice = make_user("handoff")
chat = make_chat(alice, [alice])
compose("stop", "dispatcher", "worker")
try:
content = png_bytes(320, 200)
attachment = accept(api, alice, chat, content)
row = job_row(attachment["id"])
assert row["status"] == "queued" and row["staging_key"]
assert (
psql(
f"SELECT count(*) FROM attachment_outbox WHERE job_id = '{row['id']}' AND published_at IS NULL;"
)
== "1"
)
linked = api.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "", "attachment_ids": [attachment["id"]]},
headers=message_headers(alice),
)
assert linked.status_code == 201
assert (
api.get(
f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice)
).status_code
== 409
)
compose("restart", "api") # COMMIT уже был; publish ещё не было.
wait_for(lambda: api.get("/health/ready").status_code == 200)
compose("start", "dispatcher")
wait_for(
lambda: psql(
f"SELECT count(*) FROM attachment_outbox WHERE job_id = '{row['id']}' AND published_at IS NOT NULL;"
)
== "1"
)
compose("restart", "broker")
wait_for(
lambda: "attachments.process.v1\t1"
in compose(
"exec",
"-T",
"broker",
"rabbitmqctl",
"list_queues",
"name",
"messages_ready",
)
)
compose("start", "worker")
ready = wait_attachment(api, alice, attachment["id"])
assert len(ready["variants"]) == 3
assert (
api.get(
f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice)
).content
== content
)
print(
"HANDOFF: COMMIT -> API restart -> publish -> broker restart with volume -> ready",
attachment["id"],
)
finally:
compose("start", "dispatcher", "worker")
@pytest.mark.parametrize("point", ["after-objects", "after-result"])
def test_crash_before_ack_does_not_duplicate_effect(api, make_user, make_chat, point):
alice = make_user("crash")
chat = make_chat(alice, [alice])
compose("exec", "-T", "worker", "touch", f"/tmp/lab5-crash-{point}")
try:
attachment = accept(api, alice, chat)
if point == "after-objects":
wait_for(lambda: job_row(attachment["id"])["status"] == "processing")
# Реальный SIG-exit без COMMIT; ждём штатный lease (90 с), не меняя его.
ready = wait_attachment(api, alice, attachment["id"], timeout=120)
row = job_row(attachment["id"])
assert row["attempt"] == 2 and row["failures"] == 1
else:
ready = wait_attachment(api, alice, attachment["id"])
row = job_row(attachment["id"])
assert row["attempt"] == 1
assert row["variants"] == 3
before = ready
# Явный дубль уже завершённой job: публикация через тот же adapter с confirm.
compose(
"exec",
"-T",
"dispatcher",
"python",
"-c",
f'''
import asyncio, sys
sys.path.insert(0, 'src')
from infrastructure import database_pool_manager as db
from infrastructure.broker import RabbitBrokerManager
from config.settings import BROKER_URL_FILE
from domain.jobs import JobMessageSchema
async def main():
await db.create_pool(30)
async with db.acquire() as conn:
r = await conn.fetchrow("SELECT id AS job_id, attachment_id, pipeline_version, attempt, created_at FROM attachment_jobs WHERE id = $1::uuid", "{row["id"]}")
b = RabbitBrokerManager(BROKER_URL_FILE, 2)
await b.publish(JobMessageSchema(**dict(r)))
await b.close()
await db.close()
asyncio.run(main())
''',
)
wait_queue_empty() # Проверяем фактический ack, а не только статус в БД.
for variant in ready["variants"]:
response = api.get(
f"/api/v1/attachments/{attachment['id']}/content",
params={"variant": variant["name"]},
headers=auth(alice),
)
assert response.status_code == 200
assert hashlib.sha256(response.content).hexdigest() == variant["sha256"]
assert wait_attachment(api, alice, attachment["id"]) == before
assert job_row(attachment["id"])["variants"] == 3
print(
"CRASH/REDELIVERY:",
point,
"attempt",
row["attempt"],
"variants=3",
attachment["id"],
)
finally:
compose("exec", "-T", "worker", "rm", "-f", f"/tmp/lab5-crash-{point}")
compose("start", "worker")
def test_retry_exhaustion_and_safe_operator_replay(api, make_user, make_chat):
alice = make_user("retry")
chat = make_chat(alice, [alice])
compose("stop", "worker")
name = "lab5_fault_" + uuid.uuid4().hex
attachment = accept(api, alice, chat)
row = job_row(attachment["id"])
psql(f"""CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN IF NEW.id = '{attachment["id"]}' AND NEW.status = 'ready' THEN
RAISE EXCEPTION 'injected commit failure'; END IF; RETURN NEW; END; $$;
CREATE TRIGGER {name} BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION {name}();""")
try:
compose("start", "worker")
failed = wait_attachment(
api, alice, attachment["id"], terminal="failed", timeout=90
)
assert failed["error_code"] == "retry_exhausted"
row = job_row(attachment["id"])
assert row["attempt"] == row["failures"] == 5 and row["variants"] == 0
times = json.loads(
psql(
f"SELECT json_agg(available_at ORDER BY attempt) FROM attachment_outbox WHERE job_id = '{row['id']}';"
)
)
from datetime import datetime
deltas = [
(datetime.fromisoformat(b) - datetime.fromisoformat(a)).total_seconds()
for a, b in zip(times, times[1:])
]
assert len(deltas) == 4
assert all(delay >= 2**index for index, delay in enumerate(deltas))
psql(f"DROP TRIGGER {name} ON attachments; DROP FUNCTION {name}();")
result = compose(
"exec",
"-T",
"dispatcher",
"python",
"src/jobs.py",
"replay",
"--job-id",
row["id"],
"--operator",
"lab-test",
"--reason",
"fault removed",
)
assert "queued:" in result
ready = wait_attachment(api, alice, attachment["id"])
assert len(ready["variants"]) == 3
again = compose(
"exec",
"-T",
"dispatcher",
"python",
"src/jobs.py",
"replay",
"--job-id",
row["id"],
"--operator",
"lab-test",
"--reason",
"duplicate replay",
)
assert "no-op:" in again
assert (
psql(
f"SELECT count(*) FROM attachment_replays WHERE job_id = '{row['id']}';"
)
== "1"
)
print(
"RETRY: attempts=5, backoff seconds",
deltas,
"failed -> audited replay -> ready; ready replay no-op",
)
finally:
psql(
f"DROP TRIGGER IF EXISTS {name} ON attachments; DROP FUNCTION IF EXISTS {name}();"
)
compose("start", "worker")
def test_publisher_crash_after_confirm_recovers_outbox(api, make_user, make_chat):
alice = make_user("confirm")
chat = make_chat(alice, [alice])
compose("exec", "-T", "dispatcher", "touch", "/tmp/lab5-crash-after-publish")
try:
attachment = accept(api, alice, chat)
ready = wait_attachment(api, alice, attachment["id"])
row = job_row(attachment["id"])
wait_for(
lambda: psql(
f"SELECT count(*) FROM attachment_outbox WHERE job_id = '{row['id']}' AND published_at IS NOT NULL;"
)
== "1",
timeout=30,
)
wait_queue_empty()
assert len(ready["variants"]) == 3 and row["attempt"] == 1
print(
"CONFIRM GAP: confirmed publish -> crash -> outbox lease -> duplicate no-op",
attachment["id"],
)
finally:
compose("exec", "-T", "dispatcher", "rm", "-f", "/tmp/lab5-crash-after-publish")
compose("start", "dispatcher")
def test_staging_cleanup_retention_and_replay_guard(api, make_user, make_chat, upload):
from subprocess import CalledProcessError
from test_pipeline import broken_idat
alice = make_user("retention")
chat = make_chat(alice, [alice])
ready = upload(alice, chat)
failed = accept(api, alice, chat, broken_idat())
wait_attachment(api, alice, failed["id"], terminal="failed")
failed_job = job_row(failed["id"])
compose("stop", "worker")
try:
active = accept(api, alice, chat)
psql(
f"UPDATE attachments SET created_at = clock_timestamp() - interval '2 days' WHERE id = '{active['id']}';"
)
psql(
f"UPDATE attachments SET updated_at = clock_timestamp() - interval '2 days' WHERE id = '{failed['id']}';"
)
compose("exec", "-T", "janitor", "python", "src/janitor.py", "--once")
assert job_row(ready["id"])["staging_key"] is None
assert job_row(failed["id"])["staging_key"] is None
assert job_row(active["id"])["staging_key"] is not None
assert job_row(active["id"])["status"] == "queued"
with pytest.raises(CalledProcessError):
compose(
"exec",
"-T",
"dispatcher",
"python",
"src/jobs.py",
"replay",
"--job-id",
failed_job["id"],
"--operator",
"lab-test",
"--reason",
"expired source",
)
assert (
api.get(
f"/api/v1/attachments/{ready['id']}/content", headers=auth(alice)
).status_code
== 200
)
compose("start", "worker")
wait_attachment(api, alice, active["id"])
print(
"CLEANUP: ready staging removed; expired failed retired; active queued preserved; expired replay rejected"
)
finally:
compose("start", "worker")
def test_worker_process_has_effective_memory_limit():
result = compose(
"exec",
"-T",
"worker",
"python",
"-c",
"""
import subprocess, sys, tempfile
from pathlib import Path
from PIL import Image
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / 'source.png'
with Image.new('1', (8000, 5000)) as image:
image.save(source)
result = subprocess.run([sys.executable, 'src/infrastructure/media/image_transform.py',
str(source), str(root), '40000000', '128', '30'], capture_output=True, text=True)
assert result.returncode == 2, (result.returncode, result.stderr)
assert result.stdout.strip() == 'image_resource_limit', result.stdout
print('Linux RLIMIT_AS=128MiB: decoder refused 40Mpx without killing worker')
""",
)
assert "decoder refused" in result
print(result.strip())
+80
View File
@@ -0,0 +1,80 @@
"""Конкурентные границы retirement/replay на настоящем PostgreSQL"""
from subprocess import CalledProcessError
from helpers import compose, psql, upload_raw, wait_attachment
from test_pipeline import broken_idat
def checked_compose(*args):
try:
return compose(*args)
except CalledProcessError as error:
raise AssertionError(error.stderr) from None
def test_replay_waiting_for_cleanup_rechecks_retired_source(api, make_user, make_chat):
alice = make_user("replay_race")
chat = make_chat(alice, [alice])
response = upload_raw(api, alice, chat["id"], broken_idat())
assert response.status_code == 202
attachment = wait_attachment(api, alice, response.json()["id"], terminal="failed")
job_id = psql(
f"SELECT id FROM attachment_jobs WHERE attachment_id = '{attachment['id']}';"
)
# Удерживаем lock job, запускаем replay и дожидаемся его реального ожидания
# в pg_stat_activity. Затем retirement меняет только attachment и коммитит.
result = checked_compose(
"exec",
"-T",
"dispatcher",
"python",
"-c",
f"""
import asyncio, sys
from uuid import UUID
sys.path.insert(0, 'src')
from infrastructure import database_pool_manager as db
from infrastructure.dependencies.jobs import create_job_repository
from domain.errors import ConflictError
async def main():
await db.create_pool(30)
job_id = UUID('{job_id}')
task = None
try:
async with db.acquire() as conn:
async with conn.transaction():
await conn.fetchval('SELECT id FROM attachment_jobs WHERE id = $1 FOR UPDATE', job_id)
pid = await conn.fetchval('SELECT pg_backend_pid()')
task = asyncio.create_task(create_job_repository().replay(job_id, 'race-test', 'concurrent retirement'))
for _ in range(200):
blocked = await conn.fetchval('SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid)))', pid)
if blocked:
break
await asyncio.sleep(0.01)
else:
raise AssertionError('replay did not wait for the job lock')
await conn.execute('UPDATE attachments SET staging_key = NULL WHERE id = $1', UUID('{attachment["id"]}'))
try:
changed = await task
except ConflictError:
pass
else:
raise AssertionError(f'replay accepted retired source: changed={{changed}}')
print('PASS: replay rechecks attachment after waiting; retired source rejected')
finally:
if task is not None and not task.done():
task.cancel()
await asyncio.gather(task, return_exceptions=True)
# Оставляем только эту синтетическую запись в терминальном состоянии
# и при обнаружении регрессии, не допуская processing без исходника.
async with db.acquire() as conn, conn.transaction():
await conn.fetchval('SELECT id FROM attachment_jobs WHERE id = $1 FOR UPDATE', job_id)
await conn.execute('UPDATE attachment_jobs SET lease_token = NULL, lease_until = NULL WHERE id = $1', job_id)
await conn.execute("UPDATE attachments SET status = 'failed', staging_key = NULL, error_code = 'invalid_image' WHERE id = $1", UUID('{attachment["id"]}'))
await db.close()
asyncio.run(main())
""",
)
assert "retired source rejected" in result
+4 -2
View File
@@ -24,6 +24,7 @@ from helpers import (
psql,
run_janitor,
upload_raw,
wait_attachment,
)
pytestmark = pytest.mark.skipif(
@@ -49,7 +50,7 @@ def wait_upload_works(api: httpx.Client, user: dict, chat_id: str) -> httpx.Resp
deadline = time.monotonic() + READY_TIMEOUT_SEC
while True:
response = upload_raw(api, user, chat_id, png_bytes())
if response.status_code == 201 or time.monotonic() > deadline:
if response.status_code == 202 or time.monotonic() > deadline:
return response
time.sleep(1)
@@ -89,7 +90,8 @@ def test_s3_outage_is_isolated_and_leaves_no_garbage(
compose("up", "-d", "--wait", "s3")
after = wait_upload_works(api, alice, chat["id"])
assert after.status_code == 201, after.text
assert after.status_code == 202, after.text
wait_attachment(api, alice, after.json()["id"])
content = api.get(f"/api/v1/attachments/{before['id']}/content", headers=auth(bob))
assert content.status_code == 200
+36 -12
View File
@@ -47,14 +47,19 @@ class FakeChatRepository(ChatRepository):
def __init__(self) -> None:
self.foreign: set[UUID] = set()
async def create(self, title: str, created_by: UUID, member_ids: list[UUID]) -> ChatSchema:
async def create(
self, title: str, created_by: UUID, member_ids: list[UUID]
) -> ChatSchema:
raise NotImplementedError
async def get_for_member(self, chat_id: UUID, member_id: UUID) -> ChatSchema | None:
if chat_id in self.foreign:
return None
return ChatSchema(
id=chat_id, title="chat", member_ids=[member_id], created_at=datetime.now(UTC)
id=chat_id,
title="chat",
member_ids=[member_id],
created_at=datetime.now(UTC),
)
async def list_for_member(
@@ -69,7 +74,9 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
self.rows: dict[UUID, dict] = {}
self.ready_returns_none = False
def add_row(self, object_key: str, status: AttachmentStatus, age_seconds: float) -> UUID:
def add_row(
self, object_key: str, status: AttachmentStatus, age_seconds: float
) -> UUID:
attachment_id = uuid4()
self.rows[attachment_id] = {
"status": status,
@@ -81,21 +88,30 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
async def create_pending(self, attachment: NewAttachmentSchema) -> UUID:
await self._enter("create_pending")
attachment_id = self.add_row(attachment.object_key, AttachmentStatus.PENDING, 0)
attachment_id = self.add_row(
"staging/" + attachment.object_key, AttachmentStatus.PENDING, 0
)
self.rows[attachment_id]["new"] = attachment
return attachment_id
async def mark_ready(self, attachment_id: UUID, grace_seconds: int) -> AttachmentSchema | None:
await self._enter("mark_ready")
async def mark_queued(
self, attachment_id: UUID, grace_seconds: int
) -> AttachmentSchema | None:
await self._enter("mark_queued")
row = self.rows.get(attachment_id)
if self.ready_returns_none or row is None or row["status"] != AttachmentStatus.PENDING:
if (
self.ready_returns_none
or row is None
or row["status"] != AttachmentStatus.PENDING
):
return None
if row["created_at"] <= datetime.now(UTC) - timedelta(seconds=grace_seconds):
return None
row["status"] = AttachmentStatus.READY
row["status"] = AttachmentStatus.QUEUED
new: NewAttachmentSchema = row["new"]
return AttachmentSchema(
id=attachment_id,
status="queued",
chat_id=new.chat_id,
owner_id=new.owner_id,
filename=new.filename,
@@ -120,10 +136,15 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
attachment_id
for attachment_id, row in self.rows.items()
if row["status"] == AttachmentStatus.DELETING
or (row["status"] == AttachmentStatus.PENDING and row["created_at"] < threshold)
or (
row["status"] == AttachmentStatus.PENDING
and row["created_at"] < threshold
)
]
async def claim_unfinished(self, grace_seconds: int, limit: int) -> list[UnfinishedUploadSchema]:
async def claim_unfinished(
self, grace_seconds: int, limit: int
) -> list[UnfinishedUploadSchema]:
await self._enter("claim_unfinished")
# Повторный вызов в том же проходе не должен возвращать те же строки
claimed = [
@@ -135,10 +156,13 @@ class FakeAttachmentRepository(FaultInjection, AttachmentRepository):
self.rows[attachment_id]["status"] = AttachmentStatus.DELETING
self.rows[attachment_id]["claimed_now"] = True
return [
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"]) for i in claimed
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"])
for i in claimed
]
async def list_unfinished(self, grace_seconds: int, limit: int) -> list[UnfinishedUploadSchema]:
async def list_unfinished(
self, grace_seconds: int, limit: int
) -> list[UnfinishedUploadSchema]:
await self._enter("list_unfinished")
return [
UnfinishedUploadSchema(id=i, object_key=self.rows[i]["object_key"])
@@ -82,18 +82,18 @@ def run(coro):
return asyncio.run(coro)
def test_success_stores_object_and_ready_row() -> None:
def test_success_stores_staging_and_queued_row() -> None:
stand = Stand()
data = png()
attachment = run(stand.upload(data))
assert attachment.sha256 == hashlib.sha256(data).hexdigest()
assert stand.attachments.statuses() == [AttachmentStatus.READY]
assert stand.attachments.statuses() == [AttachmentStatus.QUEUED]
[(stored, _)] = stand.storage.objects.values()
assert stored == data
[key] = stand.storage.objects
assert key.startswith("originals/") and "a.png" not in key
assert key.startswith("staging/originals/") and "a.png" not in key
# Строка записана до PUT, подтверждена после
assert stand.attachments.calls[:2] == ["create_pending", "mark_ready"]
assert stand.attachments.calls[:2] == ["create_pending", "mark_queued"]
def test_s3_failure_after_write_is_compensated() -> None:
@@ -109,7 +109,7 @@ def test_s3_failure_after_write_is_compensated() -> None:
def test_db_failure_between_s3_and_commit_is_compensated() -> None:
"""Объект записан в S3, подтверждение в БД не прошло"""
stand = Stand()
stand.attachments.fail.add("mark_ready")
stand.attachments.fail.add("mark_queued")
with pytest.raises(UnavailableError):
run(stand.upload())
assert stand.storage.objects == {}
@@ -122,7 +122,7 @@ def test_db_down_leaves_pending_row_that_janitor_cleans() -> None:
строкой pending; janitor после grace period удаляет и объект, и строку.
"""
stand = Stand()
stand.attachments.fail.update({"mark_ready", "claim_pending"})
stand.attachments.fail.update({"mark_queued", "claim_pending"})
with pytest.raises(UnavailableError):
run(stand.upload())
assert len(stand.storage.objects) == 1
@@ -140,7 +140,7 @@ def test_db_down_leaves_pending_row_that_janitor_cleans() -> None:
def test_s3_down_during_compensation_leaves_deleting_row_for_janitor() -> None:
stand = Stand()
stand.attachments.fail.add("mark_ready")
stand.attachments.fail.add("mark_queued")
stand.storage.fail.add("delete")
with pytest.raises(UnavailableError):
run(stand.upload())
@@ -241,12 +241,16 @@ def test_foreign_chat_is_404_before_reading_body() -> None:
chat_id = uuid4()
stand.chats.foreign.add(chat_id)
with pytest.raises(NotFoundError):
run(stand.service.upload(USER, chat_id, "a.png", "image/png", 10, chunks_of(b"")))
run(
stand.service.upload(
USER, chat_id, "a.png", "image/png", 10, chunks_of(b"")
)
)
def test_missing_variant_is_404() -> None:
stand = Stand()
attachment = run(stand.upload())
attachment = run(stand.upload()).model_copy(update={"status": "ready"})
async def get_for_member(attachment_id, member_id):
[key] = stand.storage.objects
@@ -258,4 +262,6 @@ def test_missing_variant_is_404() -> None:
)
assert content.content_length == attachment.size_bytes
with pytest.raises(NotFoundError):
run(stand.service.open_content(USER, attachment.id, AttachmentVariant.THUMBNAIL))
run(
stand.service.open_content(USER, attachment.id, AttachmentVariant.THUMBNAIL)
)
+71
View File
@@ -0,0 +1,71 @@
"""Восстановление после обрыва AMQP при объявлении топологии"""
import asyncio
from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import uuid4
import pytest
from aiormq import spec
import infrastructure.broker.rabbit as rabbit_module
from domain.jobs import JobMessageSchema
from infrastructure.broker import RabbitBrokerManager
def connection(fail_bind: bool):
bound = False
async def bind(*args, **kwargs):
nonlocal bound
if fail_bind:
raise ConnectionError("connection lost during queue.bind")
bound = True
async def publish(*args, **kwargs):
if not bound:
raise ConnectionError("mandatory message was unroutable")
return spec.Basic.Ack()
exchange = SimpleNamespace(publish=AsyncMock(side_effect=publish))
queue = SimpleNamespace(bind=AsyncMock(side_effect=bind))
channel = SimpleNamespace(
set_qos=AsyncMock(),
declare_exchange=AsyncMock(return_value=exchange),
declare_queue=AsyncMock(return_value=queue),
)
return SimpleNamespace(
channel=AsyncMock(return_value=channel), ready=AsyncMock(), close=AsyncMock()
)
@pytest.mark.parametrize("reopen", [False, True])
def test_publish_recovers_after_connection_loss_during_binding(
tmp_path, monkeypatch, reopen
):
url_file = tmp_path / "broker_url"
url_file.write_text("amqp://synthetic")
first, second = connection(True), connection(False)
connections = ([connection(False)] if reopen else []) + [first, second]
connect = AsyncMock(side_effect=connections)
monkeypatch.setattr(rabbit_module.aio_pika, "connect_robust", connect)
message = JobMessageSchema(
job_id=uuid4(), attachment_id=uuid4(), attempt=1, created_at=datetime.now(UTC)
)
async def run():
broker = RabbitBrokerManager(url_file, 2)
try:
if reopen:
await broker.publish(message)
await broker.close()
with pytest.raises(ConnectionError, match="queue.bind"):
await broker.publish(message)
await broker.publish(message)
assert connect.await_count == (3 if reopen else 2)
first.close.assert_awaited_once()
finally:
await broker.close()
asyncio.run(run())
@@ -0,0 +1,62 @@
"""Проверка границ worker: checksum и остановка зависшего декодера"""
import asyncio
import hashlib
import os
from datetime import UTC, datetime
from uuid import uuid4
import pytest
from fakes import FakeObjectStorage
import infrastructure.services.image_pipeline.pipeline as pipeline_module
from domain.jobs import ClaimedJobSchema, JobMessageSchema, ProcessingError
from infrastructure.services.image_pipeline import ImagePipeline
def stand(data=b"source", checksum=None):
storage = FakeObjectStorage()
storage.objects["staging/source"] = (data, datetime.now(UTC))
job = ClaimedJobSchema(
message=JobMessageSchema(
job_id=uuid4(),
attachment_id=uuid4(),
attempt=1,
created_at=datetime.now(UTC),
),
lease_token=uuid4(),
object_key="originals/final",
staging_key="staging/source",
size_bytes=len(data),
sha256=checksum or hashlib.sha256(data).hexdigest(),
content_type="image/png",
)
return ImagePipeline(None, storage, 1024, 40000000, 768, 60), storage, job
def test_checksum_mismatch_cannot_publish_original():
pipeline, storage, job = stand(checksum="0" * 64)
with pytest.raises(ProcessingError, match="checksum_mismatch"):
asyncio.run(pipeline.process(job))
assert set(storage.objects) == {"staging/source"}
def test_timeout_kills_child_and_leaves_no_effect(tmp_path, monkeypatch):
pid_file = tmp_path / "pid"
decoder = tmp_path / "decoder.py"
decoder.write_text(
f"import os, time\nfrom pathlib import Path\nPath({str(pid_file)!r}).write_text(str(os.getpid()))\ntime.sleep(30)\n"
)
monkeypatch.setattr(pipeline_module, "TRANSFORM_SCRIPT", decoder)
pipeline, storage, job = stand()
async def run():
async with asyncio.timeout(0.5):
await pipeline.process(job)
with pytest.raises(TimeoutError):
asyncio.run(run())
pid = int(pid_file.read_text())
with pytest.raises(ProcessLookupError):
os.kill(pid, 0)
assert set(storage.objects) == {"staging/source"}