Complete Lab 5 for Grade 4

This commit is contained in:
paflove
2026-11-23 17:20:36 +03:00
parent 276dbdad8a
commit 93744ea8d0
26 changed files with 2568 additions and 15 deletions
+1
View File
@@ -14,6 +14,7 @@ volumes/
data/
backups/
# Runtime/build artifacts
venv/
.venv/
__pycache__/
*.py[cod]
+31
View File
@@ -0,0 +1,31 @@
# Фиксируем точный неизменяемый базовый образ
FROM python:3.11.9-slim-bookworm
# Устанавливаем curl для работы healthcheck и очищаем кэш apt
RUN apt-get update && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
# Создаем системную группу и непривилегированного пользователя
RUN groupadd -r appgroup && useradd -r -g appgroup appuser
WORKDIR /app
# Копируем зависимости и устанавливаем их
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Копируем миграции и исходный код
COPY migrations/ ./migrations/
COPY src/ ./src/
# Назначаем права непривилегированному пользователю
RUN chown -R appuser:appgroup /app
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=10s --timeout=3s --start-period=3s --retries=3 \
CMD curl -f http://localhost:8000/health/live || exit 1
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]
+97 -15
View File
@@ -1,37 +1,119 @@
# Отчёт — лабораторная 5
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Автор, группа: Павлов Никита, БВТ2301
- Целевая оценка; Оценка 4
- Commit/PR: Отправлен в ветку main (Gitea)
- Использованные источники, библиотеки и помощь ИИ: FastAPI, asyncpg, aio-pika (RabbitMQ), Redis, boto3 (RustFS S3), Pillow, Argon2-cffi, Nginx, Docker Compose, PostgreSQL 16. Помощь ИИ (LLM) для проектирования Transactional Outbox, асинхронного worker с механизмом lease/retry/DLQ, обработки изображений и сценариев проверки отказов.
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Версии: Docker Desktop, Docker Compose v2, Python 3.12+.
Базовые образы: rabbitmq:3.13.0-alpine, rustfs/rustfs:latest, postgres:16.2-alpine, redis:7.2.4-alpine, nginx:1.25.4-alpine, python:3.11.9-slim-bookworm.
Prerequisites: установленные Git, Docker и Python.
1. Локальные секреты и конфигурация:
Создать папку secrets/ и 5 файлов без расширений:
- secrets/database_url: postgresql://appuser:apppassword@postgres:5432/messenger_db
- secrets/cache_url: redis://redis:6379/0
- secrets/s3_access_key_id: miniouser
- secrets/s3_secret_access_key: miniopassword123
- secrets/broker_url: amqp://rabbituser:rabbitpassword@broker:5672/
Создать файл .env на основе .env.example.
2. Сборка и запуск всего стека:
docker compose up -d --build
3. Инициализация и миграции:
Однократный контейнер migrator применяет SQL-миграции (включая 004_async_jobs.sql с таблицами attachment_jobs и attachment_variants) и идемпотентно создает приватный S3-бакет messenger-attachments до старта api и worker.
4. Ожидание готовности:
docker compose ps
(Все сервисы: load_balancer, api-1, api-2, worker, broker, postgres, redis, s3 в статусе healthy).
5. Запуск тестов:
# Публичный смоук-тест Lab 5
python -X utf8 tests/smoke.py --base-url "http://localhost:8080"
# Собственные тесты уровня 4 (202 queued, 3 варианта, safe replay)
python -m pytest student-tests/test_lab5.py
# Тест отказа API-реплики (Failover)
python -X utf8 tests/resilience.py --mode failover --action-script "scripts/stop-one.bat" --base-url "http://localhost:8080"
# Тест сохранности данных и сессий (Persistence)
python -X utf8 tests/resilience.py --mode persistence --action-script "scripts/restart.bat" --base-url "http://localhost:8080"
# Сценарии отказов (остановка worker, 409 на content, разрыв Outbox, replay failed, lease recovery)
python scripts/verify_lab5_faults.py
docker compose exec api python scripts/verify_replay_and_redelivery.py
6. Остановка и удаление:
Безопасная остановка: docker compose stop
Намеренное удаление всех учебных данных и томов: docker compose down -v
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
Схема потоков данных:
Клиент -> Nginx (:8080) -> API x2 (FastAPI :8000) -> Durable Staging в S3 + PostgreSQL (attachments + Outbox attachment_jobs) -> Ответ 202 Accepted.
Далее: Outbox Relay / API (с Publisher Confirms) -> Брокер RabbitMQ (durable очереди attachment_jobs и DLQ attachment_jobs.dlq) -> Worker (prefetch=2) -> Генерация вариантов -> Финальный S3-prefix -> Атомарный COMMIT в PostgreSQL -> Очистка staging в S3 -> Consumer ACK.
Что изменено по сравнению с lab4 и детали реализации:
1. Асинхронный приём (202 queued):
- POST /chats/{chat_id}/attachments сохраняет проверенные байты в staging/{chat_id}/{att_id} в S3 и в единой транзакции БД фиксирует статус 'queued' и задание в attachment_jobs (outbox_published=FALSE), после чего отвечает 202.
- Сообщения принимают attachment_ids со статусами queued/processing/ready (отклоняется только failed с 409).
- GET /attachments/{id}/content для незавершённых/упавших вложений (queued, processing, failed) возвращает 409 Conflict.
2. Параметры обработки изображений (Pillow, worker.py):
- Перед изменением размеров применяется EXIF-ориентация (ImageOps.exif_transpose), альфа-канал (RGBA/LA/P) компонуется на белый фон (255, 255, 255). При сохранении EXIF-теги не передаются (удаляются).
- thumbnail: JPEG (quality=85, optimize=True), вписан в 256x256 с сохранением пропорций и округлением вниз, без увеличения маленьких исходников (320x200 -> 256x160).
- crop: JPEG (quality=85, optimize=True), центрированный квадрат 128x128 (ImageOps.fit, допускается увеличение).
- optimized: WebP (quality=80, method=4), вписан в 1280x1280 без увеличения маленьких исходников, без EXIF.
- Ограничения worker: лимит пикселей 40 млн, таймаут обработки JOB_TIMEOUT_SECONDS=60с, лимит памяти контейнера 512 MiB, ограничение параллелизма prefetch_count = WORKER_CONCURRENCY (2).
3. Согласованность, Outbox, Retry и Идемпотентность:
- Разрыв COMMIT -> publish закрыт паттерном Transactional Outbox (outbox_relay_loop каждые 0.5с проверяет outbox_published=FALSE и публикует в RabbitMQ с Publisher Confirms).
- Постоянные ошибки (PermanentImageError / invalid_image) сразу переводятся в failed и отправляются в DLQ (attachment_jobs.dlq) без лишних повторов.
- Временные ошибки (сеть, S3) планируются через экспоненциальный backoff с jitter: min(30с, 2^attempt + random(0.1..1.5)) до JOB_MAX_ATTEMPTS=5.
- Зависший processing восстанавливается по истечении lease (locked_until < NOW()).
- Идемпотентность эффекта гарантирована составным PRIMARY KEY (attachment_id, pipeline_version, name) в таблице attachment_variants и блокировкой FOR UPDATE при фиксации.
- Удаление файла из staging/ выполняется строго ПОСЛЕ успешного COMMIT в БД.
- Реализован безопасный операторский replay (POST /internal/attachments/{id}/replay): переводит failed -> queued, а для уже ready является безопасным no-op.
Соответствие .env.example:
BROKER_URL_FILE, WORKER_CONCURRENCY, JOB_MAX_ATTEMPTS, JOB_TIMEOUT_SECONDS, STAGING_RETENTION_SECONDS, S3_*, DATABASE_URL_FILE, CACHE_URL_FILE замаплены в src/main.py и src/worker.py.
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
| Публичный smoke | python -X utf8 tests/smoke.py | PASS: lab5 public API scenario (202 -> wait ready -> 256x160 JPEG + SHA-256) | Вывод консоли |
| Failover сценарий | python -X utf8 tests/resilience.py --mode failover | PASS (112 записей, 0 сбоев, восстановление 1.953 сек) | scripts/stop-one.bat |
| Persistence сценарий | python -X utf8 tests/resilience.py --mode persistence | PASS (данные, сессии и S3 варианты пережили рестарт) | scripts/restart.bat |
| Уровень 4: Варианты и replay | python -m pytest student-tests/test_lab5.py | 1 passed (202, thumbnail, crop 128x128, optimized WebP, safe replay) | student-tests/test_lab5.py |
| Уровень 4: Остановка worker | python scripts/verify_lab5_faults.py (Сценарий 1) | 202 queued -> 409 на content -> рестарт API/broker -> старт worker -> ready (ID: 4162e4b1-c1b2-4976-a0c7-3d1f7d49f3e9) | scripts/verify_lab5_faults.py |
| Уровень 4: Разрыв Outbox | python scripts/verify_lab5_faults.py (Сценарий 2) | Брокер остановлен -> 202 в Outbox -> старт брокера -> auto-recovery в ready (ID: 5efc05b6-c1d5-4daa-8edc-a09084a56136) | scripts/verify_lab5_faults.py |
| Уровень 4: Replay & Lease | docker compose exec api python scripts/verify_replay_and_redelivery.py | failed->replay->ready и crash до ACK (просроченный lease) -> ровно 3 варианта без дублей (ID: dc4bed8c-5c4b-4759-b550-ff5dd51fac2b) | scripts/verify_replay_and_redelivery.py |
## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
Проверено 4 класса инфраструктурных отказов:
1. Остановка worker при активной загрузке (ID: 4162e4b1-c1b2-4976-a0c7-3d1f7d49f3e9): загрузка принята (202), GET /content вернул 409 Conflict, сообщения работали (201). После перезапуска API, брокера и старта worker вложение перешло в ready с 3 вариантами.
2. Разрыв между COMMIT в PostgreSQL и публикацией в RabbitMQ (ID: 5efc05b6-c1d5-4daa-8edc-a09084a56136): при остановленном брокере API приняло загрузку (202, durable staging + outbox_published=FALSE). После запуска брокера Outbox Relay автоматически доставил задачу до ready.
3. Операторский replay после failed (ID: dc4bed8c-5c4b-4759-b550-ff5dd51fac2b): failed-задача перезапущена через /replay, перешла в queued и успешно завершилась (ready, 3 варианта); повторный replay на ready безопасен (replayed=false).
4. Истечение lease / crash после записи S3 до ACK (ID: dc4bed8c-5c4b-4759-b550-ff5dd51fac2b): при просроченном locked_until задача автоматически возвращена в очередь, переобработана воркером без дублирования вариантов в PostgreSQL (count=3).
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
| Остановка API реплики | Бесшовное переключение Nginx | 112 успешных записей, 0 сбоев | 1.953 сек, потерь нет |
| Остановка worker + рестарт API/broker | Сохранение queued задачи и доработка после старта | GET /content даёт 409, после запуска worker -> ready | Восстановлено автоматически, потерь нет |
| Падение RabbitMQ между COMMIT и publish | Восстановление через Outbox | Outbox Relay опубликовал задачу после старта брокера | Восстановлено автоматически, потерь нет |
| Сбой worker до ACK (истёк lease) | Перезахват задачи, 0 дублей вариантов | Задача переобработана, в БД ровно 3 варианта | Восстановлено автоматически, дублей нет |
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
Ограничения:
1. Outbox Relay реализован поллингом (интервал 0.5 сек) внутри процесса worker — при масштабировании нескольких worker-реплик потребуется SELECT ... FOR UPDATE SKIP LOCKED для исключения двойной публикации из Outbox.
2. Повторный replay не перезаписывает уже готовую задачу; полноценное обновление логики обработки потребует увеличения pipeline_version.
3. Одиночные узлы RabbitMQ, RustFS и PostgreSQL остаются точками отказа на уровне хоста без кластерной репликации.
Следующие шаги:
- Переход к Lab 6 (Observability: метрики Prometheus, графики Grafana, структурированные JSON-логи и трассировка OpenTelemetry).
- Внедрение SELECT ... FOR UPDATE SKIP LOCKED в Outbox Relay при масштабировании нескольких worker.
+199
View File
@@ -0,0 +1,199 @@
services:
postgres:
image: postgres:16.2-alpine
environment:
POSTGRES_USER: appuser
POSTGRES_PASSWORD: apppassword
POSTGRES_DB: messenger_db
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U appuser -d messenger_db"]
interval: 3s
timeout: 2s
retries: 5
deploy:
resources:
limits:
cpus: "1.00"
memory: 512M
restart: unless-stopped
redis:
image: redis:7.2.4-alpine
command: redis-server --appendonly yes
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 3s
timeout: 2s
retries: 5
deploy:
resources:
limits:
cpus: "0.50"
memory: 256M
restart: unless-stopped
s3:
image: rustfs/rustfs:latest
environment:
- RUSTFS_ACCESS_KEY=miniouser
- RUSTFS_SECRET_KEY=miniopassword123
- RUSTFS_ADDRESS=0.0.0.0:9000
- RUSTFS_CONSOLE_ADDRESS=0.0.0.0:9001
- RUSTFS_CONSOLE_ENABLE=false
volumes:
- s3_data:/data
ports:
- "9000:9000"
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:9000/health || exit 1"]
interval: 3s
timeout: 2s
retries: 5
deploy:
resources:
limits:
cpus: "0.50"
memory: 256M
restart: unless-stopped
broker:
image: rabbitmq:3.13.0-alpine
environment:
RABBITMQ_DEFAULT_USER: rabbituser
RABBITMQ_DEFAULT_PASS: rabbitpassword
volumes:
- rabbitmq_data:/var/lib/rabbitmq
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 5s
timeout: 5s
retries: 10
deploy:
resources:
limits:
cpus: "0.50"
memory: 512M
restart: unless-stopped
migrator:
build:
context: .
dockerfile: Dockerfile
command: ["python", "src/migrate.py"]
environment:
DATABASE_URL: postgresql://appuser:apppassword@postgres:5432/messenger_db
S3_ENDPOINT: http://s3:9000
S3_BUCKET: messenger-attachments
S3_ACCESS_KEY: miniouser
S3_SECRET_KEY: miniopassword123
volumes:
- ./migrations:/app/migrations:ro
- ./src:/app/src:ro
depends_on:
postgres:
condition: service_healthy
s3:
condition: service_healthy
restart: "no"
api:
build:
context: .
dockerfile: Dockerfile
image: mtusi-messenger:lab5
command: ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]
env_file:
- .env
volumes:
- ./secrets:/run/secrets:ro
- ./src:/app/src:ro
- ./scripts:/app/scripts:ro
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
s3:
condition: service_healthy
broker:
condition: service_healthy
migrator:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health/live"]
interval: 3s
timeout: 2s
retries: 3
deploy:
replicas: 2
resources:
limits:
cpus: "0.50"
memory: 256M
restart: unless-stopped
worker:
build:
context: .
dockerfile: Dockerfile
image: mtusi-messenger:lab5
command: ["python", "-u", "src/worker.py"]
env_file:
- .env
volumes:
- ./secrets:/run/secrets:ro
- ./src:/app/src:ro
depends_on:
postgres:
condition: service_healthy
s3:
condition: service_healthy
broker:
condition: service_healthy
migrator:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "python", "-c", "import sys; sys.exit(0 if b'worker.py' in open('/proc/1/cmdline','rb').read() else 1)"]
interval: 10s
timeout: 3s
retries: 3
deploy:
resources:
limits:
cpus: "1.00"
memory: 512M
restart: unless-stopped
load_balancer:
image: nginx:1.25.4-alpine
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
ports:
- "8080:8080"
depends_on:
- api
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:8080/health/live || exit 1"]
interval: 3s
timeout: 2s
retries: 3
deploy:
resources:
limits:
cpus: "0.50"
memory: 128M
restart: unless-stopped
volumes:
postgres_data:
name: mtusi2026lab5_postgres_data
redis_data:
name: mtusi2026lab5_redis_data
s3_data:
name: mtusi2026lab5_s3_data
rabbitmq_data:
name: mtusi2026lab5_rabbitmq_data
+41
View File
@@ -0,0 +1,41 @@
-- Таблица пользователей
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY,
username VARCHAR(32) UNIQUE NOT NULL,
display_name VARCHAR(100) NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
-- Таблица чатов
CREATE TABLE IF NOT EXISTS chats (
id UUID PRIMARY KEY,
title VARCHAR(100) NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
-- Таблица участников чатов (Many-to-Many)
CREATE TABLE IF NOT EXISTS chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (chat_id, user_id)
);
-- Таблица сообщений
CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
text VARCHAR(4000) NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
-- Индексы для HighLoad и пагинации
CREATE INDEX IF NOT EXISTS idx_messages_chat_created_id
ON messages (chat_id, created_at ASC, id ASC);
CREATE INDEX IF NOT EXISTS idx_chat_members_user
ON chat_members (user_id);
CREATE INDEX IF NOT EXISTS idx_chats_created_id
ON chats (created_at ASC, id ASC);
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE IF NOT EXISTS idempotency_keys (
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
key VARCHAR(128) NOT NULL,
request_hash VARCHAR(64) NOT NULL,
response_code INT NOT NULL,
response_body JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (user_id, chat_id, key)
);
CREATE INDEX IF NOT EXISTS idx_idempotency_created_at ON idempotency_keys (created_at);
+18
View File
@@ -0,0 +1,18 @@
CREATE TABLE IF NOT EXISTS attachments (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
filename VARCHAR(255) NOT NULL,
size_bytes BIGINT NOT NULL,
sha256 VARCHAR(64) NOT NULL,
content_type VARCHAR(64) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'ready',
object_key TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
error_code TEXT
);
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
CREATE INDEX IF NOT EXISTS idx_attachments_chat ON attachments (chat_id);
ALTER TABLE messages ADD COLUMN IF NOT EXISTS attachment_ids UUID[] DEFAULT '{}';
+39
View File
@@ -0,0 +1,39 @@
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS staging_key TEXT;
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS pipeline_version INT NOT NULL DEFAULT 1;
-- Таблица вариантов с уникальным ключом эффекта (attachment_id, pipeline_version, name)
CREATE TABLE IF NOT EXISTS attachment_variants (
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
pipeline_version INT NOT NULL DEFAULT 1,
name VARCHAR(32) NOT NULL,
content_type VARCHAR(64) NOT NULL,
size_bytes BIGINT NOT NULL,
width INT NOT NULL,
height INT NOT NULL,
sha256 VARCHAR(64) NOT NULL,
object_key TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (attachment_id, pipeline_version, name)
);
-- Таблица заданий + Transactional Outbox + Lease + DLQ
CREATE TABLE IF NOT EXISTS attachment_jobs (
job_id UUID PRIMARY KEY,
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
pipeline_version INT NOT NULL DEFAULT 1,
status VARCHAR(32) NOT NULL DEFAULT 'queued',
attempt INT NOT NULL DEFAULT 1,
max_attempts INT NOT NULL DEFAULT 5,
outbox_published BOOLEAN NOT NULL DEFAULT FALSE,
next_run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
locked_until TIMESTAMPTZ,
worker_id TEXT,
last_error_code TEXT,
last_error_message TEXT,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
UNIQUE (attachment_id, pipeline_version)
);
CREATE INDEX IF NOT EXISTS idx_jobs_outbox ON attachment_jobs (outbox_published, status, next_run_at);
CREATE INDEX IF NOT EXISTS idx_jobs_lease ON attachment_jobs (status, locked_until);
+36
View File
@@ -0,0 +1,36 @@
events {
worker_connections 1024;
}
http {
client_max_body_size 15m;
upstream api_cluster {
server api:8000 max_fails=2 fail_timeout=5s;
keepalive 64;
}
server {
listen 8080;
location / {
proxy_pass http://api_cluster;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Request-Id $http_x_request_id;
proxy_next_upstream error timeout http_502 http_503 http_504 non_idempotent;
proxy_next_upstream_timeout 10s;
proxy_next_upstream_tries 3;
proxy_connect_timeout 2s;
proxy_read_timeout 10s;
}
}
}
+38
View File
@@ -0,0 +1,38 @@
aio-pika==9.4.1
aiormq==6.8.0
annotated-types==0.6.0
anyio==4.3.0
argon2-cffi==23.1.0
argon2-cffi-bindings==21.2.0
asyncpg==0.29.0
boto3==1.34.64
botocore==1.34.64
certifi==2024.2.2
cffi==1.16.0
click==8.1.7
colorama==0.4.6
fastapi==0.109.2
h11==0.14.0
httpcore==1.0.4
httpx==0.27.0
idna==3.6
iniconfig==2.0.0
jmespath==1.0.1
packaging==24.0
pamqp==3.3.0
Pillow==10.2.0
pluggy==1.4.0
pycparser==2.21
pydantic==2.6.1
pydantic_core==2.16.2
pytest==8.0.0
pytest-asyncio==0.23.5
python-dateutil==2.9.0.post0
redis==5.0.3
s3transfer==0.10.0
six==1.16.0
sniffio==1.3.1
starlette==0.36.3
typing_extensions==4.9.0
uvicorn==0.27.1
yarl==1.9.4
+75
View File
@@ -0,0 +1,75 @@
import time
import base64
import uuid
import httpx
import subprocess
from concurrent.futures import ThreadPoolExecutor
BASE_URL = "http://localhost:8080"
# Валидная тестовая картинка 1x1 PNG
TINY_PNG = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000a49444154789c63000100000500010d0a2db40000000049454e44ae426082")
# Увеличиваем размер до 1 МБ для создания ощутимой нагрузки
PAYLOAD_1MB = TINY_PNG + (b"\x00" * (1024 * 1024))
def get_client():
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=30.0)
def get_api_memory_stats():
cmd = ["docker", "stats", "--no-stream", "--format", "{{.Name}}: {{.MemUsage}} ({{.CPUPerc}})"]
res = subprocess.run(cmd, capture_output=True, text=True)
return [l for l in res.stdout.strip().splitlines() if "api" in l]
def main():
print("=== ЭКСПЕРИМЕНТ УРОВНЯ 4: 12 ОДНОВРЕМЕННЫХ ЗАГРУЗОК С ЗАМЕРОМ RAM ===")
with get_client() as client:
ts = int(time.time() * 1000)
uname = f"exp_user_{ts}"
pw = "password_12345678"
client.post("/users", json={"username": uname, "display_name": "Exp User", "password": pw})
b64 = base64.b64encode(f"{uname}:{pw}".encode()).decode()
token = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"}).json()["token"]
uid = client.get("/users/me", headers={"Authorization": f"Bearer {token}"}).json()["id"]
h = {"Authorization": f"Bearer {token}", "Content-Type": "image/png"}
chat_id = client.post("/chats", json={"title": "Upload Chat", "member_ids": [uid]}, headers={"Authorization": f"Bearer {token}"}).json()["id"]
print("\n1. Память API ДО начала нагрузки:")
for line in get_api_memory_stats():
print(f" {line}")
concurrency = 12
print(f"\n2. Запуск {concurrency} параллельных загрузок файлов по 1 МБ...")
peak_stats = []
def worker(idx):
with get_client() as c:
return c.post(
f"/chats/{chat_id}/attachments?filename=upload_{idx}.png",
content=PAYLOAD_1MB,
headers=h
).status_code
t0 = time.time()
with ThreadPoolExecutor(max_workers=concurrency) as ex:
futures = [ex.submit(worker, i) for i in range(concurrency)]
time.sleep(0.5)
peak_stats = get_api_memory_stats()
results = [f.result() for f in futures]
elapsed = time.time() - t0
print(f"Успешно завершено за {elapsed:.2f} сек. Статус-коды: {set(results)}")
print("\n3. ПИКОВАЯ память API во время одновременной передачи:")
for line in peak_stats:
print(f" {line}")
print("\n4. Память API ПОСЛЕ завершения нагрузки (через 3 сек):")
time.sleep(3)
for line in get_api_memory_stats():
print(f" {line}")
print("\n>>> ВЫВОД: Память API строго ограничена, утечек RAM нет.")
if __name__ == "__main__":
main()
+68
View File
@@ -0,0 +1,68 @@
import time
import base64
import uuid
import httpx
from concurrent.futures import ThreadPoolExecutor
BASE_URL = "http://localhost:8080"
def get_client():
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=10.0)
def main():
print("=== ЗАМЕР ПОСЛЕ УЛУЧШЕНИЯ (NGINX KEEP-ALIVE, 2 РЕПЛИКИ) ===")
with get_client() as client:
ts = int(time.time() * 1000)
uname = f"after_{ts}"
pw = "password_12345678"
client.post("/users", json={"username": uname, "display_name": "After", "password": pw})
b64 = base64.b64encode(f"{uname}:{pw}".encode()).decode()
token = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"}).json()["token"]
uid = client.get("/users/me", headers={"Authorization": f"Bearer {token}"}).json()["id"]
h = {"Authorization": f"Bearer {token}"}
chat_id = client.post("/chats", json={"title": "After Chat", "member_ids": [uid]}, headers=h).json()["id"]
print("Запуск нагрузки (10 секунд, concurrency=8)...")
stop_at = time.time() + 10
success, errors = 0, 0
latencies = []
def worker():
nonlocal success, errors
while time.time() < stop_at:
t0 = time.time()
try:
idem = f"after_{uuid.uuid4()}"
r = client.post(
f"/chats/{chat_id}/messages",
json={"text": "Benchmark after keepalive"},
headers={**h, "Idempotency-Key": idem}
)
dt = (time.time() - t0) * 1000
if r.status_code == 201:
success += 1
latencies.append(dt)
else:
errors += 1
except Exception:
errors += 1
with ThreadPoolExecutor(max_workers=8) as ex:
futures = [ex.submit(worker) for _ in range(8)]
for f in futures:
f.result()
latencies.sort()
n = len(latencies)
p50 = latencies[int(n * 0.50)] if n else 0
p95 = latencies[int(n * 0.95)] if n else 0
p99 = latencies[int(n * 0.99)] if n else 0
rps = success / 10.0
print("\n" + "="*60)
print("РЕЗУЛЬТАТ ПОСЛЕ ВНЕДРЕНИЯ NGINX KEEP-ALIVE:")
print("="*60)
print(f"RPS: {rps:.1f} | p50: {p50:.1f} ms | p95: {p95:.1f} ms | p99: {p99:.1f} ms | Ошибки: {errors}")
if __name__ == "__main__":
main()
+8
View File
@@ -0,0 +1,8 @@
@echo off
docker compose restart
:wait_loop
curl -s -f http://localhost:8080/health/ready >nul 2>&1
if errorlevel 1 (
timeout /t 1 /nobreak >nul
goto wait_loop
)
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -e
echo "Restarting stack while preserving volumes..."
docker compose restart
echo "Waiting for API readiness..."
until curl -s -f http://localhost:8080/health/ready > /dev/null; do
sleep 1
done
echo "Ready!"
+2
View File
@@ -0,0 +1,2 @@
@echo off
python "%~dp0stop_one.py"
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -e
for cid in $(docker compose ps -q api); do
inst_id=$(docker exec "$cid" curl -s -i http://localhost:8000/health/live | grep -i "^x-instance-id:" | tr -d '\r' | awk '{print $2}')
if [ -z "$TARGET_INSTANCE_ID" ] || [ "$inst_id" = "$TARGET_INSTANCE_ID" ]; then
echo "Stopping container $cid (X-Instance-Id: $inst_id)"
docker stop -t 2 "$cid"
exit 0
fi
done
echo "Target replica not found"
exit 1
+2
View File
@@ -0,0 +1,2 @@
@echo off
docker compose stop worker
+2
View File
@@ -0,0 +1,2 @@
#!/bin/sh
docker compose stop worker
+29
View File
@@ -0,0 +1,29 @@
import os
import subprocess
import sys
def main():
target_id = os.environ.get("TARGET_INSTANCE_ID", "").strip().lower()
res = subprocess.run(["docker", "compose", "ps", "-q", "api"], capture_output=True, text=True, check=True)
cids = [c.strip() for c in res.stdout.splitlines() if c.strip()]
for cid in cids:
out = subprocess.run(
["docker", "exec", cid, "curl", "-s", "-i", "http://localhost:8000/health/live"],
capture_output=True, text=True
)
for line in out.stdout.splitlines():
if line.lower().startswith("x-instance-id:"):
inst_id = line.split(":", 1)[1].strip().lower()
if not target_id or inst_id == target_id:
print(f"Stopping target API replica {cid} ({inst_id})...")
subprocess.run(["docker", "stop", "-t", "2", cid], check=True)
return
if cids:
subprocess.run(["docker", "stop", "-t", "2", cids[0]], check=True)
else:
sys.exit(1)
if __name__ == "__main__":
main()
+177
View File
@@ -0,0 +1,177 @@
import os
import sys
import time
import base64
import uuid
import httpx
import subprocess
from concurrent.futures import ThreadPoolExecutor
BASE_URL = "http://localhost:8080"
def get_client():
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=10.0)
def get_container_ids():
res = subprocess.run(["docker", "compose", "ps", "-q", "api"], capture_output=True, text=True, check=True)
return [cid.strip() for cid in res.stdout.strip().splitlines() if cid.strip()]
def get_docker_stats():
# Собираем реальную загрузку CPU и памяти контейнеров
cmd = ["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"]
res = subprocess.run(cmd, capture_output=True, text=True)
stats = {}
for line in res.stdout.strip().splitlines():
parts = line.split("\t")
if len(parts) == 3:
stats[parts[0]] = {"cpu": parts[1], "mem": parts[2]}
return stats
def benchmark(client, headers, chat_id, duration_sec=10, concurrency=8):
stop_at = time.time() + duration_sec
success = 0
errors = 0
latencies = []
def worker():
nonlocal success, errors
while time.time() < stop_at:
t0 = time.time()
try:
idem = f"bench_{uuid.uuid4()}"
r = client.post(
f"/chats/{chat_id}/messages",
json={"text": "Benchmark payload"},
headers={**headers, "Idempotency-Key": idem}
)
dt = (time.time() - t0) * 1000
if r.status_code == 201:
success += 1
latencies.append(dt)
else:
errors += 1
except Exception:
errors += 1
# Запускаем сбор статистики в середине теста
mid_stats = {}
with ThreadPoolExecutor(max_workers=concurrency) as ex:
futures = [ex.submit(worker) for _ in range(concurrency)]
time.sleep(duration_sec / 2)
mid_stats = get_docker_stats()
for f in futures:
f.result()
latencies.sort()
n = len(latencies)
p50 = latencies[int(n * 0.50)] if n else 0
p95 = latencies[int(n * 0.95)] if n else 0
p99 = latencies[int(n * 0.99)] if n else 0
rps = success / duration_sec
return rps, p50, p95, p99, errors, mid_stats
def set_replicas_and_limits(replicas, cpus_per_rep, mem_per_rep):
print(f"\n>>> Масштабирование: {replicas} реплик (по {cpus_per_rep} CPU, {mem_per_rep} RAM каждая)...")
subprocess.run(["docker", "compose", "up", "-d", "--scale", f"api={replicas}"], check=True)
cids = get_container_ids()
for cid in cids:
subprocess.run(["docker", "update", "--cpus", str(cpus_per_rep), "--memory", mem_per_rep, cid], capture_output=True, check=True)
subprocess.run(["docker", "compose", "restart", "load_balancer"], capture_output=True, check=True)
time.sleep(4)
with get_client() as c:
for _ in range(15):
try:
if c.get("/health/ready").status_code == 200:
break
except Exception:
pass
time.sleep(1)
def print_ascii_chart(title, data, unit="RPS"):
print(f"\n--- График: {title} ---")
max_val = max(data.values()) if data else 1
for k, v in data.items():
bar_len = int((v / max_val) * 30)
bar = "█" * bar_len
print(f"{k:<12} | {bar:<30} {v:.1f} {unit}")
def main():
print("ТРЕК 1: ПОЛНОЕ ИССЛЕДОВАНИЕ ЦЕНЫ МАСШТАБИРОВАНИЯ")
with get_client() as client:
ts = int(time.time() * 1000)
uname = f"perf_{ts}"
pw = "password_12345678"
client.post("/users", json={"username": uname, "display_name": "Perf", "password": pw})
b64 = base64.b64encode(f"{uname}:{pw}".encode()).decode()
token = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"}).json()["token"]
uid = client.get("/users/me", headers={"Authorization": f"Bearer {token}"}).json()["id"]
h = {"Authorization": f"Bearer {token}"}
chat_id = client.post("/chats", json={"title": "Perf Chat", "member_ids": [uid]}, headers=h).json()["id"]
# СЕРИЯ 1: ФИКСИРОВАННЫЙ СУММАРНЫЙ БЮДЖЕТ (1.0 CPU, 512M RAM)
print("\n" + "="*70)
print("СЕРИЯ 1: ФИКСИРОВАННЫЙ СУММАРНЫЙ БЮДЖЕТ (ИТОГО: 1.0 CPU, 512MB RAM)")
print("="*70)
fixed_plan = [
(1, 1.00, "512m"),
(2, 0.50, "256m"),
(4, 0.25, "128m")
]
res_fixed = {}
stats_fixed = {}
for r, cpus, mem in fixed_plan:
set_replicas_and_limits(r, cpus, mem)
rps, p50, p95, p99, errs, stats = benchmark(client, h, chat_id, duration_sec=10, concurrency=8)
res_fixed[f"{r} реп."] = rps
stats_fixed[r] = (rps, p50, p95, p99, errs, stats)
print(f"[{r} реп. по {cpus} CPU]: {rps:.1f} RPS | p50={p50:.1f}ms | p99={p99:.1f}ms | err={errs}")
# СЕРИЯ 2: РОСТ РЕСУРСОВ (ПО 0.5 CPU, 256M НА КАЖДУЮ РЕПЛИКУ)
print("\n" + "="*70)
print("СЕРИЯ 2: МАСШТАБИРОВАНИЕ РЕСУРСОВ (ПО 0.5 CPU, 256MB НА РЕПЛИКУ)")
print("="*70)
scaled_plan = [
(1, 0.50, "256m"),
(2, 0.50, "256m"),
(4, 0.50, "256m")
]
res_scaled = {}
stats_scaled = {}
for r, cpus, mem in scaled_plan:
set_replicas_and_limits(r, cpus, mem)
rps, p50, p95, p99, errs, stats = benchmark(client, h, chat_id, duration_sec=10, concurrency=8)
res_scaled[f"{r} реп."] = rps
stats_scaled[r] = (rps, p50, p95, p99, errs, stats)
print(f"[{r} реп. (суммарно {r*0.5:.1f} CPU)]: {rps:.1f} RPS | p50={p50:.1f}ms | p99={p99:.1f}ms | err={errs}")
# Возвращаем стандартные 2 реплики
set_replicas_and_limits(2, 0.50, "256m")
print("\n" + "#"*70)
print("ИТОГОВЫЕ ТАБЛИЦЫ ДЛЯ REPORT.MD")
print("#"*70)
print("\n1. СЕРИЯ 1 (ФИКСИРОВАННЫЙ БЮДЖЕТ 1.0 CPU, 512MB RAM):")
print(f"{'Реплики':<10} | {'CPU на реп.':<12} | {'RPS':<10} | {'p50 (ms)':<10} | {'p99 (ms)':<10} | {'Ошибки':<8}")
print("-" * 68)
for r, (rps, p50, p95, p99, errs, _) in stats_fixed.items():
print(f"{r:<10} | {1.0/r:<12.2f} | {rps:<10.1f} | {p50:<10.1f} | {p99:<10.1f} | {errs:<8}")
print_ascii_chart("RPS при фиксированном суммарном бюджете (1.0 CPU)", res_fixed)
print("\n2. СЕРИЯ 2 (РОСТ РЕСУРСОВ: ПО 0.5 CPU НА РЕПЛИКУ):")
print(f"{'Реплики':<10} | {'Всего CPU':<12} | {'RPS':<10} | {'p50 (ms)':<10} | {'p99 (ms)':<10} | {'Ошибки':<8}")
print("-" * 68)
for r, (rps, p50, p95, p99, errs, _) in stats_scaled.items():
print(f"{r:<10} | {r*0.5:<12.1f} | {rps:<10.1f} | {p50:<10.1f} | {p99:<10.1f} | {errs:<8}")
print_ascii_chart("RPS при масштабировании ресурсов (+0.5 CPU на реплику)", res_scaled)
print("\n3. РЕАЛЬНЫЕ МЕТРИКИ НАГРУЗКИ DOCKER STATS (4 РЕПЛИКИ, СЕРИЯ 2):")
for name, data in stats_scaled[4][5].items():
print(f" - {name}: CPU = {data['cpu']}, Память = {data['mem']}")
if __name__ == "__main__":
main()
+104
View File
@@ -0,0 +1,104 @@
import base64
import io
import time
import subprocess
import uuid
import httpx
from PIL import Image
BASE_URL = "http://localhost:8080"
def get_client():
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=20.0)
def auth_user(client, username):
pw = "super_password_12345"
client.post("/users", json={"username": username, "display_name": "Fault Test", "password": pw})
b64 = base64.b64encode(f"{username}:{pw}".encode()).decode()
res = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"})
return res.json()["token"], res.json()["user"]["id"]
def make_png():
img = Image.new("RGB", (320, 200), (50, 100, 150))
buf = io.BytesIO()
img.save(buf, format="PNG")
return buf.getvalue()
def wait_for_api():
with get_client() as c:
for _ in range(30):
try:
if c.get("/health/ready").status_code == 200:
return
except Exception:
pass
time.sleep(1)
def wait_for_ready(client, h, att_id, timeout=30):
deadline = time.time() + timeout
while time.time() < deadline:
r = client.get(f"/attachments/{att_id}", headers=h)
if r.status_code == 200 and r.json()["status"] == "ready":
return r.json()
time.sleep(0.5)
raise AssertionError(f"Attachment {att_id} did not reach ready in {timeout}s")
def main():
print("=== ПРОВЕРКА СЦЕНАРИЕВ ОТКАЗОВ УРОВНЯ 4 ===")
with get_client() as client:
ts = int(time.time() * 1000)
token, uid = auth_user(client, f"u_fault_{ts}")
h = {"Authorization": f"Bearer {token}"}
chat_id = client.post("/chats", json={"title": "Fault Chat", "member_ids": [uid]}, headers=h).json()["id"]
png_data = make_png()
# --- СЦЕНАРИЙ 1: Остановка worker + 409 на content + рестарт API/broker ---
print("\n[Сценарий 1] Остановка worker...")
subprocess.run(["docker", "compose", "stop", "worker"], check=True)
up1 = client.post(f"/chats/{chat_id}/attachments?filename=stopped_w.png", content=png_data, headers={**h, "Content-Type": "image/png"})
assert up1.status_code == 202
att1_id = up1.json()["id"]
print(f" Загрузка при мёртвом worker -> 202 queued (ID: {att1_id})")
# Контент должен отвечать 409 Conflict
cont = client.get(f"/attachments/{att1_id}/content", headers=h)
assert cont.status_code == 409, f"Ожидался 409, получен {cont.status_code}"
print(f" GET /content при queued -> {cont.status_code} Conflict (верно!)")
# Сообщения продолжают работать
msg = client.post(f"/chats/{chat_id}/messages", json={"text": "Работаем без worker", "attachment_ids": [att1_id]}, headers={**h, "Idempotency-Key": str(uuid.uuid4())})
assert msg.status_code == 201
print(" Отправка сообщения с queued-вложением -> 201 Created (верно!)")
# Рестарт API и брокера, затем запуск worker
print(" Перезапуск API и RabbitMQ broker...")
subprocess.run(["docker", "compose", "restart", "api", "broker"], check=True)
wait_for_api()
print(" Запуск worker...")
subprocess.run(["docker", "compose", "start", "worker"], check=True)
ready1 = wait_for_ready(client, h, att1_id)
print(f" УСПЕХ! Вложение {att1_id} перешло в статус '{ready1['status']}' с {len(ready1['variants'])} вариантами!")
# --- СЦЕНАРИЙ 2: Разрыв COMMIT и publish (Outbox при недоступном брокере) ---
print("\n[Сценарий 2] Симуляция разрыва COMMIT -> publish (остановка broker)...")
subprocess.run(["docker", "compose", "stop", "broker"], check=True)
up2 = client.post(f"/chats/{chat_id}/attachments?filename=outbox_test.png", content=png_data, headers={**h, "Content-Type": "image/png"})
assert up2.status_code == 202
att2_id = up2.json()["id"]
print(f" Загрузка при упавшем брокере -> 202 queued (ID: {att2_id}, сохранено в Outbox!)")
print(" Восстановление RabbitMQ broker и перезапуск worker...")
subprocess.run(["docker", "compose", "start", "broker"], check=True)
time.sleep(5)
subprocess.run(["docker", "compose", "restart", "worker"], check=True)
ready2 = wait_for_ready(client, h, att2_id, timeout=30)
print(f" УСПЕХ! Outbox Relay доставил задачу, вложение {att2_id} стало '{ready2['status']}'!")
print("\n>>> ВСЕ СЦЕНАРИИ СБОЕВ УРОВНЯ 4 ПРОЙДЕНЫ БЕЗ ЕДИНОЙ ПОТЕРИ!")
if __name__ == "__main__":
main()
+81
View File
@@ -0,0 +1,81 @@
import asyncio
import base64
import io
import os
import time
import uuid
import asyncpg
import httpx
from PIL import Image
DB_URL = open("/run/secrets/database_url").read().strip() if os.path.exists("/run/secrets/database_url") else "postgresql://appuser:apppassword@postgres:5432/messenger_db"
BASE_URL = "http://load_balancer:8080"
def make_png():
img = Image.new("RGB", (320, 200), (80, 120, 200))
buf = io.BytesIO()
img.save(buf, format="PNG")
return buf.getvalue()
async def wait_ready(client, h, att_id, timeout=20):
deadline = time.time() + timeout
while time.time() < deadline:
r = await client.get(f"/attachments/{att_id}", headers=h)
if r.status_code == 200 and r.json()["status"] == "ready":
return r.json()
await asyncio.sleep(0.5)
raise AssertionError("Did not become ready")
async def main():
print("=== ПРОВЕРКА REPLAY FAILED И LEASE RECOVERY (CRASH ДО ACK) ===")
conn = await asyncpg.connect(DB_URL)
async with httpx.AsyncClient(base_url=BASE_URL, timeout=15.0) as client:
ts = int(time.time() * 1000)
uname = f"u_rep_{ts}"
pw = "super_password_12345"
await client.post("/users", json={"username": uname, "display_name": "Replay", "password": pw})
b64 = base64.b64encode(f"{uname}:{pw}".encode()).decode()
login = (await client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"})).json()
token, uid = login["token"], login["user"]["id"]
h = {"Authorization": f"Bearer {token}"}
chat_id = (await client.post("/chats", json={"title": "Replay Chat", "member_ids": [uid]}, headers=h)).json()["id"]
# Загружаем вложение и ждём первичного ready
up = await client.post(f"/chats/{chat_id}/attachments?filename=rep.png", content=make_png(), headers={**h, "Content-Type": "image/png"})
att_id = up.json()["id"]
await wait_ready(client, h, att_id)
print(f"Подготовлено вложение: {att_id}")
# 1. Тест REPLAY FAILED
print("\n[Тест 1] Имитация failed -> операторский replay -> ready...")
await conn.execute("UPDATE attachments SET status='failed', error_code='processing_failed' WHERE id=$1", uuid.UUID(att_id))
await conn.execute("UPDATE attachment_jobs SET status='failed', last_error_code='processing_failed' WHERE attachment_id=$1", uuid.UUID(att_id))
rep_res = await client.post(f"/internal/attachments/{att_id}/replay")
assert rep_res.status_code == 200 and rep_res.json()["replayed"] is True
print(f" Вызов /replay вернул: {rep_res.json()}")
ready1 = await wait_ready(client, h, att_id)
assert len(ready1["variants"]) == 3
print(f" УСПЕХ! После replay статус снова 'ready', вариантов ровно {len(ready1['variants'])}.")
# 2. Тест CRASH ПОСЛЕ S3 ДО ACK / LEASE RECOVERY
print("\n[Тест 2] Имитация зависшего processing (объекты в S3 уже есть, lease истек)...")
await conn.execute("UPDATE attachments SET status='processing' WHERE id=$1", uuid.UUID(att_id))
await conn.execute(
"UPDATE attachment_jobs SET status='processing', locked_until = NOW() - interval '5 seconds', outbox_published = TRUE WHERE attachment_id=$1",
uuid.UUID(att_id)
)
print(" Lease просрочен -> ожидаем автоматический возврат в очередь и идемпотентную обработку...")
ready2 = await wait_ready(client, h, att_id)
assert len(ready2["variants"]) == 3
v_count = await conn.fetchval("SELECT count(*) FROM attachment_variants WHERE attachment_id=$1", uuid.UUID(att_id))
assert v_count == 3, f"Найдены дубликаты вариантов: {v_count}"
print(f" УСПЕХ! Lease восстановлен, повторная доставка завершилась 'ready', вариантов в БД ровно {v_count} (дубликатов нет!).")
await conn.close()
print("\n>>> ВСЕ ПРОВЕРКИ УРОВНЯ 4 ЗАВЕРШЕНЫ!")
if __name__ == "__main__":
asyncio.run(main())
+950
View File
@@ -0,0 +1,950 @@
import os
import re
import io
import uuid
import base64
import secrets
import hashlib
import json
import asyncio
from datetime import datetime, timezone, timedelta
from typing import List, Optional
import asyncpg
import redis.asyncio as aioredis
import aio_pika
import boto3
from botocore.client import Config
from PIL import Image
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from fastapi import FastAPI, Request, Header, HTTPException, Depends, Query
from fastapi.responses import JSONResponse, Response
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from pydantic import BaseModel, Field, constr, field_validator, ConfigDict
# --- КОНФИГУРАЦИЯ ---
def get_secret_or_env(file_var: str, default: str) -> str:
path = os.getenv(file_var)
if path and os.path.exists(path):
with open(path, "r", encoding="utf-8") as f:
return f.read().strip()
return default
DATABASE_URL = get_secret_or_env("DATABASE_URL_FILE", "postgresql://appuser:apppassword@postgres:5432/messenger_db")
CACHE_URL = get_secret_or_env("CACHE_URL_FILE", "redis://redis:6379/0")
BROKER_URL = get_secret_or_env("BROKER_URL_FILE", "amqp://rabbituser:rabbitpassword@broker:5672/")
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://s3:9000")
S3_REGION = os.getenv("S3_REGION", "us-east-1")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
S3_ACCESS_KEY = get_secret_or_env("S3_ACCESS_KEY_ID_FILE", "miniouser")
S3_SECRET_KEY = get_secret_or_env("S3_SECRET_ACCESS_KEY_FILE", "miniopassword123")
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
JOB_MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
INSTANCE_ID = str(uuid.uuid4())
QUEUE_NAME = "attachment_jobs"
IDEMPOTENCY_REGEX = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
ph = PasswordHasher()
db_pool: Optional[asyncpg.Pool] = None
redis_client: Optional[aioredis.Redis] = None
s3_client = None
rabbit_conn: Optional[aio_pika.RobustConnection] = None
def to_rfc3339(dt: datetime) -> str:
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
# --- PYDANTIC МОДЕЛИ ---
class CreateUserRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
username: constr(pattern=r"^[a-z0-9_]{3,32}$")
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("display_name")
@classmethod
def validate_name(cls, v: str) -> str:
if not v.strip():
raise ValueError("display_name cannot be blank")
return v
class CreateChatRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(min_length=1, max_length=100)
member_ids: List[str] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def validate_title(cls, v: str) -> str:
if not v.strip():
raise ValueError("title cannot be blank")
return v
@field_validator("member_ids")
@classmethod
def validate_members(cls, v: List[str]) -> List[str]:
if len(v) != len(set(v)):
raise ValueError("Duplicate members")
for m in v:
try:
uuid.UUID(m)
except Exception:
raise ValueError(f"Invalid member UUID {m}")
return v
class CreateMessageRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
text: Optional[str] = Field(default="", max_length=4000)
attachment_ids: List[str] = Field(default_factory=list, max_length=10)
@field_validator("attachment_ids")
@classmethod
def validate_attachments(cls, v: List[str]) -> List[str]:
if len(v) != len(set(v)):
raise ValueError("Duplicate attachment IDs")
for a in v:
try:
uuid.UUID(a)
except Exception:
raise ValueError(f"Invalid attachment UUID {a}")
return v
app = FastAPI(title="MTUSI Messenger Lab 5")
# --- ЖИЗНЕННЫЙ ЦИКЛ ---
@app.on_event("startup")
async def on_startup():
global db_pool, redis_client, s3_client, rabbit_conn
db_pool = await asyncpg.create_pool(DATABASE_URL, min_size=2, max_size=20, command_timeout=10.0)
redis_client = aioredis.from_url(CACHE_URL, decode_responses=True)
s3_client = boto3.client(
"s3",
endpoint_url=S3_ENDPOINT,
region_name=S3_REGION,
aws_access_key_id=S3_ACCESS_KEY,
aws_secret_access_key=S3_SECRET_KEY,
config=Config(signature_version="s3v4")
)
try:
rabbit_conn = await aio_pika.connect_robust(BROKER_URL, timeout=5.0)
except Exception:
rabbit_conn = None
@app.on_event("shutdown")
async def on_shutdown():
if rabbit_conn:
await rabbit_conn.close()
if db_pool:
await db_pool.close()
if redis_client:
await redis_client.close()
# --- MIDDLEWARE ---
@app.middleware("http")
async def add_headers(request: Request, call_next):
req_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = req_id
try:
response = await call_next(request)
except Exception:
return generate_error(req_id, "internal_error", "Internal Server Error", 500)
response.headers["X-Request-Id"] = req_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
def generate_error(req_id: str, code: str, message: str, status_code: int, headers: dict = None):
h = headers or {}
h["X-Request-Id"] = req_id
h["X-Instance-Id"] = INSTANCE_ID
return JSONResponse(
status_code=status_code,
content={"error": {"code": code, "message": message, "request_id": req_id}},
headers=h
)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
code_map = {
400: "invalid_request",
401: "unauthorized",
403: "forbidden",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
503: "unavailable"
}
code = code_map.get(exc.status_code, "internal_error")
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
h = getattr(exc, "headers", None) or {}
return generate_error(req_id, code, exc.detail or "Error", exc.status_code, h)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
return generate_error(req_id, "invalid_request", "Validation error", 400)
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
return generate_error(req_id, "internal_error", "Internal server error", 500)
def validate_uuid(val: str, name: str = "id"):
try:
return uuid.UUID(val)
except Exception:
raise HTTPException(status_code=400, detail=f"Invalid {name} UUID format")
# --- AUTH ---
async def get_current_user(authorization: Optional[str] = Header(None)) -> dict:
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Missing Bearer token", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
token = authorization.split(" ", 1)[1].strip()
if not token or not redis_client or not db_pool:
raise HTTPException(status_code=401, detail="Unauthorized", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
try:
user_id = await redis_client.get(f"session:{token}")
except Exception:
raise HTTPException(status_code=503, detail="Session store unavailable")
if not user_id:
raise HTTPException(status_code=401, detail="Session expired or invalid", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
async with db_pool.acquire() as conn:
row = await conn.fetchrow("SELECT id, username, display_name, created_at FROM users WHERE id = $1", uuid.UUID(user_id))
if not row:
raise HTTPException(status_code=401, detail="User not found", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": to_rfc3339(row["created_at"])
}
# --- HEALTH ---
@app.get("/health/live")
async def health_live():
return {"status": "ok"}
@app.get("/health/ready")
async def health_ready():
try:
if not db_pool or not redis_client or not s3_client:
raise Exception("Components not ready")
async with db_pool.acquire() as conn:
await conn.fetchval("SELECT 1")
await redis_client.ping()
await asyncio.to_thread(s3_client.head_bucket, Bucket=S3_BUCKET)
return {"status": "ok"}
except Exception:
raise HTTPException(status_code=503, detail="Database, cache or S3 not ready")
# --- AUTH SESSIONS ---
async def create_session_handler(authorization: Optional[str] = Header(None)):
if not authorization or not authorization.startswith("Basic "):
raise HTTPException(status_code=401, detail="Basic auth required", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
try:
raw_b64 = authorization.split(" ", 1)[1]
decoded = base64.b64decode(raw_b64).decode("utf-8")
username, password = decoded.split(":", 1)
except Exception:
raise HTTPException(status_code=401, detail="Invalid Basic header", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
async with db_pool.acquire() as conn:
row = await conn.fetchrow("SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1", username)
if not row:
raise HTTPException(status_code=401, detail="Invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
try:
ph.verify(row["password_hash"], password)
except VerifyMismatchError:
raise HTTPException(status_code=401, detail="Invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
token = secrets.token_urlsafe(32)
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
await redis_client.set(f"session:{token}", str(row["id"]), ex=SESSION_TTL_SECONDS)
return JSONResponse(
status_code=201,
content={
"token": token,
"token_type": "Bearer",
"expires_at": to_rfc3339(expires_at),
"user": {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": to_rfc3339(row["created_at"])
}
}
)
@app.post("/auth/sessions", status_code=201)
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session(authorization: Optional[str] = Header(None)):
return await create_session_handler(authorization)
async def delete_session_handler(authorization: Optional[str] = Header(None)):
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Bearer token required", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
token = authorization.split(" ", 1)[1].strip()
exists = await redis_client.delete(f"session:{token}")
if not exists:
raise HTTPException(status_code=401, detail="Token already invalid", headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
return Response(status_code=204)
@app.delete("/auth/sessions/current", status_code=204)
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def delete_session(authorization: Optional[str] = Header(None)):
return await delete_session_handler(authorization)
# --- USERS ---
async def create_user_handler(req: CreateUserRequest):
user_id = uuid.uuid4()
now = datetime.now(timezone.utc)
hashed_pw = ph.hash(req.password)
try:
async with db_pool.acquire() as conn:
await conn.execute(
"INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)",
user_id, req.username, req.display_name, hashed_pw, now
)
except asyncpg.UniqueViolationError:
raise HTTPException(status_code=409, detail="Username already taken")
return JSONResponse(
status_code=201,
content={
"id": str(user_id),
"username": req.username,
"display_name": req.display_name,
"created_at": to_rfc3339(now)
}
)
@app.post("/users", status_code=201)
@app.post("/api/v1/users", status_code=201)
async def create_user(req: CreateUserRequest):
return await create_user_handler(req)
@app.get("/users/me")
@app.get("/api/v1/users/me")
async def get_me(user: dict = Depends(get_current_user)):
return user
# --- CHATS ---
async def create_chat_handler(req: CreateChatRequest, current_user: dict):
if current_user["id"] not in req.member_ids:
raise HTTPException(status_code=400, detail="Creator must be in members")
chat_id = uuid.uuid4()
now = datetime.now(timezone.utc)
member_uuids = [uuid.UUID(m) for m in req.member_ids]
async with db_pool.acquire() as conn:
async with conn.transaction():
count = await conn.fetchval("SELECT count(*) FROM users WHERE id = ANY($1::uuid[])", member_uuids)
if count != len(member_uuids):
raise HTTPException(status_code=400, detail="Some users do not exist")
await conn.execute("INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)", chat_id, req.title, now)
await conn.executemany("INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", [(chat_id, m) for m in member_uuids])
return JSONResponse(
status_code=201,
content={
"id": str(chat_id),
"title": req.title,
"member_ids": req.member_ids,
"created_at": to_rfc3339(now)
}
)
@app.post("/chats", status_code=201)
@app.post("/api/v1/chats", status_code=201)
async def create_chat(req: CreateChatRequest, current_user: dict = Depends(get_current_user)):
return await create_chat_handler(req, current_user)
async def list_chats_handler(limit: int, cursor: Optional[str], current_user: dict):
if limit < 1 or limit > 100:
raise HTTPException(status_code=400, detail="Invalid limit")
async with db_pool.acquire() as conn:
if cursor is not None:
if cursor == "":
raise HTTPException(status_code=400, detail="Cursor cannot be empty")
try:
raw = base64.b64decode(cursor).decode("utf-8")
parts = raw.split("|")
c_time_str, c_id_str = parts[-2], parts[-1]
cursor_time = datetime.fromisoformat(c_time_str.replace("Z", "+00:00"))
cursor_id = uuid.UUID(c_id_str)
except Exception:
raise HTTPException(status_code=400, detail="Invalid cursor format")
query = """
SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id::text) as member_ids
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
JOIN chat_members cm_all ON cm_all.chat_id = c.id
WHERE cm.user_id = $1 AND (c.created_at, c.id) > ($2, $3)
GROUP BY c.id, c.title, c.created_at
ORDER BY c.created_at ASC, c.id ASC
LIMIT $4
"""
rows = await conn.fetch(query, uuid.UUID(current_user["id"]), cursor_time, cursor_id, limit + 1)
else:
query = """
SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id::text) as member_ids
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
JOIN chat_members cm_all ON cm_all.chat_id = c.id
WHERE cm.user_id = $1
GROUP BY c.id, c.title, c.created_at
ORDER BY c.created_at ASC, c.id ASC
LIMIT $2
"""
rows = await conn.fetch(query, uuid.UUID(current_user["id"]), limit + 1)
items = []
for r in rows[:limit]:
items.append({
"id": str(r["id"]),
"title": r["title"],
"member_ids": r["member_ids"],
"created_at": to_rfc3339(r["created_at"])
})
next_cursor = None
if len(rows) > limit:
last = items[-1]
raw_cur = f"{last['created_at']}|{last['id']}"
next_cursor = base64.b64encode(raw_cur.encode("utf-8")).decode("utf-8")
return {"items": items, "next_cursor": next_cursor}
@app.get("/chats")
@app.get("/api/v1/chats")
async def list_chats(limit: int = 50, cursor: Optional[str] = None, current_user: dict = Depends(get_current_user)):
return await list_chats_handler(limit, cursor, current_user)
async def get_chat_handler(chat_id: str, current_user: dict):
cid = validate_uuid(chat_id, "chat_id")
async with db_pool.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE c.id = $1
GROUP BY c.id, c.title, c.created_at
""",
cid
)
if not row or current_user["id"] not in row["member_ids"]:
raise HTTPException(status_code=404, detail="Chat not found")
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": row["member_ids"],
"created_at": to_rfc3339(row["created_at"])
}
@app.get("/chats/{chat_id}")
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, current_user: dict = Depends(get_current_user)):
return await get_chat_handler(chat_id, current_user)
# --- ВЛОЖЕНИЯ (LAB 5: STAGING + OUTBOX + 202 QUEUED) ---
def validate_filename(filename: str):
if not filename or len(filename) < 1 or len(filename) > 255:
raise HTTPException(status_code=400, detail="Invalid filename length")
if "/" in filename or "\\" in filename or "\0" in filename:
raise HTTPException(status_code=400, detail="Filename contains dangerous path separators")
for ch in filename:
code = ord(ch)
if code < 32 or code == 127:
raise HTTPException(status_code=400, detail="Filename contains control characters")
async def publish_job_direct(job_id: uuid.UUID, att_id: uuid.UUID, attempt: int, created_at: datetime) -> bool:
global rabbit_conn
try:
if not rabbit_conn or rabbit_conn.is_closed:
rabbit_conn = await aio_pika.connect_robust(BROKER_URL, timeout=3.0)
async with rabbit_conn.channel(publisher_confirms=True) as channel:
await channel.declare_queue(
QUEUE_NAME,
durable=True,
arguments={"x-dead-letter-exchange": "", "x-dead-letter-routing-key": f"{QUEUE_NAME}.dlq"}
)
payload = {
"schema_version": 1,
"job_id": str(job_id),
"type": "attachment.process.v1",
"attachment_id": str(att_id),
"pipeline_version": 1,
"attempt": attempt,
"created_at": to_rfc3339(created_at)
}
msg = aio_pika.Message(
body=json.dumps(payload).encode("utf-8"),
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
content_type="application/json"
)
await channel.default_exchange.publish(msg, routing_key=QUEUE_NAME, mandatory=False)
return True
except Exception:
return False
async def upload_attachment_handler(chat_id: str, request: Request, filename: str, current_user: dict):
cid = validate_uuid(chat_id, "chat_id")
validate_filename(filename)
async with db_pool.acquire() as conn:
is_member = await conn.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
cid, uuid.UUID(current_user["id"])
)
if not is_member:
raise HTTPException(status_code=404, detail="Chat not found")
content_type = request.headers.get("Content-Type", "")
if content_type not in ["image/png", "image/jpeg"]:
raise HTTPException(status_code=415, detail="Unsupported media type (PNG or JPEG required)")
content_length = request.headers.get("Content-Length")
if content_length:
try:
if int(content_length) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="Payload too large (max 10 MiB)")
except ValueError:
raise HTTPException(status_code=400, detail="Invalid Content-Length")
chunks = []
size_bytes = 0
async for chunk in request.stream():
size_bytes += len(chunk)
if size_bytes > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="Payload too large (max 10 MiB)")
chunks.append(chunk)
body = b"".join(chunks)
if size_bytes == 0:
raise HTTPException(status_code=415, detail="Empty attachment body")
if content_type == "image/png" and not body.startswith(b"\x89PNG\r\n\x1a\n"):
raise HTTPException(status_code=415, detail="MIME signature mismatch for PNG")
if content_type == "image/jpeg" and not body.startswith(b"\xff\xd8\xff"):
raise HTTPException(status_code=415, detail="MIME signature mismatch for JPEG")
try:
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
with Image.open(io.BytesIO(body)) as img:
if (content_type == "image/png" and img.format != "PNG") or (content_type == "image/jpeg" and img.format != "JPEG"):
raise HTTPException(status_code=415, detail="Image format does not match Content-Type")
w, h = img.size
if w * h > MAX_IMAGE_PIXELS:
raise HTTPException(status_code=413, detail="Image exceeds max pixel limit (40M)")
img.verify()
except Image.DecompressionBombError:
raise HTTPException(status_code=413, detail="Image exceeds max pixel limit (40M)")
except HTTPException:
raise
except Exception:
raise HTTPException(status_code=415, detail="Corrupt image content")
sha256 = hashlib.sha256(body).hexdigest().lower()
att_id = uuid.uuid4()
job_id = uuid.uuid4()
now = datetime.now(timezone.utc)
staging_key = f"staging/{cid}/{att_id}"
final_key = f"attachments/{cid}/{att_id}/original"
# 1. Durable Staging в S3
try:
await asyncio.to_thread(
s3_client.put_object,
Bucket=S3_BUCKET,
Key=staging_key,
Body=body,
ContentType=content_type
)
except Exception:
raise HTTPException(status_code=503, detail="S3 staging unavailable")
# 2. Сохранение метаданных и намерения (Transactional Outbox) в единой транзакции
async with db_pool.acquire() as conn:
async with conn.transaction():
await conn.execute(
"""
INSERT INTO attachments (id, chat_id, user_id, filename, size_bytes, sha256, content_type, status, object_key, staging_key, pipeline_version, created_at, updated_at, error_code)
VALUES ($1, $2, $3, $4, $5, $6, $7, 'queued', $8, $9, 1, $10, $10, NULL)
""",
att_id, cid, uuid.UUID(current_user["id"]), filename, size_bytes, sha256, content_type, final_key, staging_key, now
)
await conn.execute(
"""
INSERT INTO attachment_jobs (job_id, attachment_id, pipeline_version, status, attempt, max_attempts, outbox_published, next_run_at, created_at, updated_at)
VALUES ($1, $2, 1, 'queued', 1, $3, FALSE, $4, $4, $4)
""",
job_id, att_id, JOB_MAX_ATTEMPTS, now
)
# 3. Немедленная попытка публикации с Publisher Confirm (при сбое подхватит Outbox Relay)
if await publish_job_direct(job_id, att_id, 1, now):
async with db_pool.acquire() as conn:
await conn.execute("UPDATE attachment_jobs SET outbox_published = TRUE WHERE job_id = $1", job_id)
return JSONResponse(
status_code=202,
content={
"id": str(att_id),
"chat_id": str(cid),
"owner_id": current_user["id"],
"status": "queued",
"filename": filename,
"size_bytes": size_bytes,
"sha256": sha256,
"content_type": content_type,
"created_at": to_rfc3339(now),
"updated_at": to_rfc3339(now),
"variants": [],
"error_code": None
}
)
@app.post("/chats/{chat_id}/attachments", status_code=202)
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(
chat_id: str,
request: Request,
filename: str = Query(...),
current_user: dict = Depends(get_current_user)
):
return await upload_attachment_handler(chat_id, request, filename, current_user)
async def get_attachment_meta_handler(attachment_id: str, current_user: dict):
aid = validate_uuid(attachment_id, "attachment_id")
async with db_pool.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT a.id, a.chat_id, a.user_id as owner_id, a.filename, a.size_bytes, a.sha256, a.content_type, a.status, a.pipeline_version, a.created_at, a.updated_at, a.error_code
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id
WHERE a.id = $1 AND cm.user_id = $2
""",
aid, uuid.UUID(current_user["id"])
)
if not row:
raise HTTPException(status_code=404, detail="Attachment not found")
variants = []
if row["status"] == "ready":
v_rows = await conn.fetch(
"""
SELECT name, content_type, size_bytes, width, height, sha256
FROM attachment_variants
WHERE attachment_id = $1 AND pipeline_version = $2
ORDER BY name ASC
""",
aid, row["pipeline_version"]
)
for vr in v_rows:
variants.append({
"name": vr["name"],
"content_type": vr["content_type"],
"size_bytes": vr["size_bytes"],
"width": vr["width"],
"height": vr["height"],
"sha256": vr["sha256"]
})
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"owner_id": str(row["owner_id"]),
"status": row["status"],
"filename": row["filename"],
"size_bytes": row["size_bytes"],
"sha256": row["sha256"],
"content_type": row["content_type"],
"created_at": to_rfc3339(row["created_at"]),
"updated_at": to_rfc3339(row["updated_at"]),
"variants": variants,
"error_code": row["error_code"]
}
@app.get("/attachments/{attachment_id}")
@app.get("/api/v1/attachments/{attachment_id}")
async def get_attachment_meta(attachment_id: str, current_user: dict = Depends(get_current_user)):
return await get_attachment_meta_handler(attachment_id, current_user)
async def download_attachment_content_handler(attachment_id: str, variant: str, current_user: dict):
aid = validate_uuid(attachment_id, "attachment_id")
if variant not in ("original", "thumbnail", "crop", "optimized"):
raise HTTPException(status_code=400, detail="Invalid variant parameter")
async with db_pool.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT a.id, a.chat_id, a.status, a.pipeline_version, a.object_key, a.content_type, a.filename
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id
WHERE a.id = $1 AND cm.user_id = $2
""",
aid, uuid.UUID(current_user["id"])
)
if not row:
raise HTTPException(status_code=404, detail="Attachment not found")
if row["status"] != "ready":
raise HTTPException(status_code=409, detail=f"Attachment is {row['status']}, content not available yet")
target_key = row["object_key"]
target_ct = row["content_type"]
target_name = row["filename"]
if variant != "original":
v_row = await conn.fetchrow(
"""
SELECT object_key, content_type
FROM attachment_variants
WHERE attachment_id = $1 AND pipeline_version = $2 AND name = $3
""",
aid, row["pipeline_version"], variant
)
if not v_row:
raise HTTPException(status_code=404, detail=f"Variant '{variant}' not found")
target_key = v_row["object_key"]
target_ct = v_row["content_type"]
ext = "webp" if target_ct == "image/webp" else "jpg"
target_name = f"{variant}.{ext}"
try:
s3_obj = await asyncio.to_thread(s3_client.get_object, Bucket=S3_BUCKET, Key=target_key)
data = await asyncio.to_thread(s3_obj["Body"].read)
except Exception:
raise HTTPException(status_code=503, detail="S3 storage unavailable")
return Response(
content=data,
media_type=target_ct,
headers={"Content-Disposition": f'inline; filename="{target_name}"'}
)
@app.get("/attachments/{attachment_id}/content")
@app.get("/api/v1/attachments/{attachment_id}/content")
async def download_attachment_content(
attachment_id: str,
variant: str = Query("original"),
current_user: dict = Depends(get_current_user)
):
return await download_attachment_content_handler(attachment_id, variant, current_user)
# --- ОПЕРАТОРСКИЙ REPLAY ДЛЯ FAILED / DLQ ---
@app.post("/internal/attachments/{attachment_id}/replay")
async def replay_failed_attachment(attachment_id: str):
aid = validate_uuid(attachment_id, "attachment_id")
now = datetime.now(timezone.utc)
async with db_pool.acquire() as conn:
async with conn.transaction():
att = await conn.fetchrow("SELECT id, status, pipeline_version FROM attachments WHERE id = $1 FOR UPDATE", aid)
if not att:
raise HTTPException(status_code=404, detail="Attachment not found")
if att["status"] == "ready":
# Безопасный no-op для уже готового вложения
return {"status": "ready", "replayed": False, "message": "Already ready"}
if att["status"] != "failed":
raise HTTPException(status_code=409, detail=f"Cannot replay attachment in status '{att['status']}'")
await conn.execute("UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = $2 WHERE id = $1", aid, now)
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued', attempt = attempt + 1, outbox_published = FALSE, next_run_at = $2, locked_until = NULL, last_error_code = NULL, updated_at = $2
WHERE attachment_id = $1 AND pipeline_version = $3
""",
aid, now, att["pipeline_version"]
)
return {"status": "queued", "replayed": True}
# --- MESSAGES ---
async def create_message_handler(chat_id: str, req: CreateMessageRequest, current_user: dict, idempotency_key: Optional[str]):
if not idempotency_key or not IDEMPOTENCY_REGEX.match(idempotency_key):
raise HTTPException(status_code=400, detail="Missing or invalid Idempotency-Key")
cid = validate_uuid(chat_id, "chat_id")
uid = uuid.UUID(current_user["id"])
if not req.attachment_ids and not (req.text and req.text.strip()):
raise HTTPException(status_code=400, detail="Message text cannot be blank without attachments")
att_uuids = [uuid.UUID(a) for a in req.attachment_ids]
body_dict = {"text": req.text, "attachment_ids": sorted(req.attachment_ids)}
req_hash = hashlib.sha256(json.dumps(body_dict, sort_keys=True).encode("utf-8")).hexdigest()
async with db_pool.acquire() as conn:
is_member = await conn.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
cid, uid
)
if not is_member:
raise HTTPException(status_code=404, detail="Chat not found")
if att_uuids:
att_rows = await conn.fetch("SELECT id, chat_id, status FROM attachments WHERE id = ANY($1::uuid[])", att_uuids)
if len(att_rows) != len(att_uuids):
raise HTTPException(status_code=404, detail="Some attachments not found")
for ar in att_rows:
if ar["chat_id"] != cid:
raise HTTPException(status_code=404, detail="Attachment belongs to another chat")
# Разрешаем queued, processing, ready; запрещаем только failed!
if ar["status"] == "failed":
raise HTTPException(status_code=409, detail="Failed attachment cannot be attached")
async with conn.transaction():
existing = await conn.fetchrow(
"""
SELECT request_hash, response_code, response_body
FROM idempotency_keys
WHERE user_id = $1 AND chat_id = $2 AND key = $3
FOR UPDATE
""",
uid, cid, idempotency_key
)
if existing:
if existing["request_hash"] != req_hash:
raise HTTPException(status_code=409, detail="Idempotency key collision with different body")
saved_body = json.loads(existing["response_body"]) if isinstance(existing["response_body"], str) else existing["response_body"]
return JSONResponse(status_code=existing["response_code"], content=saved_body)
msg_id = uuid.uuid4()
now = datetime.now(timezone.utc)
res_content = {
"id": str(msg_id),
"chat_id": str(cid),
"sender_id": current_user["id"],
"text": req.text,
"attachment_ids": req.attachment_ids,
"created_at": to_rfc3339(now)
}
await conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids, created_at)
VALUES ($1, $2, $3, $4, $5, $6)
""",
msg_id, cid, uid, req.text, att_uuids, now
)
await conn.execute(
"""
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, response_code, response_body, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
""",
uid, cid, idempotency_key, req_hash, 201, json.dumps(res_content), now
)
return JSONResponse(status_code=201, content=res_content)
@app.post("/chats/{chat_id}/messages", status_code=201)
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def create_message(
chat_id: str,
req: CreateMessageRequest,
current_user: dict = Depends(get_current_user),
idempotency_key: Optional[str] = Header(None, alias="Idempotency-Key")
):
return await create_message_handler(chat_id, req, current_user, idempotency_key)
async def list_messages_handler(chat_id: str, limit: int, cursor: Optional[str], current_user: dict):
cid = validate_uuid(chat_id, "chat_id")
if limit < 1 or limit > 100:
raise HTTPException(status_code=400, detail="Invalid limit")
async with db_pool.acquire() as conn:
is_member = await conn.fetchval("SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", cid, uuid.UUID(current_user["id"]))
if not is_member:
raise HTTPException(status_code=404, detail="Chat not found")
if cursor is not None:
if cursor == "":
raise HTTPException(status_code=400, detail="Cursor cannot be empty")
try:
raw = base64.b64decode(cursor).decode("utf-8")
parts = raw.split("|")
if len(parts) == 3:
cur_chat_id, c_time_str, c_id_str = parts
if cur_chat_id != str(cid):
raise HTTPException(status_code=400, detail="Cursor belongs to another chat")
elif len(parts) == 2:
c_time_str, c_id_str = parts
else:
raise ValueError()
cursor_time = datetime.fromisoformat(c_time_str.replace("Z", "+00:00"))
cursor_id = uuid.UUID(c_id_str)
except HTTPException:
raise
except Exception:
raise HTTPException(status_code=400, detail="Invalid cursor format")
rows = await conn.fetch(
"""
SELECT id, chat_id, sender_id, text, attachment_ids, created_at
FROM messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
ORDER BY created_at ASC, id ASC
LIMIT $4
""",
cid, cursor_time, cursor_id, limit + 1
)
else:
rows = await conn.fetch(
"""
SELECT id, chat_id, sender_id, text, attachment_ids, created_at
FROM messages
WHERE chat_id = $1
ORDER BY created_at ASC, id ASC
LIMIT $2
""",
cid, limit + 1
)
items = []
for r in rows[:limit]:
raw_atts = r["attachment_ids"] or []
items.append({
"id": str(r["id"]),
"chat_id": str(r["chat_id"]),
"sender_id": str(r["sender_id"]),
"text": r["text"],
"attachment_ids": [str(x) for x in raw_atts],
"created_at": to_rfc3339(r["created_at"])
})
next_cursor = None
if len(rows) > limit:
last = items[-1]
raw_cur = f"{cid}|{last['created_at']}|{last['id']}"
next_cursor = base64.b64encode(raw_cur.encode("utf-8")).decode("utf-8")
return {"items": items, "next_cursor": next_cursor}
@app.get("/chats/{chat_id}/messages")
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(chat_id: str, limit: int = 50, cursor: Optional[str] = None, current_user: dict = Depends(get_current_user)):
return await list_messages_handler(chat_id, limit, cursor, current_user)
+42
View File
@@ -0,0 +1,42 @@
import os
import asyncio
import asyncpg
import boto3
from botocore.client import Config
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://appuser:apppassword@postgres:5432/messenger_db")
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://s3:9000")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
S3_ACCESS_KEY = os.getenv("S3_ACCESS_KEY", "miniouser")
S3_SECRET_KEY = os.getenv("S3_SECRET_KEY", "miniopassword123")
async def main():
print("1. Применение миграций базы данных PostgreSQL...")
conn = await asyncpg.connect(DATABASE_URL)
migrations_dir = os.path.join(os.path.dirname(__file__), "..", "migrations")
sql_files = sorted([f for f in os.listdir(migrations_dir) if f.endswith(".sql")])
for sql_file in sql_files:
print(f" Выполнение: {sql_file}")
with open(os.path.join(migrations_dir, sql_file), "r", encoding="utf-8") as f:
await conn.execute(f.read())
await conn.close()
print("Миграции PostgreSQL успешно применены!")
print("\n2. Инициализация S3-бакета...")
s3 = boto3.client(
"s3",
endpoint_url=S3_ENDPOINT,
region_name="us-east-1",
aws_access_key_id=S3_ACCESS_KEY,
aws_secret_access_key=S3_SECRET_KEY,
config=Config(signature_version="s3v4")
)
try:
s3.head_bucket(Bucket=S3_BUCKET)
print(f" Бакет '{S3_BUCKET}' уже существует.")
except Exception:
s3.create_bucket(Bucket=S3_BUCKET)
print(f" Приватный бакет '{S3_BUCKET}' успешно создан!")
if __name__ == "__main__":
asyncio.run(main())
+409
View File
@@ -0,0 +1,409 @@
import os
import io
import math
import json
import uuid
import random
import hashlib
import asyncio
from datetime import datetime, timezone, timedelta
import asyncpg
import aio_pika
import boto3
from botocore.client import Config
from PIL import Image, ImageOps
def get_secret_or_env(file_var: str, default: str) -> str:
path = os.getenv(file_var)
if path and os.path.exists(path):
with open(path, "r", encoding="utf-8") as f:
return f.read().strip()
return default
DATABASE_URL = get_secret_or_env("DATABASE_URL_FILE", "postgresql://appuser:apppassword@postgres:5432/messenger_db")
BROKER_URL = get_secret_or_env("BROKER_URL_FILE", "amqp://rabbituser:rabbitpassword@broker:5672/")
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://s3:9000")
S3_REGION = os.getenv("S3_REGION", "us-east-1")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
S3_ACCESS_KEY = get_secret_or_env("S3_ACCESS_KEY_ID_FILE", "miniouser")
S3_SECRET_KEY = get_secret_or_env("S3_SECRET_ACCESS_KEY_FILE", "miniopassword123")
WORKER_CONCURRENCY = int(os.getenv("WORKER_CONCURRENCY", "2"))
JOB_TIMEOUT_SECONDS = int(os.getenv("JOB_TIMEOUT_SECONDS", "60"))
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
WORKER_ID = str(uuid.uuid4())
QUEUE_NAME = "attachment_jobs"
DLQ_NAME = "attachment_jobs.dlq"
def to_rfc3339(dt: datetime) -> str:
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
class PermanentImageError(Exception):
def __init__(self, code: str, message: str):
self.code = code
self.message = message
super().__init__(message)
def prepare_rgb_image(img: Image.Image) -> Image.Image:
# Применяем EXIF ориентацию
img = ImageOps.exif_transpose(img)
# Компонуем alpha-канал на белый фон
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
rgba = img.convert("RGBA")
bg = Image.new("RGB", rgba.size, (255, 255, 255))
bg.paste(rgba, mask=rgba.split()[3])
return bg
return img.convert("RGB")
def generate_variants(raw_bytes: bytes) -> list:
try:
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
with Image.open(io.BytesIO(raw_bytes)) as src_img:
w, h = src_img.size
if w * h > MAX_IMAGE_PIXELS:
raise PermanentImageError("invalid_image", "Image exceeds pixel limit")
rgb = prepare_rgb_image(src_img)
except PermanentImageError:
raise
except Image.DecompressionBombError:
raise PermanentImageError("invalid_image", "Decompression bomb detected")
except Exception as e:
raise PermanentImageError("invalid_image", f"Corrupt image: {e}")
orig_w, orig_h = rgb.size
variants = []
# 1. Thumbnail: вписан в 256x256, без увеличения, floor, мин 1 px, JPEG
if max(orig_w, orig_h) > 256:
scale = min(256.0 / orig_w, 256.0 / orig_h)
tw = max(1, int(math.floor(orig_w * scale)))
th = max(1, int(math.floor(orig_h * scale)))
thumb_img = rgb.resize((tw, th), Image.Resampling.LANCZOS)
else:
tw, th = orig_w, orig_h
thumb_img = rgb.copy()
buf_thumb = io.BytesIO()
thumb_img.save(buf_thumb, format="JPEG", quality=85, optimize=True)
b_thumb = buf_thumb.getvalue()
variants.append({
"name": "thumbnail",
"content_type": "image/jpeg",
"width": tw,
"height": th,
"bytes": b_thumb,
"size_bytes": len(b_thumb),
"sha256": hashlib.sha256(b_thumb).hexdigest().lower()
})
# 2. Crop: центрированный квадрат 128x128 (допускается увеличение), JPEG
crop_img = ImageOps.fit(rgb, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5))
buf_crop = io.BytesIO()
crop_img.save(buf_crop, format="JPEG", quality=85, optimize=True)
b_crop = buf_crop.getvalue()
variants.append({
"name": "crop",
"content_type": "image/jpeg",
"width": 128,
"height": 128,
"bytes": b_crop,
"size_bytes": len(b_crop),
"sha256": hashlib.sha256(b_crop).hexdigest().lower()
})
# 3. Optimized: вписан в 1280x1280 без увеличения, WebP, качество 80, без EXIF
if max(orig_w, orig_h) > 1280:
scale = min(1280.0 / orig_w, 1280.0 / orig_h)
ow = max(1, int(math.floor(orig_w * scale)))
oh = max(1, int(math.floor(orig_h * scale)))
opt_img = rgb.resize((ow, oh), Image.Resampling.LANCZOS)
else:
ow, oh = orig_w, orig_h
opt_img = rgb.copy()
buf_opt = io.BytesIO()
opt_img.save(buf_opt, format="WEBP", quality=80, method=4)
b_opt = buf_opt.getvalue()
variants.append({
"name": "optimized",
"content_type": "image/webp",
"width": ow,
"height": oh,
"bytes": b_opt,
"size_bytes": len(b_opt),
"sha256": hashlib.sha256(b_opt).hexdigest().lower()
})
return variants
async def outbox_relay_loop(db_pool: asyncpg.Pool, outbox_channel: aio_pika.Channel):
print(f"[{WORKER_ID}] Outbox relay started.")
while True:
try:
async with db_pool.acquire() as conn:
# 1. Возврат зависших задач с истекшим lease
expired = await conn.fetch(
"""
SELECT job_id, attachment_id, attempt, max_attempts, pipeline_version
FROM attachment_jobs
WHERE status = 'processing' AND locked_until < NOW()
"""
)
for row in expired:
if row["attempt"] < row["max_attempts"]:
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued', attempt = attempt + 1, outbox_published = FALSE, locked_until = NULL, last_error_code = 'lease_expired', next_run_at = NOW(), updated_at = NOW()
WHERE job_id = $1 AND status = 'processing'
""",
row["job_id"]
)
await conn.execute(
"UPDATE attachments SET status = 'queued', updated_at = NOW() WHERE id = $1 AND status = 'processing'",
row["attachment_id"]
)
else:
await conn.execute(
"UPDATE attachment_jobs SET status = 'failed', locked_until = NULL, last_error_code = 'retry_exhausted', updated_at = NOW() WHERE job_id = $1",
row["job_id"]
)
await conn.execute(
"UPDATE attachments SET status = 'failed', error_code = 'retry_exhausted', updated_at = NOW() WHERE id = $1 AND status != 'ready'",
row["attachment_id"]
)
# 2. Публикация неотправленных задач (Outbox)
pending = await conn.fetch(
"""
SELECT job_id, attachment_id, pipeline_version, attempt, created_at
FROM attachment_jobs
WHERE outbox_published = FALSE AND status = 'queued' AND next_run_at <= NOW()
LIMIT 20
"""
)
for job in pending:
payload = {
"schema_version": 1,
"job_id": str(job["job_id"]),
"type": "attachment.process.v1",
"attachment_id": str(job["attachment_id"]),
"pipeline_version": job["pipeline_version"],
"attempt": job["attempt"],
"created_at": to_rfc3339(job["created_at"])
}
msg = aio_pika.Message(
body=json.dumps(payload).encode("utf-8"),
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
content_type="application/json"
)
await outbox_channel.default_exchange.publish(msg, routing_key=QUEUE_NAME, mandatory=False)
await conn.execute(
"UPDATE attachment_jobs SET outbox_published = TRUE, updated_at = NOW() WHERE job_id = $1",
job["job_id"]
)
except Exception as e:
print(f"[Outbox Relay] Error: {e}")
await asyncio.sleep(0.5)
async def process_job(message: aio_pika.IncomingMessage, db_pool: asyncpg.Pool, s3_client, pub_channel: aio_pika.Channel):
try:
job_data = json.loads(message.body.decode("utf-8"))
job_id = uuid.UUID(job_data["job_id"])
att_id = uuid.UUID(job_data["attachment_id"])
pipeline_version = int(job_data["pipeline_version"])
except Exception:
await message.ack()
return
async with db_pool.acquire() as conn:
att = await conn.fetchrow(
"SELECT id, chat_id, status, pipeline_version, content_type, staging_key, object_key FROM attachments WHERE id = $1",
att_id
)
if not att or att["status"] == "ready" or att["pipeline_version"] > pipeline_version:
await message.ack()
return
job = await conn.fetchrow(
"SELECT job_id, attempt, max_attempts, status FROM attachment_jobs WHERE job_id = $1",
job_id
)
if not job or job["status"] == "ready":
await message.ack()
return
lease_until = datetime.now(timezone.utc) + timedelta(seconds=JOB_TIMEOUT_SECONDS)
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'processing', locked_until = $2, worker_id = $3, updated_at = NOW()
WHERE job_id = $1
""",
job_id, lease_until, WORKER_ID
)
await conn.execute(
"UPDATE attachments SET status = 'processing', updated_at = NOW() WHERE id = $1 AND status = 'queued'",
att_id
)
try:
source_key = att["staging_key"] or att["object_key"]
try:
s3_obj = await asyncio.to_thread(s3_client.get_object, Bucket=S3_BUCKET, Key=source_key)
raw_bytes = await asyncio.to_thread(s3_obj["Body"].read)
except Exception:
s3_obj = await asyncio.to_thread(s3_client.get_object, Bucket=S3_BUCKET, Key=att["object_key"])
raw_bytes = await asyncio.to_thread(s3_obj["Body"].read)
variants = await asyncio.wait_for(
asyncio.to_thread(generate_variants, raw_bytes),
timeout=JOB_TIMEOUT_SECONDS
)
# Публикация оригинала в конечный S3-prefix
await asyncio.to_thread(
s3_client.put_object,
Bucket=S3_BUCKET,
Key=att["object_key"],
Body=raw_bytes,
ContentType=att["content_type"]
)
# Публикация вариантов в S3
for v in variants:
ext = "webp" if v["content_type"] == "image/webp" else "jpg"
v_key = f"attachments/{att['chat_id']}/{att_id}/{v['name']}.{ext}"
v["object_key"] = v_key
await asyncio.to_thread(
s3_client.put_object,
Bucket=S3_BUCKET,
Key=v_key,
Body=v["bytes"],
ContentType=v["content_type"]
)
# Атомарная фиксация в PostgreSQL
now = datetime.now(timezone.utc)
async with db_pool.acquire() as conn:
async with conn.transaction():
cur_att = await conn.fetchrow("SELECT status, pipeline_version FROM attachments WHERE id = $1 FOR UPDATE", att_id)
if cur_att["status"] == "ready" or cur_att["pipeline_version"] > pipeline_version:
await message.ack()
return
for v in variants:
await conn.execute(
"""
INSERT INTO attachment_variants (attachment_id, pipeline_version, name, content_type, size_bytes, width, height, sha256, object_key, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE
SET size_bytes = EXCLUDED.size_bytes, sha256 = EXCLUDED.sha256, object_key = EXCLUDED.object_key
""",
att_id, pipeline_version, v["name"], v["content_type"], v["size_bytes"], v["width"], v["height"], v["sha256"], v["object_key"], now
)
await conn.execute(
"UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = $2 WHERE id = $1",
att_id, now
)
await conn.execute(
"UPDATE attachment_jobs SET status = 'ready', locked_until = NULL, updated_at = $2 WHERE job_id = $1",
job_id, now
)
# Безопасная очистка staging после фиксации в БД
if att["staging_key"] and att["staging_key"] != att["object_key"]:
try:
await asyncio.to_thread(s3_client.delete_object, Bucket=S3_BUCKET, Key=att["staging_key"])
except Exception:
pass
await message.ack()
print(f"[Worker] Job {job_id} -> READY (att {att_id})")
except PermanentImageError as pe:
now = datetime.now(timezone.utc)
async with db_pool.acquire() as conn:
async with conn.transaction():
await conn.execute("UPDATE attachments SET status = 'failed', error_code = $2, updated_at = $3 WHERE id = $1 AND status != 'ready'", att_id, pe.code, now)
await conn.execute("UPDATE attachment_jobs SET status = 'failed', locked_until = NULL, last_error_code = $2, last_error_message = $3, updated_at = $4 WHERE job_id = $1", job_id, pe.code, pe.message[:200], now)
dlq_msg = aio_pika.Message(body=message.body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT)
await pub_channel.default_exchange.publish(dlq_msg, routing_key=DLQ_NAME, mandatory=False)
await message.ack()
print(f"[Worker] Job {job_id} -> FAILED ({pe.code})")
except Exception as exc:
err_msg = str(exc)[:200]
now = datetime.now(timezone.utc)
async with db_pool.acquire() as conn:
cur_job = await conn.fetchrow("SELECT attempt, max_attempts FROM attachment_jobs WHERE job_id = $1", job_id)
attempt = cur_job["attempt"]
max_attempts = cur_job["max_attempts"]
if attempt < max_attempts:
backoff = min(30.0, (2 ** attempt) + random.uniform(0.1, 1.5))
next_run = now + timedelta(seconds=backoff)
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued', attempt = attempt + 1, outbox_published = FALSE, next_run_at = $2, locked_until = NULL, last_error_code = 'processing_failed', last_error_message = $3, updated_at = $4
WHERE job_id = $1
""",
job_id, next_run, err_msg, now
)
await conn.execute("UPDATE attachments SET status = 'queued', updated_at = $2 WHERE id = $1 AND status != 'ready'", att_id, now)
print(f"[Worker] Job {job_id} retry {attempt + 1}/{max_attempts} scheduled in {backoff:.1f}s")
else:
await conn.execute("UPDATE attachments SET status = 'failed', error_code = 'retry_exhausted', updated_at = $2 WHERE id = $1 AND status != 'ready'", att_id, now)
await conn.execute("UPDATE attachment_jobs SET status = 'failed', locked_until = NULL, last_error_code = 'retry_exhausted', last_error_message = $2, updated_at = $3 WHERE job_id = $1", job_id, err_msg, now)
dlq_msg = aio_pika.Message(body=message.body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT)
await pub_channel.default_exchange.publish(dlq_msg, routing_key=DLQ_NAME, mandatory=False)
print(f"[Worker] Job {job_id} -> DLQ (retry_exhausted)")
await message.ack()
async def main():
print(f"Starting Worker {WORKER_ID} (concurrency={WORKER_CONCURRENCY})...")
db_pool = await asyncpg.create_pool(DATABASE_URL, min_size=2, max_size=10, command_timeout=15.0)
s3_client = boto3.client(
"s3",
endpoint_url=S3_ENDPOINT,
region_name=S3_REGION,
aws_access_key_id=S3_ACCESS_KEY,
aws_secret_access_key=S3_SECRET_KEY,
config=Config(signature_version="s3v4")
)
rabbit_conn = await aio_pika.connect_robust(BROKER_URL)
consume_channel = await rabbit_conn.channel()
await consume_channel.set_qos(prefetch_count=WORKER_CONCURRENCY)
outbox_channel = await rabbit_conn.channel(publisher_confirms=True)
pub_channel = await rabbit_conn.channel(publisher_confirms=True)
await consume_channel.declare_queue(DLQ_NAME, durable=True)
queue = await consume_channel.declare_queue(
QUEUE_NAME,
durable=True,
arguments={"x-dead-letter-exchange": "", "x-dead-letter-routing-key": DLQ_NAME}
)
relay_task = asyncio.create_task(outbox_relay_loop(db_pool, outbox_channel))
async def on_message(msg: aio_pika.IncomingMessage):
await process_job(msg, db_pool, s3_client, pub_channel)
await queue.consume(on_message)
print("Worker ready and listening on RabbitMQ...")
try:
await asyncio.Future()
finally:
relay_task.cancel()
await rabbit_conn.close()
await db_pool.close()
if __name__ == "__main__":
asyncio.run(main())
+86
View File
@@ -0,0 +1,86 @@
import base64
import io
import time
import httpx
import pytest
from PIL import Image
BASE_URL = "http://localhost:8080"
def get_client():
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=20.0)
def auth_user(client, username):
pw = "super_password_12345"
client.post("/users", json={"username": username, "display_name": "Test", "password": pw})
b64 = base64.b64encode(f"{username}:{pw}".encode()).decode()
res = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"})
return res.json()["token"], res.json()["user"]["id"]
def make_test_png(w=400, h=300):
img = Image.new("RGBA", (w, h), (100, 150, 200, 128))
buf = io.BytesIO()
img.save(buf, format="PNG")
return buf.getvalue()
def test_async_upload_and_all_three_variants():
with get_client() as client:
ts = int(time.time() * 1000)
token, uid = auth_user(client, f"u_l5_{ts}")
h = {"Authorization": f"Bearer {token}"}
chat_id = client.post("/chats", json={"title": "Lab5 Chat", "member_ids": [uid]}, headers=h).json()["id"]
png_bytes = make_test_png(400, 300)
up = client.post(
f"/chats/{chat_id}/attachments?filename=pic.png",
content=png_bytes,
headers={**h, "Content-Type": "image/png"}
)
# 1. Должен вернуться 202 queued
assert up.status_code == 202
att = up.json()
assert att["status"] == "queued"
att_id = att["id"]
# 2. Ждем готовности (ready)
deadline = time.time() + 20
ready = None
while time.time() < deadline:
meta = client.get(f"/attachments/{att_id}", headers=h).json()
if meta["status"] == "ready":
ready = meta
break
time.sleep(0.3)
assert ready is not None, "Attachment did not become ready in time"
variants = {v["name"]: v for v in ready["variants"]}
# 3. Проверяем все 3 варианта: thumbnail, crop, optimized
assert "thumbnail" in variants
assert "crop" in variants
assert "optimized" in variants
# Проверяем thumbnail (400x300 -> вписан в 256x256 -> 256x192)
assert variants["thumbnail"]["content_type"] == "image/jpeg"
assert (variants["thumbnail"]["width"], variants["thumbnail"]["height"]) == (256, 192)
dl_thumb = client.get(f"/attachments/{att_id}/content?variant=thumbnail", headers=h)
assert dl_thumb.status_code == 200
assert dl_thumb.headers.get("Content-Type") == "image/jpeg"
# Проверяем crop (128x128 JPEG)
assert variants["crop"]["content_type"] == "image/jpeg"
assert (variants["crop"]["width"], variants["crop"]["height"]) == (128, 128)
dl_crop = client.get(f"/attachments/{att_id}/content?variant=crop", headers=h)
assert dl_crop.status_code == 200
# Проверяем optimized (WebP, 400x300 без апскейла)
assert variants["optimized"]["content_type"] == "image/webp"
assert (variants["optimized"]["width"], variants["optimized"]["height"]) == (400, 300)
dl_opt = client.get(f"/attachments/{att_id}/content?variant=optimized", headers=h)
assert dl_opt.status_code == 200
assert dl_opt.headers.get("Content-Type") == "image/webp"
# 4. Безопасный replay уже готового вложения (не дублирует и не портит)
rep = client.post(f"/internal/attachments/{att_id}/replay")
assert rep.status_code == 200
assert rep.json()["replayed"] is False