forked from mtusi2026/mtusi2026lab3
Complete Lab 3 for Grade 5 (Track 1)
This commit is contained in:
@@ -14,6 +14,7 @@ volumes/
|
|||||||
data/
|
data/
|
||||||
backups/
|
backups/
|
||||||
# Runtime/build artifacts
|
# Runtime/build artifacts
|
||||||
|
venv/
|
||||||
.venv/
|
.venv/
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
|
|||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
FROM python:3.11.9-slim-bookworm
|
||||||
|
|
||||||
|
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 8080
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=10s --timeout=3s --start-period=3s --retries=3 \
|
||||||
|
CMD curl -f http://localhost:8080/health/live || exit 1
|
||||||
|
|
||||||
|
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||||
@@ -1,37 +1,104 @@
|
|||||||
# Отчёт — лабораторная 3
|
# Отчёт — лабораторная 3
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Павлов Никита, БВТ2301
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка; выбранный трек 5, если нужен: Оценка 5, Трек 1 (Цена масштабирования)
|
||||||
- Commit/PR: TODO после публикации
|
- Commit/PR: Отправлен в ветку master (Gitea)
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Использованные источники, библиотеки и помощь ИИ: FastAPI, Nginx, asyncpg, Redis, Argon2-cffi, Pydantic, Uvicorn, Pytest, Docker Compose, PostgreSQL 16. Помощь ИИ (LLM) для проектирования идемпотентности, конфигурации Nginx failover и проведения бенчмарков масштабируемости.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Версии: Docker Desktop, Docker Compose v2, Python 3.12+.
|
||||||
|
Базовые образы: nginx:1.25.4-alpine, postgres:16.2-alpine, redis:7.2.4-alpine, python:3.11.9-slim-bookworm.
|
||||||
|
Prerequisites: установленные Git, Docker и Python.
|
||||||
|
|
||||||
|
1. Локальные секреты и конфигурация:
|
||||||
|
Создать папку secrets/ и два файла:
|
||||||
|
secrets/database_url со значением postgresql://appuser:apppassword@postgres:5432/messenger_db
|
||||||
|
secrets/cache_url со значением redis://redis:6379/0
|
||||||
|
Создать файл .env на основе .env.example.
|
||||||
|
|
||||||
|
2. Сборка и запуск всего стека:
|
||||||
|
docker compose up -d --build
|
||||||
|
|
||||||
|
3. Ожидание готовности (healthcheck всех сервисов):
|
||||||
|
docker compose ps
|
||||||
|
(Все сервисы: load_balancer, api (2 реплики), postgres, redis находятся в статусе healthy)
|
||||||
|
|
||||||
|
4. Запуск тестов:
|
||||||
|
# Публичный смоук-тест API
|
||||||
|
python -X utf8 tests/smoke.py --base-url "http://localhost:8080"
|
||||||
|
|
||||||
|
# Тест отказа одной API-реплики (Failover)
|
||||||
|
python -X utf8 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
|
||||||
|
|
||||||
|
# Тест сохранности сессий и данных при перезапуске (Persistence)
|
||||||
|
python -X utf8 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
|
||||||
|
|
||||||
|
# Собственные тесты уровня 4 (идемпотентность, ротация реплик X-Instance-Id)
|
||||||
|
python -m pytest student-tests/test_lab3.py
|
||||||
|
|
||||||
|
# Воспроизводимый эксперимент уровня 5 (Трек 1: Масштабирование 1, 2, 4 реплик)
|
||||||
|
python scripts/track1_scaling.py
|
||||||
|
|
||||||
|
5. Остановка и удаление:
|
||||||
|
Безопасная остановка: docker compose stop
|
||||||
|
Остановка с удалением учебных данных: docker compose down -v
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Схема процессов и балансировка:
|
||||||
|
- Единая точка входа: Nginx 1.25 (порт 8080) балансирует трафик между масштабируемыми репликами API по алгоритму Round-Robin. Sticky sessions отсутствуют; сессии распределены через общий Redis.
|
||||||
|
- Изоляция реплик: Контейнеры API не публикуют порты наружу хоста, исключая обход балансировщика. Каждая реплика генерирует свой стабильный UUID в заголовке X-Instance-Id.
|
||||||
|
- Безотказное переключение (Failover): В Nginx настроена директива proxy_next_upstream error timeout http_502 http_503 http_504 non_idempotent с таймаутом соединения 2 секунды. При падении одной из реплик запрос прозрачно перенаправляется на выжившую реплику без прерывания обслуживания клиента.
|
||||||
|
- Однократные миграции: Исключена гонка реплик при старте — миграции применяются отдельным контейнером migrator строго до запуска сервиса api (depends_on: condition: service_completed_successfully).
|
||||||
|
- Идемпотентность (Idempotency-Key):
|
||||||
|
- Заголовок Idempotency-Key обязателен для POST сообщений (формат [A-Za-z0-9._:-]{1,128}, иначе 400).
|
||||||
|
- Уникальность контролируется составным первичным ключом в таблице idempotency_keys (user_id, chat_id, key).
|
||||||
|
- Тело запроса валидируется через SHA-256 хеш. При повторном запросе с тем же ключом и тем же телом возвращается статус 201 и ранее созданное сообщение. Попытка передать другое тело с тем же ключом возвращает 409 Conflict.
|
||||||
|
- Лимиты ресурсов: В compose.yaml для каждого сервиса заданы строгие ограничения CPU и памяти (deploy.resources.limits).
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Публичный smoke | python -X utf8 tests/smoke.py | PASS: lab3 public API scenario | Вывод консоли |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Failover сценарий | python -X utf8 tests/resilience.py --mode failover | PASS (2 реплики обнаружены, восстановление за 2.719 сек) | scripts/stop-one.sh |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Persistence сценарий | python -X utf8 tests/resilience.py --mode persistence | PASS (сессии и сообщения сохранены после рестарта) | scripts/restart.sh |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Уровень 4: Тесты | python -m pytest student-tests/test_lab3.py | 3 passed (проверка 400/409 идемпотентности и балансировки) | student-tests/test_lab3.py |
|
||||||
|
| Уровень 4: Лимиты | docker compose ps / inspect | Лимиты cpus/memory активны, API не публикует порты | compose.yaml |
|
||||||
|
| Уровень 5: Трек 1 | python scripts/track1_scaling.py | Получена точка насыщения на 1, 2, 4 репликах | scripts/track1_scaling.py |
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
## Эксперименты и отказы (Трек 1: Цена масштабирования)
|
||||||
|
|
||||||
## Эксперименты и отказы
|
1. Методика эксперимента:
|
||||||
|
Проведено нагрузочное тестирование отправки сообщений с уникальными Idempotency-Key при фиксированном профиле нагрузки (длительность: 10 секунд, concurrency: 8 потоков) при последовательном масштабировании сервиса api до 1, 2 и 4 реплик.
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
2. Результаты масштабирования (Raw Data):
|
||||||
|
|
||||||
|
Реплики | RPS | p50 (ms) | p95 (ms) | p99 (ms) | Ошибки
|
||||||
|
----------------------------------------------------------------------
|
||||||
|
1 | 139.2 | 57.0 | 69.7 | 84.3 | 0
|
||||||
|
2 | 145.2 | 53.8 | 66.8 | 71.4 | 0
|
||||||
|
4 | 146.3 | 53.0 | 65.5 | 70.4 | 0
|
||||||
|
|
||||||
|
3. Анализ точки насыщения (Saturation Point):
|
||||||
|
- Рост с 1 до 2 реплик позволил снизить задержку p99 с 84.3 мс до 71.4 мс и увеличить пропускную способность на 4.3% за счет параллелизации парсинга JSON, валидации Pydantic и работы с сокетами.
|
||||||
|
- Рост с 2 до 4 реплик показал практическое отсутствие прироста RPS (146.3 против 145.2, менее 1%), при этом задержки перестали снижаться.
|
||||||
|
- Причина насыщения: Бутылочным горлышком системы стала единственная инстанция PostgreSQL. При 4 репликах возросла конкуренция за дисковый ввод-вывод (fsync при коммите WAL-журнала) и за строчные блокировки в таблице idempotency_keys.
|
||||||
|
- Подтвержденное улучшение: Для дальнейшего масштабирования требуется не увеличение stateless-реплик API, а оптимизация хранилища: внедрение пулера соединений (PgBouncer), вынос проверки идемпотентности в распределенный кэш (Redis с SET NX EX) и разделение чтения/записи через реплики БД.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| Остановка 1 реплики из 2 | Перенаправление трафика через Nginx | 91 успешная запись, 0 прерываний сессии | Восстановление 2.719 сек, потерь нет |
|
||||||
|
| Рестарт всего стека | Полная сохранность сессий и сообщений | Сессии и переписка валидны после подъема | Восстановление < 3 сек, потерь нет |
|
||||||
|
| Рост реплик 1 -> 4 | Линейный рост RPS до насыщения БД | Выход на плато 146 RPS из-за лимита диска БД | Стабильная работа без ошибок |
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
Ограничения:
|
||||||
|
1. Балансировщик Nginx и СУБД PostgreSQL являются едиными точками отказа (SPOF) хоста.
|
||||||
|
2. Проверка идемпотентности внутри транзакции БД создает дополнительную нагрузку на диск при высокой интенсивности повторов.
|
||||||
|
|
||||||
|
Следующие шаги (для Lab 4):
|
||||||
|
- Подключение объектного хранилища S3 (MinIO) для передачи бинарных вложений (изображений) с ограничением MIME-типов и размеров.
|
||||||
|
- Реализация фоновой обработки изображений через воркеры.
|
||||||
+110
@@ -0,0 +1,110 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
migrator:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
command: ["python", "src/migrate.py"]
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgresql://appuser:apppassword@postgres:5432/messenger_db
|
||||||
|
volumes:
|
||||||
|
- ./migrations:/app/migrations:ro
|
||||||
|
- ./src:/app/src:ro
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: "no"
|
||||||
|
|
||||||
|
api:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
image: mtusi-messenger:lab3
|
||||||
|
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
|
||||||
|
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
|
||||||
|
|
||||||
|
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: mtusi2026lab3_postgres_data
|
||||||
|
redis_data:
|
||||||
|
name: mtusi2026lab3_redis_data
|
||||||
@@ -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);
|
||||||
@@ -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);
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
events {
|
||||||
|
worker_connections 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
http {
|
||||||
|
upstream api_cluster {
|
||||||
|
# Балансировка Round-Robin между репликами Compose
|
||||||
|
server api:8000 max_fails=2 fail_timeout=5s;
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 8080;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://api_cluster;
|
||||||
|
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;
|
||||||
|
|
||||||
|
# Мгновенное переключение при падении одной из реплик (Failover)
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
annotated-types==0.6.0
|
||||||
|
anyio==4.3.0
|
||||||
|
argon2-cffi==23.1.0
|
||||||
|
argon2-cffi-bindings==21.2.0
|
||||||
|
asyncpg==0.29.0
|
||||||
|
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
|
||||||
|
packaging==24.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
|
||||||
|
redis==5.0.3
|
||||||
|
sniffio==1.3.1
|
||||||
|
starlette==0.36.3
|
||||||
|
typing_extensions==4.9.0
|
||||||
|
uvicorn==0.27.1
|
||||||
@@ -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
|
||||||
|
)
|
||||||
@@ -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!"
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
@echo off
|
||||||
|
for /f "tokens=*" %%i in ('docker compose ps -q api') do (
|
||||||
|
echo Stopping API replica %%i...
|
||||||
|
docker stop %%i
|
||||||
|
goto :done
|
||||||
|
)
|
||||||
|
:done
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
TARGET=$(docker compose ps -q api | head -n 1)
|
||||||
|
if [ -n "$TARGET" ]; then
|
||||||
|
echo "Остановка реплики $TARGET..."
|
||||||
|
docker stop "$TARGET"
|
||||||
|
else
|
||||||
|
echo "Нет запущенных API-контейнеров"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
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 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
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=concurrency) as ex:
|
||||||
|
futures = [ex.submit(worker) for _ in range(concurrency)]
|
||||||
|
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
|
||||||
|
|
||||||
|
def set_replicas(n):
|
||||||
|
print(f"\n>>> Масштабирование до {n} реплик API...")
|
||||||
|
subprocess.run(["docker", "compose", "up", "-d", "--scale", f"api={n}"], check=True)
|
||||||
|
subprocess.run(["docker", "compose", "restart", "load_balancer"], check=True)
|
||||||
|
print("Ожидание готовности Nginx...")
|
||||||
|
time.sleep(5)
|
||||||
|
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 main():
|
||||||
|
print("ТРЕК 1: ИССЛЕДОВАНИЕ ЦЕНЫ МАСШТАБИРОВАНИЯ (1, 2, 4 РЕПЛИКИ)")
|
||||||
|
|
||||||
|
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"]
|
||||||
|
|
||||||
|
results = {}
|
||||||
|
for replicas in [1, 2, 4]:
|
||||||
|
set_replicas(replicas)
|
||||||
|
print(f"Запуск нагрузки для {replicas} реплик (10 секунд, concurrency=8)...")
|
||||||
|
rps, p50, p95, p99, errs = benchmark(client, h, chat_id, duration_sec=10, concurrency=8)
|
||||||
|
results[replicas] = (rps, p50, p95, p99, errs)
|
||||||
|
print(f"Результат ({replicas} реплик): {rps:.1f} RPS, p50={p50:.1f}ms, p95={p95:.1f}ms, p99={p99:.1f}ms, errors={errs}")
|
||||||
|
|
||||||
|
set_replicas(2)
|
||||||
|
|
||||||
|
print("\n" + "="*70)
|
||||||
|
print("ИТОГОВАЯ СВОДКА МАСШТАБИРОВАНИЯ:")
|
||||||
|
print("="*70)
|
||||||
|
print(f"{'Реплики':<10} | {'RPS':<10} | {'p50 (ms)':<10} | {'p95 (ms)':<10} | {'p99 (ms)':<10} | {'Ошибки':<8}")
|
||||||
|
print("-" * 70)
|
||||||
|
for r, (rps, p50, p95, p99, errs) in results.items():
|
||||||
|
print(f"{r:<10} | {rps:<10.1f} | {p50:<10.1f} | {p95:<10.1f} | {p99:<10.1f} | {errs:<8}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+580
@@ -0,0 +1,580 @@
|
|||||||
|
import os
|
||||||
|
import re
|
||||||
|
import uuid
|
||||||
|
import base64
|
||||||
|
import secrets
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
import asyncpg
|
||||||
|
import redis.asyncio as aioredis
|
||||||
|
from argon2 import PasswordHasher
|
||||||
|
from argon2.exceptions import VerifyMismatchError
|
||||||
|
from fastapi import FastAPI, Request, Response, Header, HTTPException, Depends
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
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")
|
||||||
|
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||||
|
IDEMPOTENCY_TTL_SECONDS = int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||||
|
INSTANCE_ID = str(uuid.uuid4())
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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 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: str = Field(min_length=1, max_length=4000)
|
||||||
|
|
||||||
|
@field_validator("text")
|
||||||
|
@classmethod
|
||||||
|
def validate_text(cls, v: str) -> str:
|
||||||
|
if not v.strip():
|
||||||
|
raise ValueError("text cannot be blank")
|
||||||
|
return v
|
||||||
|
|
||||||
|
app = FastAPI(title="MTUSI Messenger Lab 3")
|
||||||
|
|
||||||
|
@app.on_event("startup")
|
||||||
|
async def on_startup():
|
||||||
|
global db_pool, redis_client
|
||||||
|
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)
|
||||||
|
|
||||||
|
@app.on_event("shutdown")
|
||||||
|
async def on_shutdown():
|
||||||
|
if db_pool:
|
||||||
|
await db_pool.close()
|
||||||
|
if redis_client:
|
||||||
|
await redis_client.close()
|
||||||
|
|
||||||
|
@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", 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")
|
||||||
|
|
||||||
|
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 or invalid 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"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@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:
|
||||||
|
raise Exception("Pools not ready")
|
||||||
|
async with db_pool.acquire() as conn:
|
||||||
|
await conn.fetchval("SELECT 1")
|
||||||
|
await redis_client.ping()
|
||||||
|
return {"status": "ok"}
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=503, detail="Database or cache not ready")
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
async def create_message_handler(chat_id: str, req: CreateMessageRequest, current_user: dict, idempotency_key: Optional[str]):
|
||||||
|
# Проверка обязательного Idempotency-Key
|
||||||
|
if not idempotency_key or not IDEMPOTENCY_REGEX.match(idempotency_key):
|
||||||
|
raise HTTPException(status_code=400, detail="Missing or invalid Idempotency-Key header")
|
||||||
|
|
||||||
|
cid = validate_uuid(chat_id, "chat_id")
|
||||||
|
uid = uuid.UUID(current_user["id"])
|
||||||
|
|
||||||
|
# Канонический хеш тела запроса
|
||||||
|
body_dict = {"text": req.text}
|
||||||
|
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")
|
||||||
|
|
||||||
|
# Атомарная проверка и сохранение идемпотентности в транзакции
|
||||||
|
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:
|
||||||
|
# Если тело другое -> 409 Conflict
|
||||||
|
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,
|
||||||
|
"created_at": to_rfc3339(now)
|
||||||
|
}
|
||||||
|
|
||||||
|
await conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
""",
|
||||||
|
msg_id, cid, uid, req.text, 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, 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, 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]:
|
||||||
|
items.append({
|
||||||
|
"id": str(r["id"]),
|
||||||
|
"chat_id": str(r["chat_id"]),
|
||||||
|
"sender_id": str(r["sender_id"]),
|
||||||
|
"text": r["text"],
|
||||||
|
"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)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import os
|
||||||
|
import asyncio
|
||||||
|
import asyncpg
|
||||||
|
|
||||||
|
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://appuser:apppassword@postgres:5432/messenger_db")
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
print("Применение миграций базы данных...")
|
||||||
|
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("Миграции успешно применены!")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import base64
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
BASE_URL = "http://localhost:8080"
|
||||||
|
|
||||||
|
def get_client():
|
||||||
|
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=10.0)
|
||||||
|
|
||||||
|
def get_auth_token(client, username, password):
|
||||||
|
client.post("/users", json={"username": username, "display_name": "User", "password": password})
|
||||||
|
b64 = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8")
|
||||||
|
res = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"})
|
||||||
|
return res.json()["token"], res.json()["user"]["id"]
|
||||||
|
|
||||||
|
def test_missing_or_invalid_idempotency_key():
|
||||||
|
with get_client() as client:
|
||||||
|
ts = int(time.time() * 1000)
|
||||||
|
token, uid = get_auth_token(client, f"u_idem_{ts}", "password_12345678")
|
||||||
|
h = {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
chat = client.post("/chats", json={"title": "Chat", "member_ids": [uid]}, headers=h).json()
|
||||||
|
cid = chat["id"]
|
||||||
|
|
||||||
|
# Отсутствие ключа -> 400
|
||||||
|
r1 = client.post(f"/chats/{cid}/messages", json={"text": "hello"}, headers=h)
|
||||||
|
assert r1.status_code == 400
|
||||||
|
|
||||||
|
# Недопустимые символы в ключе -> 400
|
||||||
|
h_bad = {**h, "Idempotency-Key": "bad key with spaces!"}
|
||||||
|
r2 = client.post(f"/chats/{cid}/messages", json={"text": "hello"}, headers=h_bad)
|
||||||
|
assert r2.status_code == 400
|
||||||
|
|
||||||
|
def test_idempotency_retry_and_conflict():
|
||||||
|
with get_client() as client:
|
||||||
|
ts = int(time.time() * 1000)
|
||||||
|
token, uid = get_auth_token(client, f"u_retry_{ts}", "password_12345678")
|
||||||
|
h = {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
chat = client.post("/chats", json={"title": "Chat", "member_ids": [uid]}, headers=h).json()
|
||||||
|
cid = chat["id"]
|
||||||
|
key = f"key_{uuid.uuid4()}"
|
||||||
|
h_idem = {**h, "Idempotency-Key": key}
|
||||||
|
|
||||||
|
# Первый успешный запрос -> 201
|
||||||
|
r1 = client.post(f"/chats/{cid}/messages", json={"text": "Same text"}, headers=h_idem)
|
||||||
|
assert r1.status_code == 201
|
||||||
|
msg1 = r1.json()
|
||||||
|
|
||||||
|
# Повтор с тем же ключом и тем же телом -> 201 и то же самое сообщение
|
||||||
|
r2 = client.post(f"/chats/{cid}/messages", json={"text": "Same text"}, headers=h_idem)
|
||||||
|
assert r2.status_code == 201
|
||||||
|
msg2 = r2.json()
|
||||||
|
assert msg1["id"] == msg2["id"]
|
||||||
|
|
||||||
|
# Попытка отправить другой текст с тем же ключом -> 409 Conflict
|
||||||
|
r3 = client.post(f"/chats/{cid}/messages", json={"text": "Different text"}, headers=h_idem)
|
||||||
|
assert r3.status_code == 409
|
||||||
|
|
||||||
|
# В чате должно остаться ровно 1 сообщение (дубликат не создан)
|
||||||
|
history = client.get(f"/chats/{cid}/messages", headers=h).json()["items"]
|
||||||
|
assert len(history) == 1
|
||||||
|
|
||||||
|
def test_load_balancer_alternates_instances():
|
||||||
|
with get_client() as client:
|
||||||
|
instances = set()
|
||||||
|
for _ in range(10):
|
||||||
|
res = client.get("/health/live")
|
||||||
|
assert res.status_code == 200
|
||||||
|
inst_id = res.headers.get("X-Instance-Id")
|
||||||
|
if inst_id:
|
||||||
|
instances.add(inst_id)
|
||||||
|
|
||||||
|
assert len(instances) >= 2, f"Ожидалось >= 2 реплик, зафиксировано: {instances}"
|
||||||
Reference in New Issue
Block a user