forked from mtusi2026/mtusi2026lab5
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a58d6beb5c | ||
|
|
4ac53fe332 | ||
|
|
641167d5d3 | ||
|
|
5f9c681bd3 | ||
|
|
0393ef16dd | ||
|
|
aa9ca145b7 | ||
|
|
429eaef5e2 | ||
|
|
8030c8821a | ||
|
|
7d39c2dab6 |
@@ -34,3 +34,7 @@ MAX_IMAGE_PIXELS=40000000
|
|||||||
CLEANUP_INTERVAL_SECONDS=300
|
CLEANUP_INTERVAL_SECONDS=300
|
||||||
# Grace period: объекты моложе N секунд не удаляются (защита in-flight uploads).
|
# Grace period: объекты моложе N секунд не удаляются (защита in-flight uploads).
|
||||||
ORPHAN_GRACE_SECONDS=3600
|
ORPHAN_GRACE_SECONDS=3600
|
||||||
|
|
||||||
|
RABBITMQ_USER=messenger
|
||||||
|
RABBITMQ_PASSWORD=messenger-rabbit-change-me
|
||||||
|
RABBITMQ_URL=amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F
|
||||||
@@ -6,15 +6,16 @@
|
|||||||
- Использованные источники, библиотеки и помощь ИИ:
|
- Использованные источники, библиотеки и помощь ИИ:
|
||||||
- Контракт: contracts/openapi.json, contracts/README.md
|
- Контракт: contracts/openapi.json, contracts/README.md
|
||||||
- Инструкции: README.md, COURSE.md, CONTRIBUTING.md
|
- Инструкции: README.md, COURSE.md, CONTRIBUTING.md
|
||||||
- Библиотеки: fastapi==0.115.0, uvicorn[standard]==0.32.0, psycopg[binary]==3.2.3, psycopg_pool==3.2.3, redis==5.2.0, boto3==1.35.74, Pillow==11.0.0, pydantic (из fastapi)
|
- Библиотеки: fastapi==0.115.0, uvicorn[standard]==0.32.0, psycopg[binary]==3.2.3, psycopg_pool==3.2.3, redis==5.2.0, boto3==1.35.74, Pillow==11.0.0, pika==1.3.2, pydantic (из fastapi)
|
||||||
- ИИ: DeepSeek — помощь в структурировании кода и отчёта. Весь код проверен, отредактирован и запущен разработчиком.
|
- ИИ: DeepSeek — помощь в структурировании кода и отчёта. Весь код проверен, отредактирован и запущен разработчиком.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
Версии runtime/образов:
|
Версии runtime/образов:
|
||||||
- Python: 3.12 (образ `python:3.12-slim`)
|
- Python: 3.12 (образ `python:3.12-slim`)
|
||||||
- FastAPI 0.115.0, uvicorn[standard] 0.32.0, psycopg[binary] 3.2.3, psycopg_pool 3.2.3, redis 5.2.0, boto3 1.35.74, Pillow 11.0.0
|
- FastAPI 0.115.0, uvicorn[standard] 0.32.0, psycopg[binary] 3.2.3, psycopg_pool 3.2.3, redis 5.2.0, boto3 1.35.74, Pillow 11.0.0, pika 1.3.2
|
||||||
- PostgreSQL 18.6-alpine, Redis 7.4.1-alpine, nginx 1.27.3-alpine
|
- PostgreSQL 18.6-alpine, Redis 7.4.1-alpine, nginx 1.27.3-alpine
|
||||||
|
- RabbitMQ 3.13.7-management-alpine
|
||||||
- MinIO: `netvark/minio:20260213` (зеркало официального образа; оригинальные `minio/minio` удалены с Docker Hub). CLI `mc`: `netvark/mc:20260920`.
|
- MinIO: `netvark/minio:20260213` (зеркало официального образа; оригинальные `minio/minio` удалены с Docker Hub). CLI `mc`: `netvark/mc:20260920`.
|
||||||
- Docker Desktop (Windows)
|
- Docker Desktop (Windows)
|
||||||
|
|
||||||
@@ -22,14 +23,14 @@
|
|||||||
|
|
||||||
1. Клонировать репозиторий и переключиться на ветку решения:
|
1. Клонировать репозиторий и переключиться на ветку решения:
|
||||||
```
|
```
|
||||||
git clone https://gitflic.ru/project/vasyukova-nat/mtusi2026lab4.git
|
git clone https://gitflic.ru/project/vasyukova-nat/mtusi2026lab5.git
|
||||||
git checkout solution/BVT2303-Vasyukova
|
git checkout solution/BVT2303-Vasyukova
|
||||||
```
|
```
|
||||||
2. Создать `.env` из шаблона:
|
2. Создать `.env` из шаблона:
|
||||||
```
|
```
|
||||||
copy .env.example .env
|
copy .env.example .env
|
||||||
```
|
```
|
||||||
3. Собрать и поднять (LB + 2 реплики API + PostgreSQL + Redis + MinIO + minio-init + s3_cleanup):
|
3. Собрать и поднять (LB + 2 реплики API + PostgreSQL + Redis + MinIO + minio-init + rabbitmq + worker + outbox + s3_cleanup):
|
||||||
```
|
```
|
||||||
docker compose --env-file .env up -d --build
|
docker compose --env-file .env up -d --build
|
||||||
```
|
```
|
||||||
@@ -55,35 +56,52 @@ $env:PYTHONUTF8="1"
|
|||||||
| `make test` | `python tests/smoke.py --base-url http://localhost:8080` |
|
| `make test` | `python tests/smoke.py --base-url http://localhost:8080` |
|
||||||
| `make test-persistence` | `python tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080` |
|
| `make test-persistence` | `python tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080` |
|
||||||
| `make test-failover` | `python tests/resilience.py --mode failover --action-script scripts/stop-one.bat --base-url http://localhost:8080` |
|
| `make test-failover` | `python tests/resilience.py --mode failover --action-script scripts/stop-one.bat --base-url http://localhost:8080` |
|
||||||
| `make test-student` | `python student-tests/lab4_test_level4.py --base-url http://localhost:8080` |
|
| `make test-student` | `python student-tests/lab5_test_level4.py --base-url http://localhost:8080` |
|
||||||
|
|
||||||
### Остановка и удаление учебных данных
|
### Остановка и удаление учебных данных
|
||||||
|
|
||||||
```
|
```
|
||||||
docker compose stop # данные PostgreSQL, Redis и MinIO сохраняются (volumes)
|
docker compose stop # данные PostgreSQL, Redis, MinIO, RabbitMQ сохраняются (volumes)
|
||||||
docker compose down # volumes сохраняются
|
docker compose down # volumes сохраняются
|
||||||
docker compose down -v # ТОЛЬКО если осознанно стираем данные
|
docker compose down -v # ТОЛЬКО если осознанно стираем данные
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Операторский replay failed-задач
|
||||||
|
|
||||||
|
Причина ошибки устранена — вернуть задачи в обработку (failed → queued + новая строка outbox, готовые не трогаются):
|
||||||
|
|
||||||
|
```
|
||||||
|
docker compose --env-file .env exec -T worker python -m app.storage.replay_failed --all-failed
|
||||||
|
# или конкретные ID:
|
||||||
|
docker compose --env-file .env exec -T worker python -m app.storage.replay_failed <attachment_id> [...]
|
||||||
|
```
|
||||||
|
|
||||||
|
Публикацию делает существующий `outbox`, обработку — `worker`; оба должны быть запущены. Проверка: `status=queued`, затем `ready`.
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
Схема процессов и хранилищ:
|
Схема процессов и хранилищ:
|
||||||
|
|
||||||
```
|
```
|
||||||
┌─ api-1 (uvicorn:8080, INSTANCE_ID=…)
|
┌─ api-1 (uvicorn:8080) ┐
|
||||||
HTTP-клиент → lb:80 ──┤ ↘
|
HTTP-клиент → lb:80 ──┤ │
|
||||||
(nginx) └─ api-2 (uvicorn:8080, INSTANCE_ID=…) PostgreSQL 18.6 (метаданные)
|
(nginx) └─ api-2 (uvicorn:8080) ├→ PostgreSQL 18.6 (метаданные, outbox)
|
||||||
Redis 7.4.1 (сессии)
|
├→ Redis 7.4.1 (сессии)
|
||||||
MinIO (S3-байты, приватный bucket)
|
├→ MinIO (S3: staging + final байты)
|
||||||
s3_cleanup (сверка S3↔БД)
|
└→ RabbitMQ (durable job queue)
|
||||||
|
|
||||||
|
outbox (publisher) → читает unpublished из PostgreSQL → публикует в RabbitMQ
|
||||||
|
worker (consumer) → забирает job из RabbitMQ → читает staging → пишет final+variants → status=ready
|
||||||
|
s3_cleanup → сверка S3↔БД, recover зависших processing
|
||||||
```
|
```
|
||||||
|
|
||||||
Все сервисы — в одной compose-сети `mtuci2026lab4_default`. Публично опубликован только порт LB `127.0.0.1:8080:80`. Реплики `api` **не имеют `ports`** — трафик к ним идёт исключительно через LB. PostgreSQL, Redis и MinIO доступны только по внутренним именам (`postgres`, `redis`, `minio`). Административная консоль MinIO (`:9001`) и S3 API (`:9000`) **не публикуются** наружу.
|
Все сервисы — в одной compose-сети `mtuci2026lab5_default`. Публично опубликован только порт LB `127.0.0.1:8080:80`. Реплики `api` **не имеют `ports`** — трафик к ним идёт исключительно через LB. PostgreSQL, Redis, MinIO и RabbitMQ доступны только по внутренним именам. Административная консоль MinIO (`:9001`), S3 API (`:9000`) и RabbitMQ management (`:15672`) **не публикуются** наружу.
|
||||||
|
|
||||||
Источники истины:
|
Источники истины:
|
||||||
- PostgreSQL — данные (пользователи, чаты, членство, сообщения) и ключи идемпотентности.
|
- PostgreSQL — данные (пользователи, чаты, членство, сообщения, метаданные вложений, варианты, outbox, ключи идемпотентности).
|
||||||
- Redis — серверные сессии (общие для всех реплик).
|
- Redis — серверные сессии (общие для всех реплик).
|
||||||
- MinIO (S3) — байты вложений (приватный bucket `messenger-attachments`).
|
- MinIO (S3) — байты вложений: staging (`staging/…`) и финальный `attachments/…` (приватный bucket).
|
||||||
|
- RabbitMQ — durable очередь job'ов. Сама по себе не источник истины: намерение сохраняется в `outbox` до публикации.
|
||||||
|
|
||||||
Схема БД (подробнее — `src/app/storage/db.py`, константа `SCHEMA_SQL`):
|
Схема БД (подробнее — `src/app/storage/db.py`, константа `SCHEMA_SQL`):
|
||||||
```
|
```
|
||||||
@@ -100,11 +118,18 @@ idempotency_keys(user_id FK→users, method TEXT, path TEXT, key TEXT,
|
|||||||
attachments(id UUID PK, chat_id FK→chats, owner_id FK→users,
|
attachments(id UUID PK, chat_id FK→chats, owner_id FK→users,
|
||||||
filename TEXT, content_type TEXT, size_bytes BIGINT, sha256 TEXT,
|
filename TEXT, content_type TEXT, size_bytes BIGINT, sha256 TEXT,
|
||||||
object_key TEXT UNIQUE, status TEXT, error_code TEXT,
|
object_key TEXT UNIQUE, status TEXT, error_code TEXT,
|
||||||
|
processing_until TIMESTAMPTZ, -- lab5: lease для worker
|
||||||
created_at TIMESTAMPTZ, updated_at TIMESTAMPTZ)
|
created_at TIMESTAMPTZ, updated_at TIMESTAMPTZ)
|
||||||
+ INDEX idx_attachments_chat(chat_id)
|
+ INDEX idx_attachments_chat(chat_id)
|
||||||
message_attachments(message_id FK→messages, attachment_id FK→attachments, position INT,
|
message_attachments(message_id FK→messages, attachment_id FK→attachments, position INT,
|
||||||
PRIMARY KEY (message_id, attachment_id))
|
PRIMARY KEY (message_id, attachment_id))
|
||||||
+ INDEX idx_msg_att_message(message_id, position)
|
attachment_variants(attachment_id FK→attachments, pipeline_version INT, variant TEXT,
|
||||||
|
object_key TEXT, content_type TEXT, size_bytes BIGINT,
|
||||||
|
width INT, height INT, sha256 TEXT, created_at TIMESTAMPTZ,
|
||||||
|
PRIMARY KEY (attachment_id, pipeline_version, variant)) -- lab5
|
||||||
|
outbox(id BIGSERIAL PK, job_id UUID UNIQUE, payload JSONB, created_at TIMESTAMPTZ,
|
||||||
|
published_at TIMESTAMPTZ) -- lab5 level 4
|
||||||
|
+ PARTIAL INDEX idx_outbox_unpublished(id) WHERE published_at IS NULL
|
||||||
```
|
```
|
||||||
|
|
||||||
Применяется идемпотентно через `init_schema()` в отдельном one-shot сервисе `migrate` (`python -m app.storage.db`). Все временные метки — `TIMESTAMPTZ`.
|
Применяется идемпотентно через `init_schema()` в отдельном one-shot сервисе `migrate` (`python -m app.storage.db`). Все временные метки — `TIMESTAMPTZ`.
|
||||||
@@ -113,41 +138,58 @@ message_attachments(message_id FK→messages, attachment_id FK→attachments, po
|
|||||||
- `create_user` — SELECT-проверка username и INSERT в одной транзакции; при гонке `UniqueViolation` → 409.
|
- `create_user` — SELECT-проверка username и INSERT в одной транзакции; при гонке `UniqueViolation` → 409.
|
||||||
- `create_chat` — INSERT `chats` + INSERT `chat_members` в одной транзакции, откат целиком.
|
- `create_chat` — INSERT `chats` + INSERT `chat_members` в одной транзакции, откат целиком.
|
||||||
- `add_message_idempotent` — INSERT ключа идемпотентности, INSERT сообщения, INSERT связей с вложениями и UPDATE ответа ключа в **одной** транзакции.
|
- `add_message_idempotent` — INSERT ключа идемпотентности, INSERT сообщения, INSERT связей с вложениями и UPDATE ответа ключа в **одной** транзакции.
|
||||||
- Создание/отзыв сессии — одна операция.
|
- `create_attachment_queued` (lab5) — INSERT `attachments` (status=`queued`) + INSERT `outbox` в **одной** транзакции. Это durable handoff: если API упадёт сразу после ответа 202, outbox гарантирует публикацию job'а.
|
||||||
|
- `finalize_ready` — UPDATE `attachments` (status=`ready`, `object_key`=final) + INSERT `attachment_variants` с `ON CONFLICT (attachment_id, pipeline_version, variant) DO NOTHING` в **одной** транзакции. Идемпотентно к повторной доставке.
|
||||||
|
|
||||||
### Дерево проекта (изменения относительно lab3 отмечены `*`)
|
### Дерево проекта (изменения относительно lab4 отмечены `*`)
|
||||||
|
|
||||||
```
|
```
|
||||||
mtuci2026lab4/
|
mtuci2026lab5/
|
||||||
├── compose.yaml * # + minio, minio-init, s3_cleanup; lab4-network
|
├── compose.yaml * # + rabbitmq, worker, outbox; tag lab5 для всех сервисов
|
||||||
├── Dockerfile
|
├── Dockerfile
|
||||||
├── docker-entrypoint.sh # генерирует INSTANCE_ID, пишет /tmp/instance_id
|
├── docker-entrypoint.sh # генерирует INSTANCE_ID, пишет /tmp/instance_id
|
||||||
├── infra/nginx.conf
|
├── infra/nginx.conf
|
||||||
├── Makefile
|
├── Makefile
|
||||||
├── requirements.txt * # + boto3, Pillow
|
├── requirements.txt * # + pika
|
||||||
├── src/app/
|
├── src/app/
|
||||||
│ ├── main.py * # + attachments router, версия 1.4.0
|
│ ├── main.py * # версия 1.5.0, title lab5
|
||||||
│ ├── api/
|
│ ├── api/
|
||||||
│ │ ├── attachments.py * # новый: upload/get/download вложений
|
│ │ ├── attachments.py * # upload → 202 queued; download variant
|
||||||
│ │ ├── messages.py * # CreateMessage c attachment_ids, проверка принадлежности чату
|
│ │ ├── messages.py # без изменений с lab4
|
||||||
│ │ └── health.py * # + проверка S3
|
│ │ └── health.py # без изменений с lab4
|
||||||
│ ├── models/
|
│ ├── models/
|
||||||
│ │ └── schemas.py * # + Attachment, Variant, Message.attachment_ids
|
│ │ └── schemas.py # без изменений с lab4
|
||||||
│ └── storage/
|
│ ├── storage/
|
||||||
│ ├── db.py * # + attachments, message_attachments
|
│ │ ├── db.py * # + attachment_variants, outbox, processing_until
|
||||||
│ ├── postgres.py * # + методы для вложений, идемпотентность с attachments
|
│ │ ├── postgres.py * # + lab5 методы (queued, variants, outbox, lease, recover)
|
||||||
│ └── s3.py * # новый: boto3-клиент, keyspace
|
│ │ ├── s3.py * # + staging_key, variant_key
|
||||||
│ └── s3_cleanup.py * # новый: фоновая сверка S3↔БД
|
│ │ ├── rabbit.py * # новый: topology, publish с confirm, retry, DLQ
|
||||||
|
│ │ └── s3_cleanup.py * # + cleanup staging, recover processing
|
||||||
|
│ ├── worker.py * # новый: consumer, обработка изображений
|
||||||
|
│ └── outbox_worker.py * # новый: outbox publisher (level 4)
|
||||||
├── scripts/
|
├── scripts/
|
||||||
│ ├── restart.sh / .bat * # + minio, s3_cleanup
|
│ ├── restart.sh / .bat * # + rabbitmq, worker, outbox
|
||||||
│ └── stop-one.sh / .bat # без изменений
|
│ └── stop-one.sh / .bat # без изменений
|
||||||
└── student-tests/
|
└── student-tests/
|
||||||
└── lab4_test_level4.py * # новый: негативные тесты, компенсация, параллельные загрузки
|
└── lab5_test_level4.py * # новый: variants, outbox, DLQ, lease, retry
|
||||||
```
|
```
|
||||||
|
|
||||||
### Что нового в lab5 относительно lab4
|
### Что нового в lab5 относительно lab4
|
||||||
|
|
||||||
TODO
|
1. **Upload возвращает 202 queued.** `POST /api/v1/chats/{chat_id}/attachments` теперь пишет байты в **staging**-prefix (`staging/<chat_id>/<attachment_id>/original`), затем одной транзакцией сохраняет `attachments` (status=`queued`) и `outbox`. Отвечает `202 Attachment` со `status=queued`. Байты передаются в HTTP полностью, но тяжёлая обработка (resize) вынесена из API.
|
||||||
|
2. **RabbitMQ как broker.** Durable quorum queue `attachment.process.v1`, retry-очереди с TTL (`attachment.retry.5s/15s/60s`) и DLQ (`attachment.process.v1.dlq`). Сообщения persistent (`delivery_mode=2`), публикуются с **publisher confirm** (`confirm_delivery()`), consumer делает manual ack после устойчивого эффекта. Доставка — at-least-once.
|
||||||
|
3. **Outbox закрывает разрыв COMMIT → publish (level 4).** Отдельный процесс `outbox` каждые 2 секунды читает неопубликованные строки `outbox`, публикует в RabbitMQ с confirm, затем помечает `published_at`. Если API упал между COMMIT и publish — outbox опубликует job после рестарта. Если RabbitMQ недоступен — строка остаётся unpublished, повтор при следующем цикле.
|
||||||
|
4. **Worker отдельный от API.** `python -m app.worker` забирает job из RabbitMQ с `prefetch_count=1`, атомарно переводит `queued` → `processing` с lease `processing_until` (60 с), скачивает staging, пишет **оригинал** (final) + **thumbnail** + **crop** + **optimized**, затем атомарно `ready` через `finalize_ready`. Staging удаляется после успешной фиксации.
|
||||||
|
5. **Идемпотентность эффекта.** Ключ `(attachment_id, pipeline_version, variant)`. `claim_processing` возвращает False для `ready` → повторная доставка — no-op. `finalize_ready` использует `ON CONFLICT DO NOTHING`. Повтор job не создаёт дублей вариантов.
|
||||||
|
6. **Retry с backoff и DLQ (level 4).** Временные ошибки (S3 недоступен, staging missing) → публикация в retry-очередь с `x-retry-count` (5 → 15 → 60 с). После 4-й попытки — `status=failed`, `error_code=retry_exhausted` и сообщение в DLQ. Постоянные ошибки (invalid image) — сразу `failed`, `error_code=invalid_image`, без retry.
|
||||||
|
7. **Lease и recover зависших (level 4).** `processing_until` — deadline для текущей попытки. `s3_cleanup` периодически (`CLEANUP_INTERVAL_SECONDS`) переводит просроченные `processing` обратно в `queued` (`recover_stuck_processing`). При старте worker также может поднять такие записи. Так зависший processing не «залипает» навсегда.
|
||||||
|
8. **Варианты обработки (level 4).**
|
||||||
|
- `original` — байты побайтно те же, что и исходный upload (SHA-256 оригинала в `attachments.sha256`).
|
||||||
|
- `thumbnail` — JPEG, вписан в 256×256 с сохранением пропорций, без увеличения; EXIF orientation применяется; alpha компонуется на белый. Для `320×200` получается `256×160`.
|
||||||
|
- `crop` — JPEG, центрированный квадрат 128×128 (маленькие исходники могут увеличиваться).
|
||||||
|
- `optimized` — WebP, вписан в 1280×1280 без увеличения, `quality=82`, EXIF удалён (Pillow не сохраняет его в WebP по умолчанию).
|
||||||
|
9. **Лимиты и защита.** Те же `MAX_UPLOAD_BYTES=10485760` и `MAX_IMAGE_PIXELS=40000000`. Pillow в threadpool; лимит пикселей проверяется до `load()`. Лимит 40 млн пикселей остаётся; worker дополнительно распаковывает под контролем того же лимита (файл уже проверен на входе, но worker defence-in-depth).
|
||||||
|
10. **Readiness.** `/health/ready` проверяет PostgreSQL, Redis, S3. RabbitMQ не критичен для синхронного пути API (upload работает без брокера благодаря outbox); его недоступность не роняет readiness, но `outbox` не публикует, пока брокер не поднимется.
|
||||||
|
|
||||||
Соответствие `.env.example` реальной конфигурации:
|
Соответствие `.env.example` реальной конфигурации:
|
||||||
- `APP_HOST`, `APP_PORT` — используются uvicorn/CMD в Dockerfile.
|
- `APP_HOST`, `APP_PORT` — используются uvicorn/CMD в Dockerfile.
|
||||||
@@ -160,20 +202,35 @@ TODO
|
|||||||
- `S3_REGION` — регион (для MinIO фиктивный `us-east-1`).
|
- `S3_REGION` — регион (для MinIO фиктивный `us-east-1`).
|
||||||
- `S3_BUCKET` — имя приватного bucket.
|
- `S3_BUCKET` — имя приватного bucket.
|
||||||
- `MINIO_ROOT_USER` / `MINIO_ROOT_PASSWORD` — root-credentials MinIO, используются только сервисами `minio` и `minio-init`.
|
- `MINIO_ROOT_USER` / `MINIO_ROOT_PASSWORD` — root-credentials MinIO, используются только сервисами `minio` и `minio-init`.
|
||||||
- `S3_APP_KEY_ID` / `S3_APP_SECRET_KEY` — прикладные S3-credentials, используются API и `s3_cleanup`.
|
- `S3_APP_KEY_ID` / `S3_APP_SECRET_KEY` — прикладные S3-credentials, используются API, worker, outbox, `s3_cleanup`.
|
||||||
- `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS` — лимиты вложений.
|
- `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS` — лимиты вложений.
|
||||||
- `CLEANUP_INTERVAL_SECONDS` — период сверки S3↔БД.
|
- `CLEANUP_INTERVAL_SECONDS` — период сверки S3↔БД и recover зависших processing.
|
||||||
- `ORPHAN_GRACE_SECONDS` — grace period для удаления orphan-объектов.
|
- `ORPHAN_GRACE_SECONDS` — grace period для удаления orphan/staging объектов.
|
||||||
|
- `RABBITMQ_USER`, `RABBITMQ_PASSWORD` — креды брокера (создаются при старте `rabbitmq`).
|
||||||
|
- `RABBITMQ_URL` — AMQP URL (`amqp://user:pass@rabbitmq:5672/%2F`); worker, outbox используют его.
|
||||||
- `CACHE_URL_FILE` — резервная переменная из скелета, не используется.
|
- `CACHE_URL_FILE` — резервная переменная из скелета, не используется.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий | Команда | Наблюдаемый результат | Уровень |
|
| Критерий | Команда | Наблюдаемый результат | Уровень |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | `python tests/smoke.py` | PASS: lab4 public API scenario | 3 |
|
| Публичный smoke | `python tests/smoke.py` | PASS: lab5 public API scenario | 3 |
|
||||||
| S3-сервер в общем стенде, приватный bucket | `docker compose ps`; `minio-init` | minio/minio-init/s3_cleanup Up; bucket `messenger-attachments` создан | 3 |
|
| Broker + worker в общем стенде, at-least-once | `docker compose ps`; `rabbitmqctl list_queues` | rabbitmq/worker/outbox Up; consumer на `attachment.process.v1` | 3 |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Upload возвращает 202 queued, работа переживает остановку worker | `lab5_test_level4.py::test_worker_stopped` | 202 queued → content 409 → старт worker → ready | 3 |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Сохранение метаданных и сессии при рестарте | `resilience.py --mode persistence` | PASS: тот же токен и SHA-256 файла | 3 |
|
||||||
|
| Отказ одной API-реплики | `resilience.py --mode failover` | observed_instances_before=2, successful_writes=7, failed_attempts=0, first_recovery=4.245 s | 3 |
|
||||||
|
| Worker сохраняет original + один thumbnail по контракту | `lab5_test_level4.py::test_variants` | thumbnail JPEG 256×160, sha256/size совпадают | 3 |
|
||||||
|
| Ограниченный retry, финальный failed с error_code | `lab5_test_level4.py::test_broken_staging_dlq` | failed `retry_exhausted` + DLQ | 3 |
|
||||||
|
| Повтор job не создаёт второго набора вариантов | `lab5_test_level4.py::test_duplicate_delivery_no_duplicates` | variants не выросли, status=ready | 3 |
|
||||||
|
| Original неизменен, download побайтно | smoke + `test_variants` | SHA-256 совпадает; при скачивании — те же байты | 3 |
|
||||||
|
| Crop 128×128 (JPEG) | `lab5_test_level4.py::test_variants` | jpeg_size(crop) == (128,128) | 4 |
|
||||||
|
| Optimized WebP (≤1280×1280) | `lab5_test_level4.py::test_variants` | Content-Type image/webp, RIFF/WEBP | 4 |
|
||||||
|
| Outbox закрывает разрыв COMMIT → publish | `lab5_test_level4.py::test_outbox_crash` | stop outbox → upload 202 + outbox unpublished → start outbox → ready | 4 |
|
||||||
|
| Retry с backoff, DLQ, безопасный replay | `lab5_test_level4.py::test_broken_staging_dlq` | 4 попытки, `retry_exhausted`, DLQ +1 | 4 |
|
||||||
|
| Ограниченная конкуренция, prefetch=1, очистка staging | `worker.py`, `s3_cleanup.py` | prefetch_count=1; staging удаляется после finalize | 4 |
|
||||||
|
| Lease: зависший processing возвращается в queued | `lab5_test_level4.py::test_stuck_processing_recovered` | processing (lease истёк) → queued → ready | 4 |
|
||||||
|
| Лимиты времени/памяти worker | `Pillow`, `MAX_IMAGE_PIXELS`, threadpool | Pillow в threadpool, лимит до `load()` | 4 |
|
||||||
|
| Гарантия, что в очереди ID, а не байты/креды | `rabbit.py`, `outbox_worker.py` | payload = {job_id, attachment_id, pipeline_version, created_at}; staging/финальные байты — в S3 | 4 |
|
||||||
|
|
||||||
### Выводы тестов
|
### Выводы тестов
|
||||||
|
|
||||||
@@ -185,46 +242,59 @@ PASS: offline skeleton structure, local refs and Python syntax; application NOT
|
|||||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||||
|
|
||||||
(venv) PS ...> python tests/smoke.py --base-url http://localhost:8080
|
(venv) PS ...> python tests/smoke.py --base-url http://localhost:8080
|
||||||
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
|
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
|
||||||
(venv) PS ...> python tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080
|
(venv) PS ...> python tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080
|
||||||
PASS: persistence preserved confirmed data and existing session.
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
|
||||||
(venv) PS ...> python tests/resilience.py --mode failover --action-script scripts/stop-one.bat --base-url http://localhost:8080
|
(venv) PS ...> python tests/resilience.py --mode failover --action-script scripts/stop-one.bat --base-url http://localhost:8080
|
||||||
{"observed_instances_before": 2, "successful_writes": 8, "failed_attempts": 0, "first_recovery_seconds": 4.146}
|
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||||
PASS: failover preserved confirmed data and existing session.
|
{"observed_instances_before": 2, "successful_writes": 7, "failed_attempts": 0, "first_recovery_seconds": 4.245}
|
||||||
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
|
||||||
(venv) PS ...> python student-tests/lab4_test_level4.py --base-url http://localhost:8080
|
(venv) PS ...> python student-tests/lab5_test_level4.py --base-url http://localhost:8080
|
||||||
=== oversize ===
|
=== variants (thumbnail/crop/optimized) ===
|
||||||
PASS: oversize -> 413
|
PASS: original, thumbnail 256×160, crop 128×128, optimized WebP
|
||||||
=== corrupted image ===
|
=== outbox crash between COMMIT and publish ===
|
||||||
PASS: corrupted -> 415
|
PASS: outbox recovers job after stop/start without manual intervention
|
||||||
=== spoofed MIME ===
|
=== duplicate delivery does not create duplicates ===
|
||||||
PASS: spoofed MIME -> 415
|
PASS: re-delivery of the same job is a no-op
|
||||||
=== bad filename ===
|
=== worker stopped: 202 → content 409 → ready ===
|
||||||
PASS: bad filename -> 400
|
PASS: accepted work survives worker restart
|
||||||
=== foreign attachment / cross-chat ===
|
=== broken staging → retry_exhausted → failed + DLQ ===
|
||||||
PASS: foreign -> 404, cross-chat -> 404
|
PASS: bounded retry, failed with safe error_code, message in DLQ
|
||||||
=== attachment belongs to chat ===
|
=== stuck processing (lease) → queued → ready ===
|
||||||
PASS: attachment from another chat -> 404
|
PASS: expired lease is recovered, same attachment becomes ready
|
||||||
=== compensation on DB failure ===
|
PASS: all lab5 level-4 checks passed
|
||||||
upload при мёртвой БД вернул 503
|
|
||||||
компенсация: bucket не вырос (before=10 after=10)
|
|
||||||
PASS: компенсация orphan-объектов при отказе БД
|
|
||||||
=== parallel uploads memory ===
|
|
||||||
10 параллельных загрузок, пик RSS=88.94 MiB
|
|
||||||
PASS: 10 параллельных загрузок в пределах лимита памяти
|
|
||||||
PASS: all lab4 level-4 checks passed
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Hardware: Windows 11, Docker Desktop (WSL2). Лимиты контейнеров в `compose.yaml` (`api`: 1 CPU / 512M; `worker`: 1 CPU / 512M; `outbox`: 0.3 CPU / 128M; `rabbitmq`: 0.5 CPU / 512M; `s3_cleanup`: 0.3 CPU / 256M). Все данные синтетические (см. `tests/smoke.py`, `student-tests/lab5_test_level4.py`).
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| `docker compose stop outbox` между COMMIT и publish | Строка outbox остаётся `published_at IS NULL`, attachment `queued`; после `start outbox` — публикация, ready | upload → 202, outbox unpublished → start → ready | ~2 с после старта outbox (polling интервал); потери нет |
|
||||||
|
| `docker compose stop worker` после upload | 202 queued; `content` → 409; старт worker → ready | PASS: 202 → 409 → ready, thumbnail доступен | ~5–10 с после старта worker |
|
||||||
|
| `docker compose stop postgres` во время upload | S3 staging PUT прошёл, INSERT падает, компенсация удаляет staging, ответ 503 | 503, staging-объект удалён (компенсация), bucket не вырос | 0; после `start postgres` — ready за ≤90 с, по факту ~10 с |
|
||||||
|
| `docker stop` одной API-реплики (failover) | Вторая реплика обслуживает; подтверждённое не теряется; идемпотентность без дублей | 2 реплики до, 7 успешных записей, 0 ошибок, recovery=4.245 s | ≤10 с; потери нет |
|
||||||
|
| `scripts/restart.bat` (все сервисы, включая RabbitMQ) | Данные PostgreSQL/Redis/RabbitMQ и оригиналы в S3 сохраняются, сессия продолжает работать | PASS: тот же токен и SHA-256 файла после перезапуска | Готовность ≤90 с; потери нет |
|
||||||
|
| Broken staging (удалён объект `staging/…`) | 4 попытки (5+15+60 с), `failed` `retry_exhausted`, сообщение в DLQ | PASS: failed, error_code=retry_exhausted, DLQ +1 | ≤180 с; потеря — только испорченный файл |
|
||||||
|
| Зависший processing (lease истёк) | recover переводит в `queued`; worker доводит до `ready` | PASS: processing → queued → ready | ~несколько секунд после recover |
|
||||||
|
| Повторный publish того же job (эмуляция redelivery) | `claim_processing` возвращает False для `ready`; variants не растут | PASS: 3 → 3 варианта, status=ready | — |
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
- **Один Docker-host.** Отказ узла не проверялся; LB, PostgreSQL, Redis, MinIO, RabbitMQ — единичные экземпляры (SPOF). HA БД/LB/S3/broker не заявляется.
|
||||||
|
- **RabbitMQ в одном узле.** Quorum queue даёт durability при рестарте, но не переживёт потерю диска. Для уровня 4 этого достаточно; для продакшена — кластер RabbitMQ + репликация S3 + HA PostgreSQL.
|
||||||
|
- **Outbox polling.** `outbox` работает с интервалом 2 с; задержка публикации ≤2 с. Для снижения latency можно LISTEN/NOTIFY вместо polling, но это не требуется для учебного стенда.
|
||||||
|
- **At-least-once, не exactly-once.** Повторная доставка возможна (например, redelivery после ack-timeout); идемпотентность обеспечена ключом `(attachment_id, pipeline_version, variant)` и `claim_processing`, но не «exactly-once».
|
||||||
|
- **DLQ без автоматического replay.** Failed-задачи остаются в DLQ; replay — ручной (операторский), как требует методичка для уровня 4. Автоматический replay не реализован.
|
||||||
|
- **Несколько pipeline_version.** В коде `PIPELINE_VERSION=1`. Версионирование pipeline (трек 5) не реализовано; `ON CONFLICT (attachment_id, pipeline_version, variant)` уже готово к появлению v2, но второй pipeline не заявлен.
|
||||||
|
- **Память загрузки.** Тело upload читается в память API (`chunks: list[bytes]`). При `MAX_UPLOAD_BYTES=10 MiB` и лимитах `api` это приемлемо; для больших лимитов нужен `upload_fileobj` в S3 (не требуется).
|
||||||
|
- **Пиксели в worker.** Worker повторно открывает staging через Pillow. Основной лимит пикселей уже проверен на входе в API; worker не увеличивает допустимый размер, но и не делает дополнительных ограничений сверх `MAX_IMAGE_PIXELS` — это ответственность API на входе.
|
||||||
|
- **`s3_cleanup` — best-effort.** Если процесс упал во время цикла, при следующем запуске сверка продолжается. Staging моложе `ORPHAN_GRACE_SECONDS` не удаляется (защита in-flight); зависшие processing восстанавливаются на каждом цикле.
|
||||||
|
- **Компенсация «S3 → БД».** Основной путь — удалить staging при ошибке INSERT (компенсация). Обратный случай (метаданные есть, S3 staging потерян) ловится worker'ом как `staging_unavailable` → retry → при исчерпании `retry_exhausted` + DLQ. Содержимое файла восстановить неоткуда — это учебное ограничение.
|
||||||
|
- **Часы.** Порядок `(created_at, id)` требует монотонности `created_at` в пределах сервера; для учебного стенда с одной БД это выполняется.
|
||||||
|
- **Нагрузка.** Полноценных замеров RPS/p50/p95/p99 при фиксированных ресурсах не проводилось — для целевой оценки 4 это не требуется. Трек 5 (перегрузка очереди или versioned idempotency) не заявлен.
|
||||||
+83
-7
@@ -142,7 +142,7 @@ services:
|
|||||||
|
|
||||||
migrate:
|
migrate:
|
||||||
build: .
|
build: .
|
||||||
image: mtuci-messenger:lab4
|
image: mtuci-messenger:lab5
|
||||||
command: ["python", "-m", "app.storage.db"]
|
command: ["python", "-m", "app.storage.db"]
|
||||||
# Явный whitelist переменных: без MINIO_ROOT_USER/PASSWORD.
|
# Явный whitelist переменных: без MINIO_ROOT_USER/PASSWORD.
|
||||||
environment:
|
environment:
|
||||||
@@ -165,9 +165,83 @@ services:
|
|||||||
cpus: "0.1"
|
cpus: "0.1"
|
||||||
memory: 64M
|
memory: 64M
|
||||||
|
|
||||||
|
rabbitmq:
|
||||||
|
image: rabbitmq:3.13.7-management-alpine
|
||||||
|
container_name: mtuci-rabbitmq
|
||||||
|
environment:
|
||||||
|
RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-messenger}
|
||||||
|
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:-messenger-rabbit-change-me}
|
||||||
|
volumes:
|
||||||
|
- rabbitmq-data:/var/lib/rabbitmq
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 20
|
||||||
|
start_period: 20s
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 512M
|
||||||
|
reservations:
|
||||||
|
cpus: "0.1"
|
||||||
|
memory: 128M
|
||||||
|
|
||||||
|
worker:
|
||||||
|
build: .
|
||||||
|
image: mtuci-messenger:lab5
|
||||||
|
command: ["python", "-m", "app.worker"]
|
||||||
|
environment:
|
||||||
|
APP_ENV: ${APP_ENV:-lab}
|
||||||
|
DATABASE_URL: ${DATABASE_URL}
|
||||||
|
S3_ENDPOINT: ${S3_ENDPOINT:-http://minio:9000}
|
||||||
|
S3_REGION: ${S3_REGION:-us-east-1}
|
||||||
|
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||||
|
S3_APP_KEY_ID: ${S3_APP_KEY_ID}
|
||||||
|
S3_APP_SECRET_KEY: ${S3_APP_SECRET_KEY}
|
||||||
|
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
||||||
|
depends_on:
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
minio-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
rabbitmq:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "1.0"
|
||||||
|
memory: 512M
|
||||||
|
reservations:
|
||||||
|
cpus: "0.25"
|
||||||
|
memory: 128M
|
||||||
|
|
||||||
|
outbox:
|
||||||
|
build: .
|
||||||
|
image: mtuci-messenger:lab5
|
||||||
|
command: ["python", "-m", "app.outbox_worker"]
|
||||||
|
environment:
|
||||||
|
APP_ENV: ${APP_ENV:-lab}
|
||||||
|
DATABASE_URL: ${DATABASE_URL}
|
||||||
|
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
||||||
|
depends_on:
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
rabbitmq:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.3"
|
||||||
|
memory: 128M
|
||||||
|
|
||||||
api:
|
api:
|
||||||
build: .
|
build: .
|
||||||
image: mtuci-messenger:lab4
|
image: mtuci-messenger:lab5
|
||||||
# Явный whitelist переменных: приложение не получает административные
|
# Явный whitelist переменных: приложение не получает административные
|
||||||
# credentials MinIO (MINIO_ROOT_USER/PASSWORD). Для S3 — только
|
# credentials MinIO (MINIO_ROOT_USER/PASSWORD). Для S3 — только
|
||||||
# прикладные S3_APP_KEY_ID/S3_APP_SECRET_KEY с ограниченной политикой.
|
# прикладные S3_APP_KEY_ID/S3_APP_SECRET_KEY с ограниченной политикой.
|
||||||
@@ -219,7 +293,7 @@ services:
|
|||||||
# Запускается как долгоживущий сервис, спит CLEANUP_INTERVAL_SECONDS.
|
# Запускается как долгоживущий сервис, спит CLEANUP_INTERVAL_SECONDS.
|
||||||
s3_cleanup:
|
s3_cleanup:
|
||||||
build: .
|
build: .
|
||||||
image: mtuci-messenger:lab4
|
image: mtuci-messenger:lab5
|
||||||
command: ["python", "-m", "app.storage.s3_cleanup"]
|
command: ["python", "-m", "app.storage.s3_cleanup"]
|
||||||
# Явный whitelist переменных: без административных кредов MinIO.
|
# Явный whitelist переменных: без административных кредов MinIO.
|
||||||
environment:
|
environment:
|
||||||
@@ -269,12 +343,14 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres-data:
|
postgres-data:
|
||||||
name: mtuci2026lab4_postgres-data
|
name: mtuci2026lab5_postgres-data
|
||||||
redis-data:
|
redis-data:
|
||||||
name: mtuci2026lab4_redis-data
|
name: mtuci2026lab5_redis-data
|
||||||
minio-data:
|
minio-data:
|
||||||
name: mtuci2026lab4_minio-data
|
name: mtuci2026lab5_minio-data
|
||||||
|
rabbitmq-data:
|
||||||
|
name: mtuci2026lab5_rabbitmq-data
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
default:
|
default:
|
||||||
name: mtuci2026lab4_default
|
name: mtuci2026lab5_default
|
||||||
+2
-1
@@ -5,4 +5,5 @@ psycopg_pool==3.2.3
|
|||||||
redis==5.2.0
|
redis==5.2.0
|
||||||
openapi-spec-validator==0.7.2
|
openapi-spec-validator==0.7.2
|
||||||
boto3==1.35.74
|
boto3==1.35.74
|
||||||
Pillow==11.0.0
|
Pillow==11.0.0
|
||||||
|
pika==1.3.2
|
||||||
+48
-32
@@ -1,4 +1,4 @@
|
|||||||
"""Вложения (lab4): синхронный binary upload PNG/JPEG, авторизованный download."""
|
"""Вложения (lab5): upload → 202 queued, async worker, download вариантов."""
|
||||||
import hashlib
|
import hashlib
|
||||||
import io
|
import io
|
||||||
import os
|
import os
|
||||||
@@ -11,6 +11,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
|||||||
from fastapi.responses import Response
|
from fastapi.responses import Response
|
||||||
from PIL import Image, UnidentifiedImageError
|
from PIL import Image, UnidentifiedImageError
|
||||||
from starlette.concurrency import run_in_threadpool
|
from starlette.concurrency import run_in_threadpool
|
||||||
|
from botocore.exceptions import ClientError
|
||||||
|
|
||||||
from ..models.schemas import Attachment, User
|
from ..models.schemas import Attachment, User
|
||||||
from ..storage import s3
|
from ..storage import s3
|
||||||
@@ -22,6 +23,7 @@ router = APIRouter(prefix="/api/v1", tags=["attachments"])
|
|||||||
|
|
||||||
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
||||||
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||||
|
PIPELINE_VERSION = 1
|
||||||
|
|
||||||
|
|
||||||
def _require_member(chat_id: UUID, user_id: UUID):
|
def _require_member(chat_id: UUID, user_id: UUID):
|
||||||
@@ -52,11 +54,7 @@ def _detect_content_type(data: bytes) -> Optional[str]:
|
|||||||
|
|
||||||
|
|
||||||
def _validate_image(data: bytes) -> str:
|
def _validate_image(data: bytes) -> str:
|
||||||
"""MIME по содержимому + лимит пикселей + полная проверка декодирования.
|
"""MIME по содержимому + лимит пикселей + полная проверка декодирования."""
|
||||||
|
|
||||||
Полное декодирование (load) выполняется через Pillow, чтобы отвергнуть
|
|
||||||
повреждённые/обрезанные файлы, которые open() принимает по заголовку.
|
|
||||||
"""
|
|
||||||
ctype = _detect_content_type(data)
|
ctype = _detect_content_type(data)
|
||||||
if ctype is None:
|
if ctype is None:
|
||||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||||
@@ -67,14 +65,10 @@ def _validate_image(data: bytes) -> str:
|
|||||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||||
if width * height > MAX_IMAGE_PIXELS:
|
if width * height > MAX_IMAGE_PIXELS:
|
||||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||||
# Полное декодирование всех данных: битый IDAT / обрезанный файл
|
|
||||||
# поднимут OSError/ValueError и будут отвергнуты как 415.
|
|
||||||
img.load()
|
img.load()
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
raise
|
raise
|
||||||
except Image.DecompressionBombError:
|
except Image.DecompressionBombError:
|
||||||
# Pillow защищается от «бомб» по собственному порогу: для нас
|
|
||||||
# это превышение лимита пикселей → 413.
|
|
||||||
raise HTTPException(status_code=413, detail="payload_too_large")
|
raise HTTPException(status_code=413, detail="payload_too_large")
|
||||||
except Exception:
|
except Exception:
|
||||||
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
raise HTTPException(status_code=415, detail="unsupported_media_type")
|
||||||
@@ -83,9 +77,9 @@ def _validate_image(data: bytes) -> str:
|
|||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
path="/chats/{chat_id}/attachments",
|
path="/chats/{chat_id}/attachments",
|
||||||
summary="Принять один PNG/JPEG, до 10 MiB",
|
summary="Принять один PNG/JPEG, до 10 MiB (lab5: 202 queued)",
|
||||||
response_model=Attachment,
|
response_model=Attachment,
|
||||||
status_code=201,
|
status_code=202,
|
||||||
)
|
)
|
||||||
async def upload_attachment(
|
async def upload_attachment(
|
||||||
chat_id: UUID,
|
chat_id: UUID,
|
||||||
@@ -96,7 +90,6 @@ async def upload_attachment(
|
|||||||
_require_member(chat_id, user.id)
|
_require_member(chat_id, user.id)
|
||||||
safe_name = _validate_filename(filename)
|
safe_name = _validate_filename(filename)
|
||||||
|
|
||||||
# Content-Length — быстрая отсечка; не доверяем полностью.
|
|
||||||
cl = request.headers.get("content-length")
|
cl = request.headers.get("content-length")
|
||||||
if cl is not None:
|
if cl is not None:
|
||||||
try:
|
try:
|
||||||
@@ -105,7 +98,6 @@ async def upload_attachment(
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
raise HTTPException(status_code=400, detail="invalid_request")
|
raise HTTPException(status_code=400, detail="invalid_request")
|
||||||
|
|
||||||
# Потоковое чтение с жёстким лимитом.
|
|
||||||
chunks: list[bytes] = []
|
chunks: list[bytes] = []
|
||||||
total = 0
|
total = 0
|
||||||
async for chunk in request.stream():
|
async for chunk in request.stream():
|
||||||
@@ -119,16 +111,15 @@ async def upload_attachment(
|
|||||||
if not body:
|
if not body:
|
||||||
raise HTTPException(status_code=400, detail="invalid_request")
|
raise HTTPException(status_code=400, detail="invalid_request")
|
||||||
|
|
||||||
# Pillow — в threadpool, чтобы не блокировать event loop.
|
|
||||||
content_type = await run_in_threadpool(_validate_image, body)
|
content_type = await run_in_threadpool(_validate_image, body)
|
||||||
sha256 = hashlib.sha256(body).hexdigest()
|
sha256 = hashlib.sha256(body).hexdigest()
|
||||||
|
|
||||||
attachment_id = uuid4()
|
attachment_id = uuid4()
|
||||||
object_key = s3.original_key(chat_id, attachment_id)
|
staging_key = s3.staging_key(chat_id, attachment_id)
|
||||||
|
|
||||||
# 1) Сначала сохраняем в S3. Если следующий шаг упадёт — компенсируем.
|
# 1) Durable staging в S3 (приватный prefix).
|
||||||
try:
|
try:
|
||||||
await run_in_threadpool(s3.put_bytes, object_key, body, content_type)
|
await run_in_threadpool(s3.put_bytes, staging_key, body, content_type)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||||
|
|
||||||
@@ -141,19 +132,31 @@ async def upload_attachment(
|
|||||||
content_type=content_type,
|
content_type=content_type,
|
||||||
size_bytes=len(body),
|
size_bytes=len(body),
|
||||||
sha256=sha256,
|
sha256=sha256,
|
||||||
status="ready",
|
status="queued",
|
||||||
variants=[],
|
variants=[],
|
||||||
error_code=None,
|
error_code=None,
|
||||||
created_at=now,
|
created_at=now,
|
||||||
updated_at=now,
|
updated_at=now,
|
||||||
)
|
)
|
||||||
|
|
||||||
# 2) INSERT в БД. При ЛЮБОМ исключении удаляем S3-объект (компенсация).
|
job_id = uuid4()
|
||||||
|
outbox_payload = {
|
||||||
|
"job_id": str(job_id),
|
||||||
|
"type": "attachment.process.v1",
|
||||||
|
"attachment_id": str(attachment_id),
|
||||||
|
"pipeline_version": PIPELINE_VERSION,
|
||||||
|
"created_at": now.isoformat().replace("+00:00", "Z"),
|
||||||
|
}
|
||||||
|
|
||||||
|
# 2) INSERT attachment + outbox в ОДНОЙ транзакции.
|
||||||
|
# При сбое — компенсация: удаляем staging.
|
||||||
try:
|
try:
|
||||||
await run_in_threadpool(storage.create_attachment, att, object_key)
|
await run_in_threadpool(
|
||||||
|
storage.create_attachment_queued, att, staging_key, outbox_payload
|
||||||
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
try:
|
try:
|
||||||
await run_in_threadpool(s3.delete_object, object_key)
|
await run_in_threadpool(s3.delete_object, staging_key)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
raise HTTPException(status_code=503, detail="unavailable")
|
raise HTTPException(status_code=503, detail="unavailable")
|
||||||
@@ -180,15 +183,16 @@ def get_attachment(
|
|||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
path="/attachments/{attachment_id}/content",
|
path="/attachments/{attachment_id}/content",
|
||||||
summary="Скачать байты через авторизованный API",
|
summary="Скачать байты (original или variant) через авторизованный API",
|
||||||
)
|
)
|
||||||
def download_attachment(
|
def download_attachment(
|
||||||
attachment_id: UUID,
|
attachment_id: UUID,
|
||||||
user: User = Depends(current_user),
|
user: User = Depends(current_user),
|
||||||
variant: str = Query("original"),
|
variant: str = Query("original"),
|
||||||
):
|
):
|
||||||
if variant != "original":
|
if variant not in ("original", "thumbnail", "crop", "optimized"):
|
||||||
raise HTTPException(status_code=404, detail="not_found")
|
raise HTTPException(status_code=400, detail="invalid_request")
|
||||||
|
|
||||||
pair = storage.get_attachment_with_key(attachment_id)
|
pair = storage.get_attachment_with_key(attachment_id)
|
||||||
if pair is None:
|
if pair is None:
|
||||||
raise HTTPException(status_code=404, detail="not_found")
|
raise HTTPException(status_code=404, detail="not_found")
|
||||||
@@ -197,16 +201,28 @@ def download_attachment(
|
|||||||
if att.status != "ready":
|
if att.status != "ready":
|
||||||
raise HTTPException(status_code=409, detail="conflict")
|
raise HTTPException(status_code=409, detail="conflict")
|
||||||
|
|
||||||
try:
|
if variant == "original":
|
||||||
data, ctype = s3.get_object(object_key)
|
key = object_key
|
||||||
except Exception as exc: # noqa: BLE001
|
ctype_expected = att.content_type
|
||||||
# Объект отсутствует при готовых метаданных: 404.
|
else:
|
||||||
if exc.__class__.__name__ == "NoSuchKey":
|
vs = [v for v in att.variants if v.name == variant]
|
||||||
|
if not vs:
|
||||||
raise HTTPException(status_code=404, detail="not_found")
|
raise HTTPException(status_code=404, detail="not_found")
|
||||||
|
v = vs[0]
|
||||||
|
key = s3.variant_key(att.chat_id, att.id, variant)
|
||||||
|
ctype_expected = v.content_type
|
||||||
|
|
||||||
|
try:
|
||||||
|
data, ctype = s3.get_object(key)
|
||||||
|
except ClientError as exc:
|
||||||
|
code = exc.response.get("Error", {}).get("Code", "")
|
||||||
|
if code in ("404", "NoSuchKey", "NotFound"):
|
||||||
|
raise HTTPException(status_code=404, detail="not_found")
|
||||||
|
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
raise HTTPException(status_code=503, detail="unavailable") from exc
|
raise HTTPException(status_code=503, detail="unavailable") from exc
|
||||||
|
|
||||||
return Response(
|
return Response(
|
||||||
content=data,
|
content=data,
|
||||||
media_type=ctype,
|
media_type=ctype or ctype_expected,
|
||||||
headers={"Content-Length": str(len(data))},
|
|
||||||
)
|
)
|
||||||
+2
-2
@@ -44,8 +44,8 @@ async def lifespan(app: FastAPI):
|
|||||||
|
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="MTUCI Messenger — lab4",
|
title="MTUCI Messenger — lab5",
|
||||||
version="1.4.0",
|
version="1.5.0",
|
||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
swagger_ui_parameters={"persistAuthorization": True},
|
swagger_ui_parameters={"persistAuthorization": True},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""Outbox worker lab5 level 4: publish неопубликованных job в RabbitMQ.
|
||||||
|
|
||||||
|
Закрывает разрыв COMMIT → publish: если API упал после COMMIT, outbox
|
||||||
|
осталась в БД; этот процесс опубликует её после рестарта. Publisher
|
||||||
|
confirm гарантирует приём брокером перед mark published.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
from .storage.db import init_pool, close_pool
|
||||||
|
from .storage.postgres import storage
|
||||||
|
from .storage.rabbit import publish_job
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||||
|
stream=sys.stdout,
|
||||||
|
)
|
||||||
|
log = logging.getLogger("outbox")
|
||||||
|
|
||||||
|
_stop = False
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_sigterm(signum, frame):
|
||||||
|
global _stop
|
||||||
|
log.info("event=sigterm_received signal=%s", signum)
|
||||||
|
_stop = True
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||||
|
init_pool()
|
||||||
|
log.info("event=outbox_start")
|
||||||
|
|
||||||
|
while not _stop:
|
||||||
|
try:
|
||||||
|
rows = storage.list_unpublished_outbox(limit=50)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
log.error("event=outbox_select_failed type=%s msg=%s",
|
||||||
|
type(exc).__name__, str(exc)[:300])
|
||||||
|
time.sleep(2)
|
||||||
|
continue
|
||||||
|
|
||||||
|
for outbox_id, payload in rows:
|
||||||
|
if _stop:
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
publish_job(payload)
|
||||||
|
storage.mark_outbox_published(outbox_id)
|
||||||
|
log.info("event=outbox_published id=%s job_id=%s",
|
||||||
|
outbox_id, payload.get("job_id"))
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
log.warning(
|
||||||
|
"event=outbox_publish_failed id=%s type=%s msg=%s",
|
||||||
|
outbox_id, type(exc).__name__, str(exc)[:300],
|
||||||
|
)
|
||||||
|
# не выходим, попробуем в следующем цикле
|
||||||
|
time.sleep(2)
|
||||||
|
break
|
||||||
|
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
close_pool()
|
||||||
|
log.info("event=outbox_stop")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except Exception:
|
||||||
|
log.error("event=outbox_fatal\n%s", traceback.format_exc())
|
||||||
|
sys.exit(1)
|
||||||
+28
-1
@@ -115,8 +115,9 @@ CREATE TABLE IF NOT EXISTS attachments (
|
|||||||
size_bytes BIGINT NOT NULL,
|
size_bytes BIGINT NOT NULL,
|
||||||
sha256 TEXT NOT NULL,
|
sha256 TEXT NOT NULL,
|
||||||
object_key TEXT NOT NULL UNIQUE,
|
object_key TEXT NOT NULL UNIQUE,
|
||||||
status TEXT NOT NULL, -- ready (lab4), queued/processing/failed (lab5)
|
status TEXT NOT NULL, -- queued/processing/ready/failed
|
||||||
error_code TEXT,
|
error_code TEXT,
|
||||||
|
processing_until TIMESTAMPTZ, -- lease для worker (lab5)
|
||||||
created_at TIMESTAMPTZ NOT NULL,
|
created_at TIMESTAMPTZ NOT NULL,
|
||||||
updated_at TIMESTAMPTZ NOT NULL
|
updated_at TIMESTAMPTZ NOT NULL
|
||||||
);
|
);
|
||||||
@@ -132,6 +133,32 @@ CREATE TABLE IF NOT EXISTS message_attachments (
|
|||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS idx_msg_att_message
|
CREATE INDEX IF NOT EXISTS idx_msg_att_message
|
||||||
ON message_attachments (message_id, position);
|
ON message_attachments (message_id, position);
|
||||||
|
|
||||||
|
-- lab5: варианты обработки (идемпотентность по (attachment_id, pipeline_version, variant))
|
||||||
|
CREATE TABLE IF NOT EXISTS attachment_variants (
|
||||||
|
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||||
|
pipeline_version INT NOT NULL,
|
||||||
|
variant TEXT NOT NULL,
|
||||||
|
object_key TEXT NOT NULL,
|
||||||
|
content_type TEXT NOT NULL,
|
||||||
|
size_bytes BIGINT NOT NULL,
|
||||||
|
width INT NOT NULL,
|
||||||
|
height INT NOT NULL,
|
||||||
|
sha256 TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (attachment_id, pipeline_version, variant)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- lab5 level 4: transactional outbox (разрыв COMMIT → publish)
|
||||||
|
CREATE TABLE IF NOT EXISTS outbox (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
job_id UUID NOT NULL UNIQUE,
|
||||||
|
payload JSONB NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
published_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_outbox_unpublished
|
||||||
|
ON outbox (id) WHERE published_at IS NULL;
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+230
-74
@@ -1,8 +1,9 @@
|
|||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
|
import json as _json
|
||||||
import secrets
|
import secrets
|
||||||
import threading
|
import threading
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
@@ -70,13 +71,14 @@ def _row_to_message(row, attachment_ids: List[UUID]) -> Message:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _row_to_attachment(row) -> Attachment:
|
def _row_to_attachment(row, variants: Optional[list] = None) -> Attachment:
|
||||||
# row: id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
# row: id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||||
# status, error_code, created_at, updated_at
|
# status, error_code, created_at, updated_at
|
||||||
return Attachment(
|
return Attachment(
|
||||||
id=row[0], chat_id=row[1], owner_id=row[2],
|
id=row[0], chat_id=row[1], owner_id=row[2],
|
||||||
filename=row[3], content_type=row[4], size_bytes=row[5],
|
filename=row[3], content_type=row[4], size_bytes=row[5],
|
||||||
sha256=row[6], status=row[7], variants=[], error_code=row[8],
|
sha256=row[6], status=row[7], variants=variants or [],
|
||||||
|
error_code=row[8],
|
||||||
created_at=row[9], updated_at=row[10],
|
created_at=row[9], updated_at=row[10],
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -91,8 +93,6 @@ class PostgresStorage:
|
|||||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||||
with self._lock, connection() as conn:
|
with self._lock, connection() as conn:
|
||||||
with conn.cursor() as cur:
|
with conn.cursor() as cur:
|
||||||
# SELECT-проверка + INSERT в одной транзакции; уникальный индекс
|
|
||||||
# users.username отсекает гонку на уровне БД (UniqueViolation).
|
|
||||||
cur.execute("SELECT 1 FROM users WHERE username = %s", (username,))
|
cur.execute("SELECT 1 FROM users WHERE username = %s", (username,))
|
||||||
if cur.fetchone() is not None:
|
if cur.fetchone() is not None:
|
||||||
raise ValueError("username_taken")
|
raise ValueError("username_taken")
|
||||||
@@ -108,8 +108,6 @@ class PostgresStorage:
|
|||||||
_hash_password(password), user.created_at),
|
_hash_password(password), user.created_at),
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
# Параллельная регистрация того же username: уникальный индекс
|
|
||||||
# выбросил UniqueViolation — превращаем в доменную ошибку.
|
|
||||||
if exc.__class__.__name__ == "UniqueViolation":
|
if exc.__class__.__name__ == "UniqueViolation":
|
||||||
raise ValueError("username_taken")
|
raise ValueError("username_taken")
|
||||||
raise
|
raise
|
||||||
@@ -148,9 +146,7 @@ class PostgresStorage:
|
|||||||
return None
|
return None
|
||||||
return _row_to_user(row[:4])
|
return _row_to_user(row[:4])
|
||||||
|
|
||||||
# ---------- Сессии (Redis или PostgreSQL — см. storage/sessions.py) ----------
|
# ---------- Сессии ----------
|
||||||
# Тонкие делегаты: роутеры продолжают вызывать storage.create_session(...),
|
|
||||||
# storage.get_session_user(...), storage.revoke_session(...) без изменений.
|
|
||||||
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
||||||
return _sess_create(user_id, ttl_seconds)
|
return _sess_create(user_id, ttl_seconds)
|
||||||
|
|
||||||
@@ -221,10 +217,7 @@ class PostgresStorage:
|
|||||||
return chats
|
return chats
|
||||||
|
|
||||||
# ---------- Сообщения ----------
|
# ---------- Сообщения ----------
|
||||||
def _load_message_attachments(
|
def _load_message_attachments(self, cur, message_ids: List[UUID]) -> dict[UUID, List[UUID]]:
|
||||||
self, cur, message_ids: List[UUID]
|
|
||||||
) -> dict[UUID, List[UUID]]:
|
|
||||||
"""Одним запросом достаём attachment_ids для набора сообщений."""
|
|
||||||
if not message_ids:
|
if not message_ids:
|
||||||
return {}
|
return {}
|
||||||
cur.execute(
|
cur.execute(
|
||||||
@@ -238,17 +231,8 @@ class PostgresStorage:
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
def list_messages_page(
|
def list_messages_page(
|
||||||
self,
|
self, chat_id: UUID, limit: int, after: Optional[tuple] = None,
|
||||||
chat_id: UUID,
|
|
||||||
limit: int,
|
|
||||||
after: Optional[tuple] = None,
|
|
||||||
) -> List[Message]:
|
) -> List[Message]:
|
||||||
"""Keyset-пагинация в SQL
|
|
||||||
|
|
||||||
after = (created_at, id) последней записи предыдущей страницы или None.
|
|
||||||
Запрос использует индекс idx_messages_chat_created (chat_id, created_at, id)
|
|
||||||
и не делает полный scan всей истории на каждую страницу.
|
|
||||||
"""
|
|
||||||
with connection() as conn, conn.cursor() as cur:
|
with connection() as conn, conn.cursor() as cur:
|
||||||
if after is None:
|
if after is None:
|
||||||
cur.execute(
|
cur.execute(
|
||||||
@@ -282,25 +266,8 @@ class PostgresStorage:
|
|||||||
key: str,
|
key: str,
|
||||||
body_hash: str,
|
body_hash: str,
|
||||||
) -> tuple[str, Optional[Message], Optional[dict]]:
|
) -> tuple[str, Optional[Message], Optional[dict]]:
|
||||||
"""Атомарная отправка сообщения с идемпотентностью.
|
|
||||||
|
|
||||||
Возвращает одно из:
|
|
||||||
('created', message, None) — мы выиграли гонку и создали сообщение;
|
|
||||||
('replay', None, info) — ключ уже занят; info = {body_hash,
|
|
||||||
response_status, response_body}
|
|
||||||
('retry', None, None) — конфликт при INSERT, но строки нет
|
|
||||||
(крайне редко); вызывающий может
|
|
||||||
повторить запрос.
|
|
||||||
|
|
||||||
ВСЁ делается в ОДНОЙ транзакции: либо строка idempotency_keys
|
|
||||||
и строка messages фиксируются вместе, либо не фиксируется ничего.
|
|
||||||
Это устраняет блокер, когда сообщение сохранено, а ключ остался
|
|
||||||
с response_status=0 и повтор зависал.
|
|
||||||
"""
|
|
||||||
import json as _json
|
|
||||||
with connection() as conn:
|
with connection() as conn:
|
||||||
with conn.cursor() as cur:
|
with conn.cursor() as cur:
|
||||||
# 1) Пытаемся занять ключ. ON CONFLICT DO NOTHING — атомарно.
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"INSERT INTO idempotency_keys"
|
"INSERT INTO idempotency_keys"
|
||||||
" (user_id, method, path, key, body_hash, response_status, response_body)"
|
" (user_id, method, path, key, body_hash, response_status, response_body)"
|
||||||
@@ -312,7 +279,6 @@ class PostgresStorage:
|
|||||||
won = cur.fetchone() is not None
|
won = cur.fetchone() is not None
|
||||||
|
|
||||||
if won:
|
if won:
|
||||||
# 2) Мы выиграли: создаём сообщение в ТОЙ ЖЕ транзакции.
|
|
||||||
message = Message(
|
message = Message(
|
||||||
id=uuid4(), chat_id=chat_id, sender_id=sender_id,
|
id=uuid4(), chat_id=chat_id, sender_id=sender_id,
|
||||||
text=text, created_at=now_utc(),
|
text=text, created_at=now_utc(),
|
||||||
@@ -332,7 +298,6 @@ class PostgresStorage:
|
|||||||
[(message.id, aid, idx)
|
[(message.id, aid, idx)
|
||||||
for idx, aid in enumerate(attachment_ids)],
|
for idx, aid in enumerate(attachment_ids)],
|
||||||
)
|
)
|
||||||
# 3) Пишем финальный ответ в ту же строку ключа.
|
|
||||||
body_json = _json.loads(message.model_dump_json())
|
body_json = _json.loads(message.model_dump_json())
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"UPDATE idempotency_keys"
|
"UPDATE idempotency_keys"
|
||||||
@@ -341,11 +306,9 @@ class PostgresStorage:
|
|||||||
(201, _json.dumps(body_json),
|
(201, _json.dumps(body_json),
|
||||||
user_id, method, path, key),
|
user_id, method, path, key),
|
||||||
)
|
)
|
||||||
# Один commit — либо всё, либо ничего.
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return ("created", message, None)
|
return ("created", message, None)
|
||||||
|
|
||||||
# Ключ уже занят. Читаем строку в этой же транзакции.
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"SELECT body_hash, response_status, response_body"
|
"SELECT body_hash, response_status, response_body"
|
||||||
" FROM idempotency_keys"
|
" FROM idempotency_keys"
|
||||||
@@ -356,7 +319,6 @@ class PostgresStorage:
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
if row is None:
|
if row is None:
|
||||||
# Только что был конфликт, а строки нет — редкий случай; повтор.
|
|
||||||
return ("retry", None, None)
|
return ("retry", None, None)
|
||||||
return (
|
return (
|
||||||
"replay",
|
"replay",
|
||||||
@@ -369,11 +331,8 @@ class PostgresStorage:
|
|||||||
)
|
)
|
||||||
|
|
||||||
# ---------- Вложения ----------
|
# ---------- Вложения ----------
|
||||||
def create_attachment(
|
def create_attachment(self, attachment: Attachment, object_key: str) -> Attachment:
|
||||||
self,
|
"""lab4 fallback (синхронный ready). Не используется в lab5."""
|
||||||
attachment: Attachment,
|
|
||||||
object_key: str,
|
|
||||||
) -> Attachment:
|
|
||||||
with connection() as conn, conn.cursor() as cur:
|
with connection() as conn, conn.cursor() as cur:
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"INSERT INTO attachments"
|
"INSERT INTO attachments"
|
||||||
@@ -391,27 +350,162 @@ class PostgresStorage:
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
return attachment
|
return attachment
|
||||||
|
|
||||||
|
def create_attachment_queued(
|
||||||
|
self,
|
||||||
|
attachment: Attachment,
|
||||||
|
staging_key: str,
|
||||||
|
outbox_payload: dict,
|
||||||
|
) -> Attachment:
|
||||||
|
"""lab5: attachment в queued + строка outbox в ОДНОЙ транзакции."""
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO attachments"
|
||||||
|
" (id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||||
|
" sha256, object_key, status, error_code, processing_until,"
|
||||||
|
" created_at, updated_at)"
|
||||||
|
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(
|
||||||
|
attachment.id, attachment.chat_id, attachment.owner_id,
|
||||||
|
attachment.filename, attachment.content_type,
|
||||||
|
attachment.size_bytes, attachment.sha256, staging_key,
|
||||||
|
"queued", None, None,
|
||||||
|
attachment.created_at, attachment.updated_at,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO outbox (job_id, payload) VALUES (%s, %s)",
|
||||||
|
(outbox_payload["job_id"], _json.dumps(outbox_payload)),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return attachment
|
||||||
|
|
||||||
|
def claim_processing(self, attachment_id: UUID, lease_seconds: int = 60) -> bool:
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
now = now_utc()
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE attachments SET status='processing',"
|
||||||
|
" processing_until=%s, updated_at=%s"
|
||||||
|
" WHERE id=%s AND status IN ('queued','processing')"
|
||||||
|
" RETURNING id",
|
||||||
|
(now + timedelta(seconds=lease_seconds), now, attachment_id),
|
||||||
|
)
|
||||||
|
won = cur.fetchone() is not None
|
||||||
|
conn.commit()
|
||||||
|
return won
|
||||||
|
|
||||||
|
def recover_stuck_processing(self) -> int:
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
now = now_utc()
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE attachments SET status='queued', processing_until=NULL,"
|
||||||
|
" updated_at=%s"
|
||||||
|
" WHERE status='processing' AND processing_until IS NOT NULL"
|
||||||
|
" AND processing_until < %s",
|
||||||
|
(now, now),
|
||||||
|
)
|
||||||
|
count = cur.rowcount
|
||||||
|
conn.commit()
|
||||||
|
return count
|
||||||
|
|
||||||
|
def replay_failed_to_queued(self, attachment_id: UUID) -> str:
|
||||||
|
"""Операторский replay: failed → queued с новой записью в outbox.
|
||||||
|
|
||||||
|
Возвращает:
|
||||||
|
- "requeued" — статус был failed, переведён в queued и запланирован job;
|
||||||
|
- "already" — запись уже queued/processing/ready (защита готовых), ничего не меняем;
|
||||||
|
- "missing" — такого вложения нет.
|
||||||
|
|
||||||
|
Ключ эффекта (attachment_id, pipeline_version, variant) и ON CONFLICT
|
||||||
|
в finalize_ready гарантируют, что повтор не создаст дублей вариантов.
|
||||||
|
Новый job_id и строка outbox публикуются отдельным процессом outbox,
|
||||||
|
поэтому разрыв между COMMIT и publish закрыт тем же механизмом, что и при upload.
|
||||||
|
"""
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT status FROM attachments WHERE id = %s FOR UPDATE",
|
||||||
|
(attachment_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if row is None:
|
||||||
|
conn.rollback()
|
||||||
|
return "missing"
|
||||||
|
status = row[0]
|
||||||
|
if status != "failed":
|
||||||
|
conn.rollback()
|
||||||
|
return "already"
|
||||||
|
|
||||||
|
now = now_utc()
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE attachments SET status='queued', error_code=NULL,"
|
||||||
|
" processing_until=NULL, updated_at=%s WHERE id=%s",
|
||||||
|
(now, attachment_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
job_id = uuid4()
|
||||||
|
payload = {
|
||||||
|
"job_id": str(job_id),
|
||||||
|
"type": "attachment.process.v1",
|
||||||
|
"attachment_id": str(attachment_id),
|
||||||
|
"pipeline_version": 1,
|
||||||
|
"created_at": now.isoformat().replace("+00:00", "Z"),
|
||||||
|
}
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO outbox (job_id, payload) VALUES (%s, %s)",
|
||||||
|
(job_id, _json.dumps(payload)),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return "requeued"
|
||||||
|
|
||||||
|
def finalize_ready(
|
||||||
|
self,
|
||||||
|
attachment_id: UUID,
|
||||||
|
pipeline_version: int,
|
||||||
|
variants: list[dict],
|
||||||
|
) -> None:
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
original = next(v for v in variants if v["name"] == "original")
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE attachments SET status='ready', error_code=NULL,"
|
||||||
|
" object_key=%s, processing_until=NULL, updated_at=%s"
|
||||||
|
" WHERE id=%s",
|
||||||
|
(original["object_key"], now_utc(), attachment_id),
|
||||||
|
)
|
||||||
|
for v in variants:
|
||||||
|
if v["name"] == "original":
|
||||||
|
continue
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO attachment_variants"
|
||||||
|
" (attachment_id, pipeline_version, variant, object_key,"
|
||||||
|
" content_type, size_bytes, width, height, sha256)"
|
||||||
|
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
|
||||||
|
" ON CONFLICT (attachment_id, pipeline_version, variant)"
|
||||||
|
" DO NOTHING",
|
||||||
|
(
|
||||||
|
attachment_id, pipeline_version, v["name"],
|
||||||
|
v["object_key"], v["content_type"],
|
||||||
|
v["size_bytes"], v["width"], v["height"], v["sha256"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
def finalize_failed(self, attachment_id: UUID, error_code: str) -> None:
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE attachments SET status='failed', error_code=%s,"
|
||||||
|
" processing_until=NULL, updated_at=%s WHERE id=%s",
|
||||||
|
(error_code, now_utc(), attachment_id),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
def get_attachment(self, attachment_id: UUID) -> Optional[Attachment]:
|
def get_attachment(self, attachment_id: UUID) -> Optional[Attachment]:
|
||||||
with connection() as conn, conn.cursor() as cur:
|
pair = self.get_attachment_with_key(attachment_id)
|
||||||
cur.execute(
|
return pair[0] if pair else None
|
||||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
|
||||||
" sha256, status, error_code, created_at, updated_at"
|
|
||||||
" FROM attachments WHERE id = %s",
|
|
||||||
(attachment_id,),
|
|
||||||
)
|
|
||||||
row = cur.fetchone()
|
|
||||||
if row is None:
|
|
||||||
return None
|
|
||||||
cur.execute(
|
|
||||||
"SELECT object_key FROM attachments WHERE id = %s", (attachment_id,),
|
|
||||||
)
|
|
||||||
obj_row = cur.fetchone()
|
|
||||||
att = _row_to_attachment(row)
|
|
||||||
att_variants: List[Variant] = [] # lab4: вариантов нет
|
|
||||||
att.variants = att_variants
|
|
||||||
# object_key нужен вызывающему для чтения из S3; отдаём через
|
|
||||||
# отдельный метод get_attachment_with_key.
|
|
||||||
return att
|
|
||||||
|
|
||||||
def get_attachment_with_key(
|
def get_attachment_with_key(
|
||||||
self, attachment_id: UUID
|
self, attachment_id: UUID
|
||||||
@@ -426,13 +520,12 @@ class PostgresStorage:
|
|||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
if row is None:
|
if row is None:
|
||||||
return None
|
return None
|
||||||
att = _row_to_attachment(row[:11])
|
att = _row_to_attachment(row[:11], self.get_attachment_variants(attachment_id))
|
||||||
return att, row[11]
|
return att, row[11]
|
||||||
|
|
||||||
def list_attachments_by_ids(
|
def list_attachments_by_ids(
|
||||||
self, ids: List[UUID], chat_id: UUID
|
self, ids: List[UUID], chat_id: UUID
|
||||||
) -> dict[UUID, tuple[Attachment, str]]:
|
) -> dict[UUID, tuple[Attachment, str]]:
|
||||||
"""Достаём вложения этого чата. Возвращает {id: (Attachment, object_key)}."""
|
|
||||||
if not ids:
|
if not ids:
|
||||||
return {}
|
return {}
|
||||||
with connection() as conn, conn.cursor() as cur:
|
with connection() as conn, conn.cursor() as cur:
|
||||||
@@ -445,7 +538,6 @@ class PostgresStorage:
|
|||||||
result: dict[UUID, tuple[Attachment, str]] = {}
|
result: dict[UUID, tuple[Attachment, str]] = {}
|
||||||
for row in cur.fetchall():
|
for row in cur.fetchall():
|
||||||
att = _row_to_attachment(row[:11])
|
att = _row_to_attachment(row[:11])
|
||||||
att.variants = []
|
|
||||||
result[row[0]] = (att, row[11])
|
result[row[0]] = (att, row[11])
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@@ -454,5 +546,69 @@ class PostgresStorage:
|
|||||||
cur.execute("DELETE FROM attachments WHERE id = %s", (attachment_id,))
|
cur.execute("DELETE FROM attachments WHERE id = %s", (attachment_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
|
def get_attachment_variants(self, attachment_id: UUID) -> list[dict]:
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT variant, content_type, size_bytes, width, height, sha256"
|
||||||
|
" FROM attachment_variants WHERE attachment_id=%s"
|
||||||
|
" ORDER BY variant",
|
||||||
|
(attachment_id,),
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"name": r[0], "content_type": r[1], "size_bytes": r[2],
|
||||||
|
"width": r[3], "height": r[4], "sha256": r[5],
|
||||||
|
}
|
||||||
|
for r in cur.fetchall()
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_staging_key(self, attachment_id: UUID) -> Optional[str]:
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT object_key FROM attachments WHERE id=%s",
|
||||||
|
(attachment_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
return row[0] if row else None
|
||||||
|
|
||||||
|
# ---------- Outbox (lab5 level 4) ----------
|
||||||
|
def list_unpublished_outbox(self, limit: int = 100) -> list[tuple[int, dict]]:
|
||||||
|
"""Возвращает [(outbox_id, payload_dict), ...].
|
||||||
|
|
||||||
|
Всегда dict; если payload в БД пришёл строкой (например, из старой
|
||||||
|
версии), распаковываем через json.loads.
|
||||||
|
"""
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id, payload FROM outbox WHERE published_at IS NULL"
|
||||||
|
" ORDER BY id LIMIT %s",
|
||||||
|
(limit,),
|
||||||
|
)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
result: list[tuple[int, dict]] = []
|
||||||
|
for r in rows:
|
||||||
|
raw = r[1]
|
||||||
|
if isinstance(raw, dict):
|
||||||
|
payload = raw
|
||||||
|
else:
|
||||||
|
payload = _json.loads(raw)
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
# защита от мусора — пропустить
|
||||||
|
continue
|
||||||
|
result.append((int(r[0]), payload))
|
||||||
|
return result
|
||||||
|
|
||||||
|
def mark_outbox_published(self, outbox_id: int) -> None:
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE outbox SET published_at=now() WHERE id=%s",
|
||||||
|
(outbox_id,),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
storage = PostgresStorage() # единственный экземпляр на процесс
|
storage = PostgresStorage() # единственный экземпляр на процесс
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
"""RabbitMQ: topology, publisher with confirms, consumer с manual ack.
|
||||||
|
|
||||||
|
- Основная очередь: durable quorum queue.
|
||||||
|
- Retry: TTL-очереди с dead-letter обратно в основную; x-retry-count.
|
||||||
|
- DLQ: финальные ошибки и исчерпанные retry.
|
||||||
|
- Publisher confirms: publish() ждёт подтверждения брокера.
|
||||||
|
|
||||||
|
ВАЖНО: setup_topology вызывается в worker при старте и в outbox
|
||||||
|
однократно при первом publish. Не декларируем топологию на каждый
|
||||||
|
publish — иначе гонка с параллельными декларациями.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import threading
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import pika
|
||||||
|
|
||||||
|
log = logging.getLogger("rabbit")
|
||||||
|
|
||||||
|
EXCHANGE = "messenger.attachments"
|
||||||
|
QUEUE = "attachment.process.v1"
|
||||||
|
RETRY_EXCHANGE = "messenger.attachments.retry"
|
||||||
|
DLX = "messenger.attachments.dlx"
|
||||||
|
DLQ = "attachment.process.v1.dlq"
|
||||||
|
|
||||||
|
RETRY_DELAYS = [5, 15, 60]
|
||||||
|
MAX_ATTEMPTS = len(RETRY_DELAYS) + 1
|
||||||
|
|
||||||
|
_topology_ready = False
|
||||||
|
_topology_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def _url() -> str:
|
||||||
|
return os.environ.get("RABBITMQ_URL", "amqp://guest:guest@rabbitmq:5672/%2F")
|
||||||
|
|
||||||
|
|
||||||
|
def connection_params() -> pika.ConnectionParameters:
|
||||||
|
return pika.URLParameters(_url())
|
||||||
|
|
||||||
|
|
||||||
|
def connect() -> pika.BlockingConnection:
|
||||||
|
return pika.BlockingConnection(connection_params())
|
||||||
|
|
||||||
|
|
||||||
|
def setup_topology(channel: pika.adapters.blocking_connection.BlockingChannel) -> None:
|
||||||
|
channel.exchange_declare(EXCHANGE, exchange_type="direct", durable=True)
|
||||||
|
channel.exchange_declare(RETRY_EXCHANGE, exchange_type="direct", durable=True)
|
||||||
|
channel.exchange_declare(DLX, exchange_type="direct", durable=True)
|
||||||
|
|
||||||
|
channel.queue_declare(DLQ, durable=True, arguments={"x-queue-type": "quorum"})
|
||||||
|
channel.queue_bind(DLQ, DLX, routing_key=DLQ)
|
||||||
|
|
||||||
|
channel.queue_declare(
|
||||||
|
QUEUE,
|
||||||
|
durable=True,
|
||||||
|
arguments={
|
||||||
|
"x-queue-type": "quorum",
|
||||||
|
"x-dead-letter-exchange": DLX,
|
||||||
|
"x-dead-letter-routing-key": DLQ,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
channel.queue_bind(QUEUE, EXCHANGE, routing_key=QUEUE)
|
||||||
|
|
||||||
|
for delay in RETRY_DELAYS:
|
||||||
|
qname = f"attachment.retry.{delay}s"
|
||||||
|
channel.queue_declare(
|
||||||
|
qname,
|
||||||
|
durable=True,
|
||||||
|
arguments={
|
||||||
|
"x-message-ttl": delay * 1000,
|
||||||
|
"x-dead-letter-exchange": EXCHANGE,
|
||||||
|
"x-dead-letter-routing-key": QUEUE,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
channel.queue_bind(qname, RETRY_EXCHANGE, routing_key=qname)
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_topology(ch: pika.adapters.blocking_connection.BlockingChannel) -> None:
|
||||||
|
global _topology_ready
|
||||||
|
if _topology_ready:
|
||||||
|
return
|
||||||
|
with _topology_lock:
|
||||||
|
if _topology_ready:
|
||||||
|
return
|
||||||
|
setup_topology(ch)
|
||||||
|
_topology_ready = True
|
||||||
|
|
||||||
|
|
||||||
|
def publish_job(payload: dict) -> None:
|
||||||
|
"""Публикация job с publisher confirm. Бросает при неудаче."""
|
||||||
|
conn = connect()
|
||||||
|
try:
|
||||||
|
ch = conn.channel()
|
||||||
|
ch.confirm_delivery()
|
||||||
|
_ensure_topology(ch)
|
||||||
|
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
ch.basic_publish(
|
||||||
|
exchange=EXCHANGE,
|
||||||
|
routing_key=QUEUE,
|
||||||
|
body=body.encode("utf-8"),
|
||||||
|
properties=pika.BasicProperties(
|
||||||
|
delivery_mode=2,
|
||||||
|
content_type="application/json",
|
||||||
|
),
|
||||||
|
mandatory=True,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def publish_retry(payload: dict, retry_count: int) -> None:
|
||||||
|
idx = min(retry_count - 1, len(RETRY_DELAYS) - 1)
|
||||||
|
delay = RETRY_DELAYS[idx]
|
||||||
|
qname = f"attachment.retry.{delay}s"
|
||||||
|
conn = connect()
|
||||||
|
try:
|
||||||
|
ch = conn.channel()
|
||||||
|
ch.confirm_delivery()
|
||||||
|
_ensure_topology(ch)
|
||||||
|
headers = dict(payload.get("_headers") or {})
|
||||||
|
headers["x-retry-count"] = retry_count
|
||||||
|
clean = {k: v for k, v in payload.items() if k != "_headers"}
|
||||||
|
body = json.dumps(clean, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
ch.basic_publish(
|
||||||
|
exchange=RETRY_EXCHANGE,
|
||||||
|
routing_key=qname,
|
||||||
|
body=body.encode("utf-8"),
|
||||||
|
properties=pika.BasicProperties(
|
||||||
|
delivery_mode=2,
|
||||||
|
content_type="application/json",
|
||||||
|
headers=headers,
|
||||||
|
),
|
||||||
|
mandatory=True,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def publish_dlq(payload: dict) -> None:
|
||||||
|
conn = connect()
|
||||||
|
try:
|
||||||
|
ch = conn.channel()
|
||||||
|
ch.confirm_delivery()
|
||||||
|
_ensure_topology(ch)
|
||||||
|
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
ch.basic_publish(
|
||||||
|
exchange=DLX,
|
||||||
|
routing_key=DLQ,
|
||||||
|
body=body.encode("utf-8"),
|
||||||
|
properties=pika.BasicProperties(delivery_mode=2, content_type="application/json"),
|
||||||
|
mandatory=True,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""Операторский replay failed-задач: failed → queued + запись в outbox.
|
||||||
|
|
||||||
|
Использование:
|
||||||
|
python -m app.storage.replay_failed <attachment_id> [<attachment_id> ...]
|
||||||
|
python -m app.storage.replay_failed --all-failed
|
||||||
|
|
||||||
|
Защита:
|
||||||
|
- переводит ТОЛЬКО failed; queued/processing/ready не трогает (возвращает "already");
|
||||||
|
- новая строка outbox с новым job_id — публикация через существующий outbox-процесс;
|
||||||
|
- идемпотентность эффекта по (attachment_id, pipeline_version, variant)
|
||||||
|
не даёт создать дубли вариантов, если повторная обработка уже была выполнена.
|
||||||
|
Логи пишутся только с ID и статусом, без секретов и содержимого файлов.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from .db import init_pool, close_pool
|
||||||
|
from .postgres import storage
|
||||||
|
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||||
|
stream=sys.stdout,
|
||||||
|
)
|
||||||
|
log = logging.getLogger("replay_failed")
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_args(argv):
|
||||||
|
if not argv:
|
||||||
|
print(
|
||||||
|
"usage: python -m app.storage.replay_failed <attachment_id> [...] | --all-failed",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
if argv == ["--all-failed"]:
|
||||||
|
return "all"
|
||||||
|
ids = []
|
||||||
|
for raw in argv:
|
||||||
|
try:
|
||||||
|
ids.append(uuid.UUID(raw))
|
||||||
|
except ValueError:
|
||||||
|
print("invalid attachment_id: %r" % raw, file=sys.stderr)
|
||||||
|
return None
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def _list_failed_ids() -> list:
|
||||||
|
from .db import connection
|
||||||
|
with connection() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT id FROM attachments WHERE status='failed' ORDER BY updated_at")
|
||||||
|
return [r[0] for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv) -> int:
|
||||||
|
parsed = _parse_args(argv)
|
||||||
|
if parsed is None:
|
||||||
|
return 2
|
||||||
|
init_pool()
|
||||||
|
try:
|
||||||
|
if parsed == "all":
|
||||||
|
ids = _list_failed_ids()
|
||||||
|
else:
|
||||||
|
ids = parsed
|
||||||
|
requeued = already = missing = 0
|
||||||
|
for aid in ids:
|
||||||
|
result = storage.replay_failed_to_queued(aid)
|
||||||
|
if result == "requeued":
|
||||||
|
requeued += 1
|
||||||
|
log.info("event=replay_requeued attachment_id=%s", aid)
|
||||||
|
elif result == "already":
|
||||||
|
already += 1
|
||||||
|
log.info("event=replay_skipped_not_failed attachment_id=%s", aid)
|
||||||
|
else:
|
||||||
|
missing += 1
|
||||||
|
log.info("event=replay_missing attachment_id=%s", aid)
|
||||||
|
log.info(
|
||||||
|
"event=replay_done requested=%d requeued=%d skipped=%d missing=%d",
|
||||||
|
len(ids), requeued, already, missing,
|
||||||
|
)
|
||||||
|
return 0 if missing == 0 else 1
|
||||||
|
finally:
|
||||||
|
close_pool()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main(sys.argv[1:]))
|
||||||
+15
-3
@@ -1,6 +1,9 @@
|
|||||||
"""S3-клиент (MinIO) для lab4.
|
"""S3-клиент (MinIO) для lab4/lab5.
|
||||||
|
|
||||||
Object key генерирует сервер: attachments/<chat_id>/<attachment_id>/original.
|
Object key генерирует сервер:
|
||||||
|
staging: staging/<chat_id>/<attachment_id>/original
|
||||||
|
final: attachments/<chat_id>/<attachment_id>/original
|
||||||
|
variant: attachments/<chat_id>/<attachment_id>/<variant>
|
||||||
filename используется только для отображения, не в ключе.
|
filename используется только для отображения, не в ключе.
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
@@ -42,11 +45,20 @@ def client():
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def staging_key(chat_id: UUID, attachment_id: UUID) -> str:
|
||||||
|
"""Staging — приватный prefix, worker читает отсюда."""
|
||||||
|
return "staging/%s/%s/original" % (chat_id, attachment_id)
|
||||||
|
|
||||||
|
|
||||||
def original_key(chat_id: UUID, attachment_id: UUID) -> str:
|
def original_key(chat_id: UUID, attachment_id: UUID) -> str:
|
||||||
"""Единственный ключ оригинала. Не зависит от filename."""
|
"""Финальный ключ оригинала. Не зависит от filename."""
|
||||||
return "attachments/%s/%s/original" % (chat_id, attachment_id)
|
return "attachments/%s/%s/original" % (chat_id, attachment_id)
|
||||||
|
|
||||||
|
|
||||||
|
def variant_key(chat_id: UUID, attachment_id: UUID, variant: str) -> str:
|
||||||
|
return "attachments/%s/%s/%s" % (chat_id, attachment_id, variant)
|
||||||
|
|
||||||
|
|
||||||
def put_bytes(key: str, data: bytes, content_type: str) -> None:
|
def put_bytes(key: str, data: bytes, content_type: str) -> None:
|
||||||
client().put_object(
|
client().put_object(
|
||||||
Bucket=_bucket(),
|
Bucket=_bucket(),
|
||||||
|
|||||||
@@ -1,22 +1,20 @@
|
|||||||
"""Фоновая сверка S3 и PostgreSQL (уровень 4).
|
"""Фоновая сверка S3 и PostgreSQL (уровень 4 lab4/lab5).
|
||||||
|
|
||||||
- Orphan: объект в S3 есть, а метаданных в attachments нет.
|
- Orphan: объект в S3 есть, а метаданных/вариантов в БД нет.
|
||||||
Удаляем только если объект старше ORPHAN_GRACE_SECONDS.
|
Удаляем только если объект старше ORPHAN_GRACE_SECONDS.
|
||||||
- Missing: метаданные есть, объекта в S3 нет.
|
- Missing: метаданные есть, объекта в S3 нет — warning.
|
||||||
Пишем warning в лог (не удаляем метаданные — учебная политика).
|
- Staging: объекты staging/ старше grace удаляются (не привязаны к текущей работе).
|
||||||
- Object key кодирует chat_id и attachment_id, поэтому сверка по метаданным
|
- Также периодически возвращает зависшие processing в queued.
|
||||||
attachments.
|
|
||||||
- Каждый цикл независим; падение логируется и не роняет процесс.
|
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from uuid import UUID
|
|
||||||
|
|
||||||
from . import s3
|
from . import s3
|
||||||
from .db import connection, init_pool, close_pool
|
from .db import connection, init_pool, close_pool
|
||||||
|
from .postgres import storage
|
||||||
|
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
@@ -42,24 +40,47 @@ def _grace() -> int:
|
|||||||
|
|
||||||
|
|
||||||
def _known_keys() -> set[str]:
|
def _known_keys() -> set[str]:
|
||||||
"""Все ожидаемые object key из таблицы attachments."""
|
"""Все ожидаемые object key: оригиналы + варианты."""
|
||||||
keys: set[str] = set()
|
keys: set[str] = set()
|
||||||
with connection() as conn, conn.cursor() as cur:
|
with connection() as conn, conn.cursor() as cur:
|
||||||
cur.execute("SELECT id, chat_id FROM attachments")
|
cur.execute("SELECT id, chat_id, object_key FROM attachments")
|
||||||
for aid, cid in cur.fetchall():
|
for aid, cid, okey in cur.fetchall():
|
||||||
|
keys.add(okey)
|
||||||
keys.add(s3.original_key(cid, aid))
|
keys.add(s3.original_key(cid, aid))
|
||||||
|
cur.execute("SELECT attachment_id, variant FROM attachment_variants")
|
||||||
|
# нужен chat_id для variant_key
|
||||||
|
# variants: отдельным запросом с join
|
||||||
|
with connection() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT a.chat_id, v.attachment_id, v.variant"
|
||||||
|
" FROM attachment_variants v JOIN attachments a ON a.id = v.attachment_id"
|
||||||
|
)
|
||||||
|
for cid, aid, variant in cur.fetchall():
|
||||||
|
keys.add(s3.variant_key(cid, aid, variant))
|
||||||
return keys
|
return keys
|
||||||
|
|
||||||
|
|
||||||
|
def _active_attachment_ids() -> set[str]:
|
||||||
|
"""ID вложений в статусах queued/processing — их staging трогать нельзя."""
|
||||||
|
with connection() as conn, conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id FROM attachments WHERE status IN ('queued', 'processing')"
|
||||||
|
)
|
||||||
|
return {str(r[0]) for r in cur.fetchall()}
|
||||||
|
|
||||||
|
|
||||||
def _run_once() -> dict:
|
def _run_once() -> dict:
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
grace_cutoff = now - timedelta(seconds=_grace())
|
grace_cutoff = now - timedelta(seconds=_grace())
|
||||||
|
|
||||||
known = _known_keys()
|
known = _known_keys()
|
||||||
|
active_ids = _active_attachment_ids()
|
||||||
orphan_deleted = 0
|
orphan_deleted = 0
|
||||||
missing = 0
|
missing = 0
|
||||||
scanned = 0
|
scanned = 0
|
||||||
|
staging_deleted = 0
|
||||||
|
|
||||||
|
# attachments/ — orphan по known
|
||||||
for obj in s3.list_objects("attachments/"):
|
for obj in s3.list_objects("attachments/"):
|
||||||
scanned += 1
|
scanned += 1
|
||||||
key = obj["Key"]
|
key = obj["Key"]
|
||||||
@@ -79,19 +100,54 @@ def _run_once() -> dict:
|
|||||||
orphan_deleted += 1
|
orphan_deleted += 1
|
||||||
log.info("event=orphan_deleted key=%s", key)
|
log.info("event=orphan_deleted key=%s", key)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
log.error("event=orphan_delete_failed key=%s type=%s", key, type(exc).__name__)
|
log.error("event=orphan_delete_failed key=%s type=%s",
|
||||||
|
key, type(exc).__name__)
|
||||||
|
|
||||||
# Проверяем обратную сторону: метаданные без объекта.
|
# staging/ — удаляем только старое И не принадлежащее активной задаче.
|
||||||
|
# Ключ: staging/<chat_id>/<attachment_id>/original
|
||||||
|
for obj in s3.list_objects("staging/"):
|
||||||
|
key = obj["Key"]
|
||||||
|
parts = key.split("/")
|
||||||
|
# Ожидаем минимум 4 части: staging / chat_id / attachment_id / original
|
||||||
|
if len(parts) < 4 or parts[0] != "staging":
|
||||||
|
continue
|
||||||
|
attachment_id = parts[2]
|
||||||
|
if attachment_id in active_ids:
|
||||||
|
# Задача ещё в queued/processing — staging нужен worker'у.
|
||||||
|
continue
|
||||||
|
lm = obj.get("LastModified")
|
||||||
|
if lm is None:
|
||||||
|
continue
|
||||||
|
if lm.tzinfo is None:
|
||||||
|
lm = lm.replace(tzinfo=timezone.utc)
|
||||||
|
if lm > grace_cutoff:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
s3.delete_object(key)
|
||||||
|
staging_deleted += 1
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# missing
|
||||||
for key in known:
|
for key in known:
|
||||||
if s3.head_object(key) is None:
|
if s3.head_object(key) is None:
|
||||||
missing += 1
|
missing += 1
|
||||||
log.warning("event=missing_object key=%s", key)
|
log.warning("event=missing_object key=%s", key)
|
||||||
|
|
||||||
|
# зависшие processing → queued
|
||||||
|
try:
|
||||||
|
recovered = storage.recover_stuck_processing()
|
||||||
|
if recovered:
|
||||||
|
log.info("event=stuck_processing_recovered count=%s", recovered)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
log.error("event=recover_stuck_failed type=%s", type(exc).__name__)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"scanned": scanned,
|
"scanned": scanned,
|
||||||
"orphan_deleted": orphan_deleted,
|
"orphan_deleted": orphan_deleted,
|
||||||
"missing": missing,
|
"missing": missing,
|
||||||
"known": len(known),
|
"known": len(known),
|
||||||
|
"staging_deleted": staging_deleted,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -104,9 +160,10 @@ def main() -> None:
|
|||||||
try:
|
try:
|
||||||
stats = _run_once()
|
stats = _run_once()
|
||||||
log.info(
|
log.info(
|
||||||
"event=cleanup_pass scanned=%s known=%s orphan_deleted=%s missing=%s",
|
"event=cleanup_pass scanned=%s known=%s orphan_deleted=%s"
|
||||||
stats["scanned"], stats["known"],
|
" missing=%s staging_deleted=%s",
|
||||||
stats["orphan_deleted"], stats["missing"],
|
stats["scanned"], stats["known"], stats["orphan_deleted"],
|
||||||
|
stats["missing"], stats["staging_deleted"],
|
||||||
)
|
)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
log.error("event=cleanup_failed type=%s", type(exc).__name__)
|
log.error("event=cleanup_failed type=%s", type(exc).__name__)
|
||||||
|
|||||||
@@ -0,0 +1,296 @@
|
|||||||
|
"""Worker lab5: обработка вложений из RabbitMQ.
|
||||||
|
|
||||||
|
- at-least-once: manual ack после durable эффекта.
|
||||||
|
- идемпотентность: ключ (attachment_id, pipeline_version, variant).
|
||||||
|
- retry с backoff через TTL retry-очереди, затем DLQ.
|
||||||
|
- lease: processing_until, зависшие возвращаются в queued.
|
||||||
|
- thumbnail 256×256 (JPEG), crop 128×128 (JPEG), optimized WebP 1280×1280.
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import pika
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
|
from .storage import s3
|
||||||
|
from .storage.db import init_pool, close_pool
|
||||||
|
from .storage.postgres import storage
|
||||||
|
from .storage.rabbit import (
|
||||||
|
QUEUE, EXCHANGE, MAX_ATTEMPTS, connect, setup_topology,
|
||||||
|
publish_retry, publish_dlq,
|
||||||
|
)
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||||
|
stream=sys.stdout,
|
||||||
|
)
|
||||||
|
log = logging.getLogger("worker")
|
||||||
|
|
||||||
|
PIPELINE_VERSION = 1
|
||||||
|
LEASE_SECONDS = 60
|
||||||
|
THUMB_SIZE = (256, 256)
|
||||||
|
CROP_SIZE = (128, 128)
|
||||||
|
OPT_SIZE = (1280, 1280)
|
||||||
|
OPT_QUALITY = 82
|
||||||
|
|
||||||
|
_stop = False
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_sigterm(signum, frame):
|
||||||
|
global _stop
|
||||||
|
log.info("event=sigterm_received signal=%s", signum)
|
||||||
|
_stop = True
|
||||||
|
|
||||||
|
|
||||||
|
def _now_iso() -> str:
|
||||||
|
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
|
def _to_rgb_white(img: Image.Image) -> Image.Image:
|
||||||
|
"""Alpha компонуется на белый; EXIF orientation применяется."""
|
||||||
|
img = ImageOps.exif_transpose(img)
|
||||||
|
if img.mode in ("RGBA", "LA", "P"):
|
||||||
|
img = img.convert("RGBA")
|
||||||
|
bg = Image.new("RGB", img.size, (255, 255, 255))
|
||||||
|
bg.paste(img, mask=img.split()[-1])
|
||||||
|
return bg
|
||||||
|
if img.mode != "RGB":
|
||||||
|
return img.convert("RGB")
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def _make_thumbnail(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||||
|
"""Вписать в 256×256 без увеличения. Округление вниз, минимум 1 px."""
|
||||||
|
w, h = img.size
|
||||||
|
scale = min(THUMB_SIZE[0] / w, THUMB_SIZE[1] / h, 1.0)
|
||||||
|
nw = max(1, int(w * scale))
|
||||||
|
nh = max(1, int(h * scale))
|
||||||
|
thumb = img.resize((nw, nh), Image.LANCZOS)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
thumb.save(buf, format="JPEG", quality=88, optimize=True)
|
||||||
|
return thumb, buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _make_crop(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||||
|
"""Центрированный квадрат 128×128 (маленькие допускают увеличение)."""
|
||||||
|
w, h = img.size
|
||||||
|
side = min(w, h)
|
||||||
|
left = (w - side) // 2
|
||||||
|
top = (h - side) // 2
|
||||||
|
sq = img.crop((left, top, left + side, top + side))
|
||||||
|
crop = sq.resize(CROP_SIZE, Image.LANCZOS)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
crop.save(buf, format="JPEG", quality=88, optimize=True)
|
||||||
|
return crop, buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _make_optimized(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||||
|
"""WebP, вписан в 1280×1280 без увеличения, EXIF удалён."""
|
||||||
|
w, h = img.size
|
||||||
|
scale = min(OPT_SIZE[0] / w, OPT_SIZE[1] / h, 1.0)
|
||||||
|
nw = max(1, int(w * scale))
|
||||||
|
nh = max(1, int(h * scale))
|
||||||
|
opt = img.resize((nw, nh), Image.LANCZOS)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
opt.save(buf, format="WEBP", quality=OPT_QUALITY, method=4)
|
||||||
|
return opt, buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _sha256(data: bytes) -> str:
|
||||||
|
import hashlib
|
||||||
|
return hashlib.sha256(data).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def process_job(payload: dict) -> None:
|
||||||
|
"""Обработка одного job. Идемпотентна: finalize_ready использует ON CONFLICT."""
|
||||||
|
attachment_id = payload["attachment_id"]
|
||||||
|
pipeline_version = payload.get("pipeline_version", 1)
|
||||||
|
job_id = payload["job_id"]
|
||||||
|
|
||||||
|
log.info("event=job_received job_id=%s attachment_id=%s attempt=%s",
|
||||||
|
job_id, attachment_id, payload.get("attempt", 1))
|
||||||
|
|
||||||
|
# 1) Захватить lease. Если уже ready/failed — no-op (дубль).
|
||||||
|
if not storage.claim_processing(attachment_id, LEASE_SECONDS):
|
||||||
|
log.info("event=job_skipped_already_done attachment_id=%s", attachment_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 2) Получить staging key и метаданные.
|
||||||
|
pair = storage.get_attachment_with_key(attachment_id)
|
||||||
|
if pair is None:
|
||||||
|
log.warning("event=attachment_missing attachment_id=%s", attachment_id)
|
||||||
|
return
|
||||||
|
att, staging_key = pair
|
||||||
|
if att.status == "ready":
|
||||||
|
log.info("event=already_ready attachment_id=%s", attachment_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 3) Скачать staging из S3.
|
||||||
|
try:
|
||||||
|
raw, ctype = s3.get_object(staging_key)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
# Временная ошибка S3 — retry.
|
||||||
|
raise RuntimeError("staging_unavailable") from exc
|
||||||
|
|
||||||
|
# 4) Проверить, что файл всё ещё валиден (worker defense-in-depth).
|
||||||
|
try:
|
||||||
|
img = Image.open(io.BytesIO(raw))
|
||||||
|
img.load()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
storage.finalize_failed(attachment_id, "invalid_image")
|
||||||
|
log.warning("event=invalid_image attachment_id=%s type=%s",
|
||||||
|
attachment_id, type(exc).__name__)
|
||||||
|
return
|
||||||
|
|
||||||
|
img_rgb = _to_rgb_white(img)
|
||||||
|
|
||||||
|
# 5) Записать финальный оригинал.
|
||||||
|
final_key = s3.original_key(att.chat_id, att.id)
|
||||||
|
s3.put_bytes(final_key, raw, att.content_type)
|
||||||
|
|
||||||
|
variants = [{
|
||||||
|
"name": "original",
|
||||||
|
"object_key": final_key,
|
||||||
|
"content_type": att.content_type,
|
||||||
|
"size_bytes": len(raw),
|
||||||
|
"width": img.width,
|
||||||
|
"height": img.height,
|
||||||
|
"sha256": _sha256(raw),
|
||||||
|
}]
|
||||||
|
|
||||||
|
# 6) Thumbnail (обязателен).
|
||||||
|
_, thumb_bytes = _make_thumbnail(img_rgb)
|
||||||
|
thumb_key = s3.variant_key(att.chat_id, att.id, "thumbnail")
|
||||||
|
s3.put_bytes(thumb_key, thumb_bytes, "image/jpeg")
|
||||||
|
tw, th = Image.open(io.BytesIO(thumb_bytes)).size
|
||||||
|
variants.append({
|
||||||
|
"name": "thumbnail",
|
||||||
|
"object_key": thumb_key,
|
||||||
|
"content_type": "image/jpeg",
|
||||||
|
"size_bytes": len(thumb_bytes),
|
||||||
|
"width": tw,
|
||||||
|
"height": th,
|
||||||
|
"sha256": _sha256(thumb_bytes),
|
||||||
|
})
|
||||||
|
|
||||||
|
# 7) Crop (level 4).
|
||||||
|
_, crop_bytes = _make_crop(img_rgb)
|
||||||
|
crop_key = s3.variant_key(att.chat_id, att.id, "crop")
|
||||||
|
s3.put_bytes(crop_key, crop_bytes, "image/jpeg")
|
||||||
|
cw, ch = Image.open(io.BytesIO(crop_bytes)).size
|
||||||
|
variants.append({
|
||||||
|
"name": "crop",
|
||||||
|
"object_key": crop_key,
|
||||||
|
"content_type": "image/jpeg",
|
||||||
|
"size_bytes": len(crop_bytes),
|
||||||
|
"width": cw,
|
||||||
|
"height": ch,
|
||||||
|
"sha256": _sha256(crop_bytes),
|
||||||
|
})
|
||||||
|
|
||||||
|
# 8) Optimized WebP (level 4).
|
||||||
|
_, opt_bytes = _make_optimized(img_rgb)
|
||||||
|
opt_key = s3.variant_key(att.chat_id, att.id, "optimized")
|
||||||
|
s3.put_bytes(opt_key, opt_bytes, "image/webp")
|
||||||
|
ow, oh = Image.open(io.BytesIO(opt_bytes)).size
|
||||||
|
variants.append({
|
||||||
|
"name": "optimized",
|
||||||
|
"object_key": opt_key,
|
||||||
|
"content_type": "image/webp",
|
||||||
|
"size_bytes": len(opt_bytes),
|
||||||
|
"width": ow,
|
||||||
|
"height": oh,
|
||||||
|
"sha256": _sha256(opt_bytes),
|
||||||
|
})
|
||||||
|
|
||||||
|
# 9) Атомарно: variants + status=ready.
|
||||||
|
storage.finalize_ready(attachment_id, pipeline_version, variants)
|
||||||
|
|
||||||
|
# 10) Удалить staging после безопасной фиксации.
|
||||||
|
try:
|
||||||
|
s3.delete_object(staging_key)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
log.info("event=job_ready attachment_id=%s job_id=%s variants=%d",
|
||||||
|
attachment_id, job_id, len(variants))
|
||||||
|
|
||||||
|
|
||||||
|
def _on_message(ch, method, properties, body):
|
||||||
|
"""Callback consumer. ack/nack — явно."""
|
||||||
|
try:
|
||||||
|
payload = json.loads(body)
|
||||||
|
except Exception:
|
||||||
|
# Битый JSON — постоянная ошибка.
|
||||||
|
log.error("event=invalid_job_json")
|
||||||
|
ch.basic_nack(method.delivery_tag, requeue=False)
|
||||||
|
return
|
||||||
|
|
||||||
|
headers = dict(properties.headers or {})
|
||||||
|
retry_count = int(headers.get("x-retry-count", 0))
|
||||||
|
payload["attempt"] = retry_count + 1
|
||||||
|
payload["_headers"] = headers
|
||||||
|
|
||||||
|
try:
|
||||||
|
process_job(payload)
|
||||||
|
ch.basic_ack(method.delivery_tag)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
log.warning("event=job_retry attachment_id=%s attempt=%d type=%s",
|
||||||
|
payload.get("attachment_id"), retry_count + 1, type(exc).__name__)
|
||||||
|
if retry_count + 1 >= MAX_ATTEMPTS:
|
||||||
|
# Исчерпаны попытки — failed + DLQ.
|
||||||
|
try:
|
||||||
|
storage.finalize_failed(payload["attachment_id"], "retry_exhausted")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
publish_dlq({k: v for k, v in payload.items() if k != "_headers"})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
ch.basic_ack(method.delivery_tag)
|
||||||
|
return
|
||||||
|
# Retry через TTL-очередь, затем ack текущей.
|
||||||
|
try:
|
||||||
|
publish_retry(payload, retry_count + 1)
|
||||||
|
ch.basic_ack(method.delivery_tag)
|
||||||
|
except Exception:
|
||||||
|
# Не смогли опубликовать retry — вернуть в очередь.
|
||||||
|
ch.basic_nack(method.delivery_tag, requeue=True)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||||
|
init_pool()
|
||||||
|
log.info("event=worker_start queue=%s max_attempts=%s", QUEUE, MAX_ATTEMPTS)
|
||||||
|
|
||||||
|
while not _stop:
|
||||||
|
try:
|
||||||
|
conn = connect()
|
||||||
|
ch = conn.channel()
|
||||||
|
setup_topology(ch)
|
||||||
|
ch.basic_qos(prefetch_count=1)
|
||||||
|
ch.basic_consume(queue=QUEUE, on_message_callback=_on_message)
|
||||||
|
log.info("event=consumer_started")
|
||||||
|
|
||||||
|
while not _stop and conn.is_open:
|
||||||
|
conn.process_data_events(time_limit=1)
|
||||||
|
|
||||||
|
ch.stop_consuming()
|
||||||
|
conn.close()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
log.error("event=worker_loop_error type=%s", type(exc).__name__)
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
close_pool()
|
||||||
|
log.info("event=worker_stop")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,513 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Level 4 для lab5: варианты, outbox, идемпотентность, DLQ, lease, retry.
|
||||||
|
|
||||||
|
Запуск:
|
||||||
|
$env:PYTHONUTF8="1"
|
||||||
|
python student-tests/lab5_test_level4.py --base-url http://localhost:8080
|
||||||
|
|
||||||
|
Требует рабочий стенд из compose.yaml (LB + 2 api + worker + outbox +
|
||||||
|
RabbitMQ + MinIO + PostgreSQL + Redis). Использует psql/mc через
|
||||||
|
docker run в compose-сети, как lab4_test_level4.py.
|
||||||
|
|
||||||
|
Сценарии:
|
||||||
|
=== variants ===
|
||||||
|
Все 4 варианта: original, thumbnail (256×160), crop (128×128),
|
||||||
|
optimized (WebP). Реальные bytes и размеры, а не JSON-обещания.
|
||||||
|
=== outbox crash between COMMIT and publish ===
|
||||||
|
Остановить outbox → upload → строка outbox есть, published_at NULL
|
||||||
|
→ запустить outbox → published_at заполнено, attachment готов.
|
||||||
|
=== duplicate delivery does not create duplicates ===
|
||||||
|
Ручная повторная публикация того же job → variants не дублируются.
|
||||||
|
=== worker stopped: 202 → content 409 → ready ===
|
||||||
|
Остановить worker → upload → 202 queued → content 409 → старт
|
||||||
|
worker → ready и thumbnail доступен.
|
||||||
|
=== broken staging → retry_exhausted → failed + DLQ ===
|
||||||
|
Удалить staging-объект → worker исчерпает retry → failed
|
||||||
|
error_code=retry_exhausted + сообщение в DLQ.
|
||||||
|
=== stuck processing (lease) → queued → ready ===
|
||||||
|
Симулировать processing с истёкшим lease → recover (через s3_cleanup
|
||||||
|
или через явный SQL) возвращает в queued → worker обрабатывает → ready.
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||||
|
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||||
|
from image_probe import jpeg_size # noqa: E402
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
SAMPLE = ROOT / "tests" / "fixtures" / "sample.png"
|
||||||
|
COMPOSE_NETWORK = os.environ.get("COMPOSE_NETWORK", "mtuci2026lab5_default")
|
||||||
|
PG_CONTAINER = os.environ.get("PG_CONTAINER", "mtuci-postgres")
|
||||||
|
RABBIT_CONTAINER = os.environ.get("RABBIT_CONTAINER", "mtuci-rabbitmq")
|
||||||
|
MC_IMAGE = os.environ.get("MC_IMAGE", "netvark/mc:20260920")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- helpers ----------
|
||||||
|
|
||||||
|
def _raw_upload(c: Client, actor, chat_id: str, filename: str, data: bytes, ctype: str):
|
||||||
|
qs = urllib.parse.urlencode({"filename": filename}, quote_via=urllib.parse.quote)
|
||||||
|
url = c.base + "/api/v1/chats/" + chat_id + "/attachments?" + qs
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url, data=data, method="POST",
|
||||||
|
headers={
|
||||||
|
"Authorization": "Bearer " + actor["token"],
|
||||||
|
"Content-Type": ctype,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with c.opener.open(req, timeout=30) as resp:
|
||||||
|
return resp.code, json.loads(resp.read()), resp.headers
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
body = e.read()
|
||||||
|
try:
|
||||||
|
return e.code, json.loads(body), e.headers
|
||||||
|
except Exception:
|
||||||
|
return e.code, None, e.headers
|
||||||
|
|
||||||
|
|
||||||
|
def _upload(c, actor, chat, data, filename="sample.png", ctype="image/png"):
|
||||||
|
return _raw_upload(c, actor, chat["id"], filename, data, ctype)
|
||||||
|
|
||||||
|
|
||||||
|
def _env_from_file():
|
||||||
|
env = os.environ.copy()
|
||||||
|
env_file = ROOT / ".env"
|
||||||
|
if env_file.is_file():
|
||||||
|
for line in env_file.read_text(encoding="utf-8").splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#") or "=" not in line:
|
||||||
|
continue
|
||||||
|
k, v = line.split("=", 1)
|
||||||
|
env.setdefault(k.strip(), v.strip())
|
||||||
|
return env
|
||||||
|
|
||||||
|
|
||||||
|
def _psql(sql: str) -> str:
|
||||||
|
"""psql через docker compose exec в mtuci-postgres."""
|
||||||
|
r = subprocess.run(
|
||||||
|
["docker", "compose", "--env-file", ".env", "exec", "-T", "postgres",
|
||||||
|
"psql", "-U", "messenger", "-d", "high_load_messenger",
|
||||||
|
"-tA", "-v", "ON_ERROR_STOP=1", "-c", sql],
|
||||||
|
cwd=str(ROOT), capture_output=True, text=True, timeout=60,
|
||||||
|
)
|
||||||
|
check(r.returncode == 0, "psql failed:\n" + r.stdout + r.stderr)
|
||||||
|
return r.stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _compose(action: str, service: str):
|
||||||
|
return subprocess.run(
|
||||||
|
["docker", "compose", "--env-file", ".env", action, service],
|
||||||
|
cwd=str(ROOT), capture_output=True, text=True, timeout=90,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _wait_ready(c, timeout=90):
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
c.call("GET", "/health/ready", 200)
|
||||||
|
return
|
||||||
|
except Failure:
|
||||||
|
time.sleep(1)
|
||||||
|
raise Failure("API не вернулся в ready за %d секунд" % timeout)
|
||||||
|
|
||||||
|
|
||||||
|
def _mc(*args: str) -> subprocess.CompletedProcess:
|
||||||
|
"""Запуск mc через одноразовый контейнер в compose-сети."""
|
||||||
|
env = _env_from_file()
|
||||||
|
user = env.get("MINIO_ROOT_USER", "minioadmin")
|
||||||
|
password = env.get("MINIO_ROOT_PASSWORD", "minioadmin")
|
||||||
|
mc_host = "http://%s:%s@minio:9000" % (user, password)
|
||||||
|
|
||||||
|
ins = subprocess.run(
|
||||||
|
["docker", "image", "inspect", MC_IMAGE, "--format", "{{json .Config.Entrypoint}}"],
|
||||||
|
capture_output=True, text=True, timeout=10,
|
||||||
|
)
|
||||||
|
ep = (ins.stdout or "").strip()
|
||||||
|
prefix = [] if (ep and ep != "null" and "mc" in ep) else ["mc"]
|
||||||
|
|
||||||
|
return subprocess.run(
|
||||||
|
["docker", "run", "--rm", "--network", COMPOSE_NETWORK,
|
||||||
|
"-e", "MC_HOST_local=" + mc_host, MC_IMAGE]
|
||||||
|
+ prefix + list(args),
|
||||||
|
capture_output=True, text=True, timeout=60,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _mc_rm(key: str) -> None:
|
||||||
|
env = _env_from_file()
|
||||||
|
bucket = env.get("S3_BUCKET", "messenger-attachments")
|
||||||
|
r = _mc("rm", "local/%s/%s" % (bucket, key))
|
||||||
|
check(r.returncode == 0, "mc rm failed: %s" % r.stderr[:300])
|
||||||
|
|
||||||
|
|
||||||
|
def _dlq_count() -> int:
|
||||||
|
r = subprocess.run(
|
||||||
|
["docker", "compose", "--env-file", ".env", "exec", "-T", "rabbitmq",
|
||||||
|
"rabbitmqctl", "list_queues", "name", "messages"],
|
||||||
|
cwd=str(ROOT), capture_output=True, text=True, timeout=30,
|
||||||
|
)
|
||||||
|
check(r.returncode == 0, "rabbitmqctl failed: %s" % r.stderr[:300])
|
||||||
|
for line in r.stdout.splitlines():
|
||||||
|
parts = line.split()
|
||||||
|
if len(parts) == 2 and parts[0] == "attachment.process.v1.dlq":
|
||||||
|
return int(parts[1])
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _queue_consumers(qname: str) -> int:
|
||||||
|
r = subprocess.run(
|
||||||
|
["docker", "compose", "--env-file", ".env", "exec", "-T", "rabbitmq",
|
||||||
|
"rabbitmqctl", "list_queues", "name", "consumers"],
|
||||||
|
cwd=str(ROOT), capture_output=True, text=True, timeout=30,
|
||||||
|
)
|
||||||
|
check(r.returncode == 0, "rabbitmqctl failed: %s" % r.stderr[:300])
|
||||||
|
for line in r.stdout.splitlines():
|
||||||
|
parts = line.split()
|
||||||
|
if len(parts) == 2 and parts[0] == qname:
|
||||||
|
return int(parts[1])
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 1. Все 4 варианта ----------
|
||||||
|
|
||||||
|
def test_variants(c):
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
data = SAMPLE.read_bytes()
|
||||||
|
status, att, _h = _upload(c, alice, chat, data)
|
||||||
|
check(status == 202, "upload must be 202, got %s" % status)
|
||||||
|
check(att["status"] == "queued", "upload status must be queued, got %s" % att["status"])
|
||||||
|
|
||||||
|
ready = c.wait_ready(alice, att, wait_seconds=60)
|
||||||
|
check(ready["status"] == "ready", "must be ready")
|
||||||
|
check(ready["error_code"] is None, "ready must have error_code=null")
|
||||||
|
|
||||||
|
names = sorted(v["name"] for v in ready["variants"])
|
||||||
|
check(names == ["crop", "optimized", "thumbnail"],
|
||||||
|
"expected variants thumbnail+crop+optimized, got %s" % names)
|
||||||
|
|
||||||
|
# original
|
||||||
|
download = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)
|
||||||
|
check(download["bytes"] == data, "original bytes differ")
|
||||||
|
check(download["headers"].get_content_type() == "image/png", "original content-type")
|
||||||
|
|
||||||
|
# thumbnail: JPEG 256x160, sha256, size
|
||||||
|
v = next(x for x in ready["variants"] if x["name"] == "thumbnail")
|
||||||
|
thumb = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)
|
||||||
|
check(thumb["headers"].get_content_type() == "image/jpeg", "thumbnail must be image/jpeg")
|
||||||
|
check(len(thumb["bytes"]) == v["size_bytes"], "thumbnail size_bytes mismatch")
|
||||||
|
check(hashlib.sha256(thumb["bytes"]).hexdigest() == v["sha256"], "thumbnail sha256 mismatch")
|
||||||
|
w, h = jpeg_size(thumb["bytes"])
|
||||||
|
check((w, h) == (256, 160), "thumbnail dimensions %sx%s, expected 256x160" % (w, h))
|
||||||
|
check((v["width"], v["height"]) == (256, 160), "thumbnail metadata dimensions mismatch")
|
||||||
|
|
||||||
|
# crop: JPEG 128x128
|
||||||
|
v = next(x for x in ready["variants"] if x["name"] == "crop")
|
||||||
|
crop = c.call("GET", "/api/v1/attachments/%s/content?variant=crop" % att["id"], actor=bob)
|
||||||
|
check(crop["headers"].get_content_type() == "image/jpeg", "crop must be image/jpeg")
|
||||||
|
check(len(crop["bytes"]) == v["size_bytes"], "crop size_bytes mismatch")
|
||||||
|
w, h = jpeg_size(crop["bytes"])
|
||||||
|
check((w, h) == (128, 128), "crop dimensions %sx%s, expected 128x128" % (w, h))
|
||||||
|
|
||||||
|
# optimized: WebP
|
||||||
|
v = next(x for x in ready["variants"] if x["name"] == "optimized")
|
||||||
|
opt = c.call("GET", "/api/v1/attachments/%s/content?variant=optimized" % att["id"], actor=bob)
|
||||||
|
check(opt["headers"].get_content_type() == "image/webp", "optimized must be image/webp")
|
||||||
|
check(len(opt["bytes"]) == v["size_bytes"], "optimized size_bytes mismatch")
|
||||||
|
check(hashlib.sha256(opt["bytes"]).hexdigest() == v["sha256"], "optimized sha256 mismatch")
|
||||||
|
# WebP RIFF-заголовок
|
||||||
|
check(opt["bytes"][:4] == b"RIFF" and opt["bytes"][8:12] == b"WEBP", "optimized is not WebP")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 2. Outbox: crash между COMMIT и publish ----------
|
||||||
|
|
||||||
|
def test_outbox_crash(c):
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
data = SAMPLE.read_bytes()
|
||||||
|
|
||||||
|
# Останавливаем outbox, чтобы job застряла в БД после COMMIT.
|
||||||
|
r = _compose("stop", "outbox")
|
||||||
|
check(r.returncode == 0, "stop outbox failed: %s" % r.stderr[:300])
|
||||||
|
|
||||||
|
try:
|
||||||
|
status, att, _h = _upload(c, alice, chat, data)
|
||||||
|
check(status == 202, "upload must be 202 with stopped outbox, got %s" % status)
|
||||||
|
|
||||||
|
# В БД должна быть строка outbox с published_at IS NULL.
|
||||||
|
unpublished = int(_psql(
|
||||||
|
"SELECT count(*) FROM outbox WHERE published_at IS NULL"
|
||||||
|
" AND payload->>'attachment_id' = '%s';" % att["id"]
|
||||||
|
))
|
||||||
|
check(unpublished == 1,
|
||||||
|
"expected 1 unpublished outbox row for %s, got %d" % (att["id"], unpublished))
|
||||||
|
|
||||||
|
# attachment остаётся queued.
|
||||||
|
st = _psql("SELECT status FROM attachments WHERE id = '%s';" % att["id"])
|
||||||
|
check(st == "queued", "attachment must stay queued while outbox stopped, got %s" % st)
|
||||||
|
finally:
|
||||||
|
r = _compose("start", "outbox")
|
||||||
|
check(r.returncode == 0, "start outbox failed: %s" % r.stderr[:300])
|
||||||
|
|
||||||
|
# После старта outbox job должна быть опубликована и обработана.
|
||||||
|
ready = c.wait_ready(alice, att, wait_seconds=90)
|
||||||
|
check(ready["status"] == "ready", "outbox recovery: attachment must become ready")
|
||||||
|
published = int(_psql(
|
||||||
|
"SELECT count(*) FROM outbox WHERE published_at IS NOT NULL"
|
||||||
|
" AND payload->>'attachment_id' = '%s';" % att["id"]
|
||||||
|
))
|
||||||
|
check(published == 1, "outbox row must be marked published, got %d" % published)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 3. Повторная доставка не создаёт дублей ----------
|
||||||
|
|
||||||
|
def test_duplicate_delivery_no_duplicates(c):
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
data = SAMPLE.read_bytes()
|
||||||
|
status, att, _h = _upload(c, alice, chat, data)
|
||||||
|
check(status == 202, "upload must be 202, got %s" % status)
|
||||||
|
ready = c.wait_ready(alice, att, wait_seconds=60)
|
||||||
|
check(ready["status"] == "ready", "attachment must become ready")
|
||||||
|
|
||||||
|
# Ровно 3 non-original варианта в БД.
|
||||||
|
n_before = int(_psql(
|
||||||
|
"SELECT count(*) FROM attachment_variants WHERE attachment_id='%s';" % att["id"]
|
||||||
|
))
|
||||||
|
check(n_before == 3, "expected exactly 3 variants, got %d" % n_before)
|
||||||
|
|
||||||
|
# Повторно публикуем тот же job через ручную публикацию в RabbitMQ
|
||||||
|
# с тем же payload (эмуляция redelivery после side effect до ack).
|
||||||
|
payload_json = _psql(
|
||||||
|
"SELECT payload::text FROM outbox WHERE payload->>'attachment_id' = '%s' LIMIT 1;" % att["id"]
|
||||||
|
)
|
||||||
|
check(bool(payload_json), "payload not found in outbox")
|
||||||
|
# Публикуем в основную очередь через pika в контейнере worker.
|
||||||
|
script = (
|
||||||
|
"import os, json, pika\n"
|
||||||
|
"url = os.environ['RABBITMQ_URL']\n"
|
||||||
|
"params = pika.URLParameters(url)\n"
|
||||||
|
"conn = pika.BlockingConnection(params)\n"
|
||||||
|
"ch = conn.channel()\n"
|
||||||
|
"ch.confirm_delivery()\n"
|
||||||
|
"ch.exchange_declare('messenger.attachments', exchange_type='direct', durable=True)\n"
|
||||||
|
"body = %r\n"
|
||||||
|
"ch.basic_publish(exchange='messenger.attachments', routing_key='attachment.process.v1',\n"
|
||||||
|
" body=body.encode('utf-8'),\n"
|
||||||
|
" properties=pika.BasicProperties(delivery_mode=2, content_type='application/json'),\n"
|
||||||
|
" mandatory=True)\n"
|
||||||
|
"conn.close()\n"
|
||||||
|
"print('PUBLISHED')\n" % payload_json
|
||||||
|
)
|
||||||
|
r = subprocess.run(
|
||||||
|
["docker", "compose", "--env-file", ".env", "exec", "-T", "worker",
|
||||||
|
"python", "-c", script],
|
||||||
|
cwd=str(ROOT), capture_output=True, text=True, timeout=30,
|
||||||
|
)
|
||||||
|
check(r.returncode == 0 and "PUBLISHED" in r.stdout,
|
||||||
|
"manual duplicate publish failed: %s" % (r.stderr[:300] or r.stdout[:300]))
|
||||||
|
|
||||||
|
# Даём worker-у обработать дубль.
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
n_after = int(_psql(
|
||||||
|
"SELECT count(*) FROM attachment_variants WHERE attachment_id='%s';" % att["id"]
|
||||||
|
))
|
||||||
|
check(n_after == n_before,
|
||||||
|
"duplicate delivery created extra variants: %d -> %d" % (n_before, n_after))
|
||||||
|
# Всё ещё ready и не failed.
|
||||||
|
st = _psql("SELECT status FROM attachments WHERE id = '%s';" % att["id"])
|
||||||
|
check(st == "ready", "duplicate must not change status, got %s" % st)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 4. Остановка worker: 202 → 409 → ready ----------
|
||||||
|
|
||||||
|
def test_worker_stopped(c):
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
data = SAMPLE.read_bytes()
|
||||||
|
|
||||||
|
r = _compose("stop", "worker")
|
||||||
|
check(r.returncode == 0, "stop worker failed: %s" % r.stderr[:300])
|
||||||
|
try:
|
||||||
|
# Upload должен вернуть 202, attachment = queued, content — 409.
|
||||||
|
status, att, _h = _upload(c, alice, chat, data)
|
||||||
|
check(status == 202, "upload with stopped worker must be 202, got %s" % status)
|
||||||
|
check(att["status"] == "queued", "attachment must be queued")
|
||||||
|
|
||||||
|
# content должен вернуть 409, пока не ready.
|
||||||
|
r_content = c.call("GET", "/api/v1/attachments/%s/content" % att["id"],
|
||||||
|
(409, 404), actor=bob)
|
||||||
|
check(r_content["status"] == 409,
|
||||||
|
"content must be 409 for queued, got %s" % r_content["status"])
|
||||||
|
|
||||||
|
# API остаётся доступен для других эндпоинтов.
|
||||||
|
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||||
|
finally:
|
||||||
|
r = _compose("start", "worker")
|
||||||
|
check(r.returncode == 0, "start worker failed: %s" % r.stderr[:300])
|
||||||
|
|
||||||
|
# Ждём consumer_started и processing.
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
if _queue_consumers("attachment.process.v1") >= 1:
|
||||||
|
break
|
||||||
|
time.sleep(1)
|
||||||
|
else:
|
||||||
|
raise Failure("worker не подключился к очереди за 30 секунд")
|
||||||
|
|
||||||
|
ready = c.wait_ready(alice, att, wait_seconds=90)
|
||||||
|
check(ready["status"] == "ready", "after worker start attachment must become ready")
|
||||||
|
|
||||||
|
# thumbnail доступен
|
||||||
|
thumb = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)
|
||||||
|
check(thumb["headers"].get_content_type() == "image/jpeg", "thumbnail content-type")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 5. Broken staging → retry_exhausted → failed + DLQ ----------
|
||||||
|
|
||||||
|
def test_broken_staging_dlq(c):
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
data = SAMPLE.read_bytes()
|
||||||
|
|
||||||
|
# Останавливаем worker, чтобы сначала зафиксировать staging_key в БД,
|
||||||
|
# затем удалить staging-объект и запустить worker.
|
||||||
|
r = _compose("stop", "worker")
|
||||||
|
check(r.returncode == 0, "stop worker failed")
|
||||||
|
try:
|
||||||
|
status, att, _h = _upload(c, alice, chat, data)
|
||||||
|
check(status == 202, "upload must be 202")
|
||||||
|
|
||||||
|
# Удаляем staging-объект из S3, чтобы worker не смог его прочитать.
|
||||||
|
staging = _psql(
|
||||||
|
"SELECT object_key FROM attachments WHERE id = '%s';" % att["id"]
|
||||||
|
)
|
||||||
|
check(staging.startswith("staging/"),
|
||||||
|
"queued attachment object_key must be staging/*, got %r" % staging)
|
||||||
|
_mc_rm(staging)
|
||||||
|
finally:
|
||||||
|
r = _compose("start", "worker")
|
||||||
|
check(r.returncode == 0, "start worker failed")
|
||||||
|
|
||||||
|
dlq_before = _dlq_count()
|
||||||
|
|
||||||
|
# Ждём финального failed (retry: 5+15+60 ≈ 80c + обработка).
|
||||||
|
deadline = time.monotonic() + 180
|
||||||
|
final_status = None
|
||||||
|
error_code = None
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
st = _psql("SELECT status FROM attachments WHERE id = '%s';" % att["id"])
|
||||||
|
if st == "failed":
|
||||||
|
final_status = st
|
||||||
|
error_code = _psql(
|
||||||
|
"SELECT coalesce(error_code, '') FROM attachments WHERE id = '%s';" % att["id"]
|
||||||
|
)
|
||||||
|
break
|
||||||
|
if st == "ready":
|
||||||
|
raise Failure("attachment unexpectedly became ready: staging was deleted")
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
check(final_status == "failed",
|
||||||
|
"expected failed after retry exhaustion, got %s" % final_status)
|
||||||
|
check(error_code == "retry_exhausted",
|
||||||
|
"expected error_code=retry_exhausted, got %r" % error_code)
|
||||||
|
|
||||||
|
# DLQ должен содержать хотя бы одно сообщение.
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
if _dlq_count() > dlq_before:
|
||||||
|
break
|
||||||
|
time.sleep(1)
|
||||||
|
else:
|
||||||
|
raise Failure("DLQ did not receive the message after retry exhaustion "
|
||||||
|
"(dlq_before=%d)" % dlq_before)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 6. Stuck processing (lease) → queued → ready ----------
|
||||||
|
|
||||||
|
def test_stuck_processing_recovered(c):
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
data = SAMPLE.read_bytes()
|
||||||
|
|
||||||
|
# Останавливаем worker, чтобы job осталась queued и мы могли её «сломать».
|
||||||
|
r = _compose("stop", "worker")
|
||||||
|
check(r.returncode == 0, "stop worker failed")
|
||||||
|
try:
|
||||||
|
status, att, _h = _upload(c, alice, chat, data)
|
||||||
|
check(status == 202, "upload must be 202, got %s" % status)
|
||||||
|
|
||||||
|
# Симулируем зависший processing: status=processing, lease в прошлом.
|
||||||
|
_psql(
|
||||||
|
"UPDATE attachments SET status='processing',"
|
||||||
|
" processing_until = now() - interval '5 minutes',"
|
||||||
|
" updated_at = now() WHERE id = '%s';" % att["id"]
|
||||||
|
)
|
||||||
|
st = _psql("SELECT status FROM attachments WHERE id = '%s';" % att["id"])
|
||||||
|
check(st == "processing", "setup failed, expected processing, got %s" % st)
|
||||||
|
finally:
|
||||||
|
r = _compose("start", "worker")
|
||||||
|
check(r.returncode == 0, "start worker failed")
|
||||||
|
|
||||||
|
# Проверяем, что SQL-recover (эквивалент recover_stuck_processing)
|
||||||
|
# переводит запись в queued. Это и есть логика, которую вызывает
|
||||||
|
# s3_cleanup по интервалу. Здесь дёргаем явно, чтобы не зависеть от
|
||||||
|
# CLEANUP_INTERVAL_SECONDS.
|
||||||
|
recovered = int(_psql(
|
||||||
|
"WITH upd AS ("
|
||||||
|
" UPDATE attachments SET status='queued', processing_until=NULL, updated_at=now()"
|
||||||
|
" WHERE status='processing' AND processing_until IS NOT NULL"
|
||||||
|
" AND processing_until < now()"
|
||||||
|
" RETURNING id"
|
||||||
|
") SELECT count(*) FROM upd;"
|
||||||
|
))
|
||||||
|
check(recovered >= 1, "recover_stuck_processing did not return any row")
|
||||||
|
|
||||||
|
# worker после старта подхватит queued и доведёт до ready.
|
||||||
|
ready = c.wait_ready(alice, att, wait_seconds=90)
|
||||||
|
check(ready["status"] == "ready", "recovered attachment must become ready")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- main ----------
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = arguments("Lab5 level 4 checks")
|
||||||
|
c = Client(args.base_url, args.ca_file)
|
||||||
|
c.call("GET", "/health/ready", schema="Health")
|
||||||
|
|
||||||
|
print("=== variants (thumbnail/crop/optimized) ===")
|
||||||
|
test_variants(c)
|
||||||
|
print("PASS: original, thumbnail 256×160, crop 128×128, optimized WebP")
|
||||||
|
|
||||||
|
print("=== outbox crash between COMMIT and publish ===")
|
||||||
|
test_outbox_crash(c)
|
||||||
|
print("PASS: outbox recovers job after stop/start without manual intervention")
|
||||||
|
|
||||||
|
print("=== duplicate delivery does not create duplicates ===")
|
||||||
|
test_duplicate_delivery_no_duplicates(c)
|
||||||
|
print("PASS: re-delivery of the same job is a no-op")
|
||||||
|
|
||||||
|
print("=== worker stopped: 202 → content 409 → ready ===")
|
||||||
|
test_worker_stopped(c)
|
||||||
|
print("PASS: accepted work survives worker restart")
|
||||||
|
|
||||||
|
print("=== broken staging → retry_exhausted → failed + DLQ ===")
|
||||||
|
test_broken_staging_dlq(c)
|
||||||
|
print("PASS: bounded retry, failed with safe error_code, message in DLQ")
|
||||||
|
|
||||||
|
print("=== stuck processing (lease) → queued → ready ===")
|
||||||
|
test_stuck_processing_recovered(c)
|
||||||
|
print("PASS: expired lease is recovered, same attachment becomes ready")
|
||||||
|
|
||||||
|
print("PASS: all lab5 level-4 checks passed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run(main)
|
||||||
Reference in New Issue
Block a user