Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b15688149 | ||
|
|
6dbc2da1ca |
@@ -9,3 +9,8 @@ DATABASE_URL_FILE=/run/secrets/database_url
|
|||||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||||
SESSION_STORE=postgres
|
SESSION_STORE=postgres
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
CACHE_URL_FILE=/run/secrets/cache_url
|
||||||
|
POSTGRES_USER=messenger
|
||||||
|
POSTGRES_PASSWORD=messenger_password
|
||||||
|
POSTGRES_DB=messenger_db
|
||||||
|
DATABASE_URL=postgresql+asyncpg://messenger:messenger_password@db:5432/messenger_db
|
||||||
|
REDIS_URL=redis://redis:6379/0
|
||||||
|
|||||||
@@ -1,14 +1,36 @@
|
|||||||
## Лабораторная 2
|
## Лабораторная 2
|
||||||
|
|
||||||
Автор / группа: TODO
|
Автор / группа: Долда Кирилл, БПИ2301
|
||||||
Целевая оценка (3/4/5): TODO
|
Целевая оценка (3/4/5): 5
|
||||||
Трек 5, если заявлен: TODO
|
Трек 5, если заявлен: Трек 2 - План запроса и восстановление
|
||||||
|
|
||||||
Что реализовано и что перенесено: TODO
|
## Что реализовано и что перенесено:
|
||||||
Команды запуска из чистого clone: TODO
|
* Реализован REST API мессенджера с хранением в PostgreSQL и сессиями в Redis.
|
||||||
Результаты проверок и ссылка на REPORT.md: TODO
|
* Перенесено из lab1: эндпоинты пользователей, чатов и сообщений, формат ошибок Error, X-Request-Id, пагинация, healthcheck, Dockerfile с непривилегированным пользователем и graceful shutdown.
|
||||||
Ограничения / известные ошибки: TODO
|
* Изменено: X-User-Id заменён на Bearer-токены (Basic только на /auth/sessions), хранилище переведено с in-memory словарей на PostgreSQL, добавлены миграции Alembic, хеширование паролей bcrypt, Redis для сессий с TTL и AOF, собственные тесты безопасности.
|
||||||
Источники и использование ИИ: TODO
|
|
||||||
|
## Команды запуска из чистого clone:
|
||||||
|
* cp .env.example .env
|
||||||
|
* docker compose up -d --build
|
||||||
|
* docker exec -it -u root -w /app mtusi_messenger_app alembic revision --autogenerate -m "create tables"
|
||||||
|
* docker exec -it -w /app mtusi_messenger_app alembic upgrade head
|
||||||
|
* make test
|
||||||
|
* pytest tests/test_security.py -v
|
||||||
|
* make explain-10k
|
||||||
|
* make explain-composite
|
||||||
|
* make explain-simple
|
||||||
|
* make backup-restore
|
||||||
|
|
||||||
|
## Результаты проверок и ссылка на REPORT.md:
|
||||||
|
make test — PASS: lab2 public API scenario.
|
||||||
|
pytest tests/test_security.py -v — 3/3 PASS.
|
||||||
|
make explain-10k — Index Scan, 0.22 мс.
|
||||||
|
Сравнение индексов на 80 000: составной 0.308 мс без сортировки, простой 8.200 мс, разница в 27 раз.
|
||||||
|
make backup-restore — 200 008 записей в основной и восстановленной базах, целостность подтверждена.
|
||||||
|
Выводы сохранены в evidence/ (explain_10k.txt, explain_composite.txt, explain_simple.txt, backup.sql)
|
||||||
|
|
||||||
|
## Источники и использование ИИ:
|
||||||
|
FastAPI, SQLAlchemy, asyncpg, Alembic, passlib[bcrypt], redis, psycopg2-binary, pytest. ИИ — помощь в разборе контракта.
|
||||||
|
|
||||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||||
- [ ] Контракт и публичные тесты не ослаблены.
|
- [ ] Контракт и публичные тесты не ослаблены.
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
на 3
|
||||||
|
|
||||||
|
Переход на новую аутентификацию: X-User-Id полностью удален из рабочих эндпоинтов. Везде используется Depends(get_current_user) (Bearer).
|
||||||
|
|
||||||
|
Сохранность данных (Persistence): Настроено через volumes в docker-compose.yml (postgres_data, redis_data). При перезапуске контейнеров (docker compose restart) данные и сессии не теряются.
|
||||||
|
|
||||||
|
PostgreSQL (Схема): В models/chat.py, user.py, message.py прописаны ForeignKey (с ondelete="CASCADE"), primary_key, unique=True для username. Миграции Alembic настроены и работают.
|
||||||
|
|
||||||
|
Атомарность создания чата: В routers/chats.py используется session.add(chat) + await session.flush(), затем добавление участников и один await session.commit(). Если упадет добавление участника, чат не создастся (откатится).
|
||||||
|
|
||||||
|
Basic только на логине: В routers/auth.py HTTPBasic используется только для POST /auth/sessions. Остальные — только HTTPBearer.
|
||||||
|
|
||||||
|
TTL и отзыв сессии: В security.py используется redis_client.setex(..., SESSION_TTL_SECONDS, ...). Логаут (DELETE /auth/sessions/current) физически удаляет токен из Redis.
|
||||||
|
|
||||||
|
Пароли: В security.py используется passlib с алгоритмом bcrypt.
|
||||||
|
|
||||||
|
на 4
|
||||||
|
|
||||||
|
1. Redis для сессий с TTL и инвалидацией
|
||||||
|
Где: security.py (redis_client.setex), docker-compose.yml (redis-server --appendonly yes).
|
||||||
|
|
||||||
|
Что сделано: Redis — источник истины для сессий. Включена персистентность AOF (Append Only File), поэтому сессии переживают перезапуск Redis. TTL настраивается через переменную окружения. Инвалидация (удаление) происходит при логауте. app/security.py
|
||||||
|
|
||||||
|
2. Параметризованные запросы, пул соединений, таймауты
|
||||||
|
Где: database.py (create_async_engine).
|
||||||
|
|
||||||
|
Что сделано: Используется SQLAlchemy (безопасный ORM, защита от SQL-инъекций по умолчанию). В create_async_engine прописаны pool_size=5, max_overflow=10, pool_timeout=30, pool_recycle=1800.
|
||||||
|
|
||||||
|
Гонка username: Решается на уровне БД (ограничение UNIQUE в PostgreSQL). Если два потока одновременно попытаются создать alice, один получит IntegrityError (который в идеале нужно перехватить и вернуть 409, но защита есть).
|
||||||
|
|
||||||
|
Rollback: Работает за счет транзакций SQLAlchemy (commit только в конце).
|
||||||
|
|
||||||
|
3. Индекс истории и пагинация
|
||||||
|
Где: models/message.py (Index("ix_messages_chat_created_id", ...)).
|
||||||
|
|
||||||
|
Что сделано: Составной индекс на (chat_id, created_at, id) создан.
|
||||||
|
|
||||||
|
Чего не хватает: В задании требуют провести EXPLAIN (ANALYZE, BUFFERS) на 10 000 сообщений, чтобы доказать, что база использует этот индекс, а не делает полный перебор (Seq Scan).
|
||||||
|
|
||||||
|
4. Автоматическая проверка expiry, logout, неверного пароля и недоступности Redis/БД
|
||||||
|
Где: Логика есть в коде (security.py, auth.py).
|
||||||
|
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
FROM python:3.13-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements-dev.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements-dev.txt
|
||||||
|
|
||||||
|
RUN useradd --create-home --shell /bin/bash appuser
|
||||||
|
|
||||||
|
COPY app/ app/
|
||||||
|
|
||||||
|
COPY alembic.ini .
|
||||||
|
COPY alembic/ alembic/
|
||||||
|
RUN chown -R appuser:appuser /app/alembic
|
||||||
|
|
||||||
|
USER appuser
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||||
|
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/live')" || exit 1
|
||||||
|
|
||||||
|
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080", "--timeout-graceful-shutdown", "10", "--reload"]
|
||||||
|
|
||||||
@@ -24,3 +24,62 @@ load:
|
|||||||
test-persistence:
|
test-persistence:
|
||||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
|
explain-10k:
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_db -c "EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = '22222222-2222-2222-2222-222222222222' ORDER BY created_at, id LIMIT 50 OFFSET 0;"
|
||||||
|
|
||||||
|
explain-composite:
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_db -c "EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = '66666666-6666-4666-8666-666666666666' ORDER BY created_at, id LIMIT 50 OFFSET 0;" | tee evidence/explain_composite.txt
|
||||||
|
|
||||||
|
explain-simple:
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_db -c "DROP INDEX IF EXISTS ix_messages_chat_created_id;"
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_db -c "CREATE INDEX ix_messages_chat_only ON messages (chat_id); ANALYZE messages;"
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_db -c "EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = '66666666-6666-4666-8666-666666666666' ORDER BY created_at, id LIMIT 50 OFFSET 0;" | tee evidence/explain_simple.txt
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_db -c "DROP INDEX ix_messages_chat_only;"
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_db -c "CREATE INDEX ix_messages_chat_created_id ON messages (chat_id, created_at, id);"
|
||||||
|
|
||||||
|
backup-restore:
|
||||||
|
@echo "Делаем бекап pg_dump"
|
||||||
|
time docker exec -it mtusi_messenger_db pg_dump -U messenger -d messenger_db > evidence/backup.sql
|
||||||
|
@echo "Создаем новую базу messenger_restore"
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d postgres -c "DROP DATABASE IF EXISTS messenger_restore;"
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d postgres -c "CREATE DATABASE messenger_restore;"
|
||||||
|
@echo "Копируем бекап в контейнер и восстанавливаем"
|
||||||
|
docker cp evidence/backup.sql mtusi_messenger_db:/tmp/
|
||||||
|
time docker exec -it mtusi_messenger_db psql -U messenger -d messenger_restore -f /tmp/backup.sql > /dev/null
|
||||||
|
@echo "В основной базе messenger_db:"
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_db -t -c "SELECT count(*) FROM messages;"
|
||||||
|
@echo "В восстановленной базе messenger_restore:"
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_restore -t -c "SELECT count(*) FROM messages;"
|
||||||
|
|
||||||
|
test-race:
|
||||||
|
@echo "Запускаем два одновременных запроса на регистрацию"
|
||||||
|
@RACE_USER="race_$$(date +%s)"; \
|
||||||
|
curl -s -o /dev/null -w "Запрос 1: %{http_code}\n" -X POST http://localhost:8080/api/v1/users -H "Content-Type: application/json" -d "{\"username\": \"$$RACE_USER\", \"display_name\": \"Race\", \"password\": \"secret1234567\"}" & \
|
||||||
|
curl -s -o /dev/null -w "Запрос 2: %{http_code}\n" -X POST http://localhost:8080/api/v1/users -H "Content-Type: application/json" -d "{\"username\": \"$$RACE_USER\", \"display_name\": \"Race\", \"password\": \"secret1234567\"}" & \
|
||||||
|
wait
|
||||||
|
|
||||||
|
test-redis:
|
||||||
|
@echo "Ставим Redis на паузу"
|
||||||
|
docker pause mtusi_messenger_redis
|
||||||
|
@echo "Запрос"
|
||||||
|
time curl -s -w "\nHTTP Статус: %{http_code}\n" http://localhost:8080/api/v1/users/me -H "Authorization: Bearer test_token"
|
||||||
|
@echo "Снимаем паузу"
|
||||||
|
docker unpause mtusi_messenger_redis
|
||||||
|
|
||||||
|
test-health-db:
|
||||||
|
@echo "Останавливаем БД"
|
||||||
|
docker compose stop db
|
||||||
|
@echo "Проверяем health ready"
|
||||||
|
curl -s -o /dev/null -w "HTTP Статус: %{http_code}\n" http://localhost:8080/health/ready
|
||||||
|
docker compose start db
|
||||||
|
|
||||||
|
test-health-redis:
|
||||||
|
@echo "Останавливаем"
|
||||||
|
docker compose stop redis
|
||||||
|
@echo "Проверяем health ожидая 503 "
|
||||||
|
curl -s -o /dev/null -w "HTTP Статус: %{http_code}\n" http://localhost:8080/health/ready
|
||||||
|
docker compose start redis
|
||||||
|
|
||||||
|
test-resilience:
|
||||||
|
$(PYTHON) -m pytest tests/test_resilience.py -v
|
||||||
@@ -1,37 +1,127 @@
|
|||||||
# Отчёт — лабораторная 2
|
# Отчёт — лабораторная 2
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Долда Кирилл, БПИ2301
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка: 5
|
||||||
- Commit/PR: TODO после публикации
|
- Использованные источники, библиотеки и помощь ИИ: FastAPI, SQLAlchemy, asyncpg, Alembic, passlib[bcrypt], redis, psycopg2-binary
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Docker Desktop + Python 3.13
|
||||||
|
|
||||||
|
Версии runtime/образов:
|
||||||
|
python:3.13-slim
|
||||||
|
postgres:16-alpine
|
||||||
|
redis:7-alpine
|
||||||
|
|
||||||
|
Python-пакеты: fastapi==0.115.0, uvicorn[standard]==0.52.4, pydantic==2.13.5, sqlalchemy[asyncio]==2.1.0, asyncpg==0.31.0, redis==6.2.0, passlib==1.7.4, bcrypt==4.1.2, alembic==1.14.0, psycopg2-binary, pytest==8.3.4
|
||||||
|
|
||||||
|
Сборка и запуск
|
||||||
|
docker compose up -d --build
|
||||||
|
|
||||||
|
Создание структры Alembic
|
||||||
|
docker exec -it mtusi_messenger_app alembic init alembic
|
||||||
|
|
||||||
|
Создаем файл миграции
|
||||||
|
docker exec -it -u root -w /app mtusi_messenger_app alembic revision --autogenerate -m "create tables"
|
||||||
|
|
||||||
|
Команда применения миграций Alembic
|
||||||
|
docker exec -it -w /app mtusi_messenger_app alembic upgrade head
|
||||||
|
|
||||||
|
Проверяем таблицы в БД
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_db -c "\dt"
|
||||||
|
|
||||||
|
Файл миграции для теста в 10к сообщений
|
||||||
|
docker exec -it -w /app mtusi_messenger_app alembic revision -m "seed explain test 10k"
|
||||||
|
|
||||||
|
Применяем миграцию
|
||||||
|
docker exec -it -w /app mtusi_messenger_app alembic upgrade head
|
||||||
|
|
||||||
|
Тестируем на 10к
|
||||||
|
make explain-10k
|
||||||
|
|
||||||
|
Создаем файл миграции для проверки EXPLAIN, Index (100к сообщений с разбиением на 3 таблицы 80к/10к/10к)
|
||||||
|
docker exec -it -w /app mtusi_messenger_app alembic revision -m "seed load test data"
|
||||||
|
|
||||||
|
Применяем миграцию
|
||||||
|
docker exec -it -w /app mtusi_messenger_app alembic upgrade head
|
||||||
|
|
||||||
|
Тестируем на составном индексе (сортировка по дате создания и айди, при поиске сообщений)
|
||||||
|
make explain-composite
|
||||||
|
|
||||||
|
Тестируем на обычном индексе (обычная сортировка чатов, без внутренней сортировки)
|
||||||
|
make explain-simple
|
||||||
|
|
||||||
|
Результаты выполнения в папке evidence
|
||||||
|
|
||||||
|
|
||||||
|
Заходим интерактивно в БД:
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_db
|
||||||
|
|
||||||
|
Тест с LIMIT 50:
|
||||||
|
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = '66666666-6666-4666-8666-666666666666' ORDER BY created_at, id LIMIT 50 OFFSET 0;
|
||||||
|
|
||||||
|
## Тесты
|
||||||
|
|
||||||
|
make test
|
||||||
|
pytest tests/test_security.py -v
|
||||||
|
make explain-10k
|
||||||
|
make explain-composite
|
||||||
|
make explain-simple
|
||||||
|
make backup-restore
|
||||||
|
|
||||||
|
## Безопасная остановка
|
||||||
|
|
||||||
|
Данные сохраняются в томах
|
||||||
|
|
||||||
|
docker compose down
|
||||||
|
|
||||||
|
Намеренное удаление контейнеров и томов
|
||||||
|
|
||||||
|
docker compose down -v
|
||||||
|
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Схема: клиент -> FastApi -> PostgreSQL + Redis с сессиями TTL
|
||||||
|
Источник истины: PostgreSQL. Внешние ключи с ondelete="CASCADE", уникальность username
|
||||||
|
Транзакционные границы: создание чата выполняется атомарно flush + commit
|
||||||
|
Сессии: Redis, токен secrets.token_urlsafe(32) с TTL.
|
||||||
|
Инвалидация при логауте — удаление из Redis. Персистентность Redis через --appendonly yes.
|
||||||
|
Что изменено: X-User-Id убран, теперь Bearer, хранилище переведено на PostgreSQL, добавлены миграции, хеширование bcrypt, Redis для сессий, собственные тесты безопасности.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
|----------------------------------|----------------------------------------------|----------------------------| --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Публичный smoke | make test | PASS: lab2 public API scenario |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Проверка структуры | make check | PASS: offline skeleton structure, local refs and Python syntax; |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| TTL, logout, неправильный пароль | pytest tests/test_security.py -v | PASS 3/3 |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| EXPLAIN на 10 000 сообщений | make explain-10k | ~0.22 мс | evidence/explain_10k.txt |
|
||||||
|
| Сравнение двух индексов | make explain-composite / make explain-simple | 0.3ms / 8.2 ms |
|
||||||
|
| Бекап, восстановление | make backup-restore | pg_dump -> messenger_restore -> 200 008 записей в обеих базах | evidence/backup.sql |
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
При выборке 50 сообщений из чата с 10 000 сообщений PostgreSQL использует Index Scan по индексу ix_messages_chat_created_id, время выполнения составляет 0.22 мс.
|
||||||
|
|
||||||
|
Составной индекс выполнил поиск - за 0.3 мс без сортировки, а простой индекс - за 8.2 мс с полной сортировкой 80 000 строк, что доказывает преимущество составного индекса
|
||||||
|
|
||||||
|
Гипотеза:
|
||||||
|
|
||||||
|
Составной индекс (chat_id, created_at, id) быстрее простого (chat_id), потому что избавляет от сортировки.
|
||||||
|
|
||||||
|
Методика: Замер с составным индексом на 80к -> удаление составного, создание простого -> замер -> возврат обратно
|
||||||
|
Бэкап через pg_dump -> заливка в новую БД messenger_restore -> сверка количества.
|
||||||
|
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| Тип индекса | Время | Buffers | Сортировка |
|
||||||
| TODO | TODO | TODO | TODO |
|
| Составной | 0.308 мс | shared hit=1 read=3 | Без сортировки |
|
||||||
|
| Простой | 8.200 мс | shared hit=1063 read=72 | Производилась |
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
Вывод: Составной индекс быстрее в 27 раз.
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
Ограничения:
|
||||||
|
|
||||||
|
На синтетических данных разница между индексами видна только на большом чате 80к, на малых 10к нивелируется.
|
||||||
+117
@@ -0,0 +1,117 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts
|
||||||
|
# Use forward slashes (/) also on windows to provide an os agnostic path
|
||||||
|
script_location = alembic
|
||||||
|
|
||||||
|
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||||
|
# Uncomment the line below if you want the files to be prepended with date and time
|
||||||
|
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||||
|
# for all available tokens
|
||||||
|
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||||
|
|
||||||
|
# sys.path path, will be prepended to sys.path if present.
|
||||||
|
# defaults to the current working directory.
|
||||||
|
prepend_sys_path = .
|
||||||
|
|
||||||
|
# timezone to use when rendering the date within the migration file
|
||||||
|
# as well as the filename.
|
||||||
|
# If specified, requires the python>=3.9 or backports.zoneinfo library.
|
||||||
|
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
|
||||||
|
# string value is passed to ZoneInfo()
|
||||||
|
# leave blank for localtime
|
||||||
|
# timezone =
|
||||||
|
|
||||||
|
# max length of characters to apply to the "slug" field
|
||||||
|
# truncate_slug_length = 40
|
||||||
|
|
||||||
|
# set to 'true' to run the environment during
|
||||||
|
# the 'revision' command, regardless of autogenerate
|
||||||
|
# revision_environment = false
|
||||||
|
|
||||||
|
# set to 'true' to allow .pyc and .pyo files without
|
||||||
|
# a source .py file to be detected as revisions in the
|
||||||
|
# versions/ directory
|
||||||
|
# sourceless = false
|
||||||
|
|
||||||
|
# version location specification; This defaults
|
||||||
|
# to alembic/versions. When using multiple version
|
||||||
|
# directories, initial revisions must be specified with --version-path.
|
||||||
|
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||||
|
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
|
||||||
|
|
||||||
|
# version path separator; As mentioned above, this is the character used to split
|
||||||
|
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||||
|
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||||
|
# Valid values for version_path_separator are:
|
||||||
|
#
|
||||||
|
# version_path_separator = :
|
||||||
|
# version_path_separator = ;
|
||||||
|
# version_path_separator = space
|
||||||
|
# version_path_separator = newline
|
||||||
|
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
|
||||||
|
|
||||||
|
# set to 'true' to search source files recursively
|
||||||
|
# in each "version_locations" directory
|
||||||
|
# new in Alembic version 1.10
|
||||||
|
# recursive_version_locations = false
|
||||||
|
|
||||||
|
# the output encoding used when revision files
|
||||||
|
# are written from script.py.mako
|
||||||
|
# output_encoding = utf-8
|
||||||
|
|
||||||
|
sqlalchemy.url = driver://user:pass@localhost/dbname
|
||||||
|
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
# post_write_hooks defines scripts or Python functions that are run
|
||||||
|
# on newly generated revision scripts. See the documentation for further
|
||||||
|
# detail and examples
|
||||||
|
|
||||||
|
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||||
|
# hooks = black
|
||||||
|
# black.type = console_scripts
|
||||||
|
# black.entrypoint = black
|
||||||
|
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
|
||||||
|
# hooks = ruff
|
||||||
|
# ruff.type = exec
|
||||||
|
# ruff.executable = %(here)s/.venv/bin/ruff
|
||||||
|
# ruff.options = --fix REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Logging configuration
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARNING
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARNING
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration.
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
from app.models.base import Base
|
||||||
|
from app.models.user import User
|
||||||
|
|
||||||
|
from app.models.chat import Chat, ChatMember
|
||||||
|
from app.models.message import Message
|
||||||
|
from app.config import DATABASE_URL
|
||||||
|
|
||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from sqlalchemy import engine_from_config
|
||||||
|
from sqlalchemy import pool
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
|
||||||
|
# this is the Alembic Config object, which provides
|
||||||
|
# access to the values within the .ini file in use.
|
||||||
|
config = context.config
|
||||||
|
config.set_main_option("sqlalchemy.url", DATABASE_URL.replace("+asyncpg", "+psycopg2"))
|
||||||
|
|
||||||
|
|
||||||
|
# Interpret the config file for Python logging.
|
||||||
|
# This line sets up loggers basically.
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
# add your model's MetaData object here
|
||||||
|
# for 'autogenerate' support
|
||||||
|
# from myapp import mymodel
|
||||||
|
# target_metadata = mymodel.Base.metadata
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
# other values from the config, defined by the needs of env.py,
|
||||||
|
# can be acquired:
|
||||||
|
# my_important_option = config.get_main_option("my_important_option")
|
||||||
|
# ... etc.
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
"""Run migrations in 'offline' mode.
|
||||||
|
|
||||||
|
This configures the context with just a URL
|
||||||
|
and not an Engine, though an Engine is acceptable
|
||||||
|
here as well. By skipping the Engine creation
|
||||||
|
we don't even need a DBAPI to be available.
|
||||||
|
|
||||||
|
Calls to context.execute() here emit the given string to the
|
||||||
|
script output.
|
||||||
|
|
||||||
|
"""
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
"""Run migrations in 'online' mode.
|
||||||
|
|
||||||
|
In this scenario we need to create an Engine
|
||||||
|
and associate a connection with the context.
|
||||||
|
|
||||||
|
"""
|
||||||
|
connectable = engine_from_config(
|
||||||
|
config.get_section(config.config_ini_section, {}),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
context.configure(
|
||||||
|
connection=connection, target_metadata=target_metadata
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"""create tables
|
||||||
|
|
||||||
|
Revision ID: b24373e3b620
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-10-24 06:54:22.471827
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = 'b24373e3b620'
|
||||||
|
down_revision: Union[str, None] = None
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('chats',
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('title', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_table('users',
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('username', sa.String(length=32), nullable=False),
|
||||||
|
sa.Column('display_name', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('password_hash', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
|
||||||
|
op.create_table('chat_members',
|
||||||
|
sa.Column('chat_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('user_id', sa.UUID(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'),
|
||||||
|
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('chat_id', 'user_id')
|
||||||
|
)
|
||||||
|
op.create_table('messages',
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('chat_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('sender_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('text', sa.Text(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'),
|
||||||
|
sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index('ix_messages_chat_created_id', 'messages', ['chat_id', 'created_at', 'id'], unique=False)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_index('ix_messages_chat_created_id', table_name='messages')
|
||||||
|
op.drop_table('messages')
|
||||||
|
op.drop_table('chat_members')
|
||||||
|
op.drop_index(op.f('ix_users_username'), table_name='users')
|
||||||
|
op.drop_table('users')
|
||||||
|
op.drop_table('chats')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""seed explain test 10k
|
||||||
|
|
||||||
|
Revision ID: bc35c1b6b748
|
||||||
|
Revises: f9b85be2b710
|
||||||
|
Create Date: 2026-10-24 07:04:09.294404
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = 'bc35c1b6b748'
|
||||||
|
down_revision: Union[str, None] = 'f9b85be2b710'
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.execute("""
|
||||||
|
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||||
|
VALUES ('11111111-1111-1111-1111-111111111111', 'explain_test', 'Test', 'hash', NOW())
|
||||||
|
ON CONFLICT DO NOTHING;
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
INSERT INTO chats (id, title, created_at)
|
||||||
|
VALUES ('22222222-2222-2222-2222-222222222222', 'Explain Chat', NOW())
|
||||||
|
ON CONFLICT DO NOTHING;
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
SELECT gen_random_uuid(), '22222222-2222-2222-2222-222222222222', '11111111-1111-1111-1111-111111111111', 'Message ' || i, NOW() - (i || ' minutes')::interval
|
||||||
|
FROM generate_series(1, 10000) AS i;
|
||||||
|
""")
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.execute("DELETE FROM messages WHERE chat_id = '22222222-2222-2222-2222-222222222222';")
|
||||||
|
op.execute("DELETE FROM chats WHERE id = '22222222-2222-2222-2222-222222222222';")
|
||||||
|
op.execute("DELETE FROM users WHERE id = '11111111-1111-1111-1111-111111111111';")
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
"""seed load test data
|
||||||
|
|
||||||
|
Revision ID: f9b85be2b710
|
||||||
|
Revises: b24373e3b620
|
||||||
|
Create Date: ...
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = 'f9b85be2b710'
|
||||||
|
down_revision: Union[str, None] = 'b24373e3b620'
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.execute("""
|
||||||
|
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||||
|
VALUES ('55555555-5555-4555-8555-555555555555', 'load_test', 'Load', 'hash', NOW())
|
||||||
|
ON CONFLICT DO NOTHING;
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
INSERT INTO chats (id, title, created_at) VALUES
|
||||||
|
('66666666-6666-4666-8666-666666666666', 'Big Chat', NOW()),
|
||||||
|
('77777777-7777-4777-8777-777777777777', 'Small Chat 1', NOW()),
|
||||||
|
('88888888-8888-4888-8888-888888888888', 'Small Chat 2', NOW())
|
||||||
|
ON CONFLICT DO NOTHING;
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
SELECT gen_random_uuid(), '66666666-6666-4666-8666-666666666666', '55555555-5555-4555-8555-555555555555', 'Big ' || i, NOW() - (i || ' minutes')::interval
|
||||||
|
FROM generate_series(1, 80000) AS i;
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
SELECT gen_random_uuid(), '77777777-7777-4777-8777-777777777777', '55555555-5555-4555-8555-555555555555', 'Small1 ' || i, NOW() - (i || ' minutes')::interval
|
||||||
|
FROM generate_series(1, 10000) AS i;
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
SELECT gen_random_uuid(), '88888888-8888-4888-8888-888888888888', '55555555-5555-4555-8555-555555555555', 'Small2 ' || i, NOW() - (i || ' minutes')::interval
|
||||||
|
FROM generate_series(1, 10000) AS i;
|
||||||
|
""")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.execute("""
|
||||||
|
DELETE FROM messages WHERE chat_id IN (
|
||||||
|
'66666666-6666-4666-8666-666666666666',
|
||||||
|
'77777777-7777-4777-8777-777777777777',
|
||||||
|
'88888888-8888-4888-8888-888888888888'
|
||||||
|
);
|
||||||
|
""")
|
||||||
|
op.execute("""
|
||||||
|
DELETE FROM chats WHERE id IN (
|
||||||
|
'66666666-6666-4666-8666-666666666666',
|
||||||
|
'77777777-7777-4777-8777-777777777777',
|
||||||
|
'88888888-8888-4888-8888-888888888888'
|
||||||
|
);
|
||||||
|
""")
|
||||||
|
op.execute("DELETE FROM users WHERE id = '55555555-5555-4555-8555-555555555555';")
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
DATABASE_URL = os.getenv(
|
||||||
|
"DATABASE_URL",
|
||||||
|
"postgresql+asyncpg://messenger:messenger_password@db:5432/messenger_db",
|
||||||
|
)
|
||||||
|
REDIS_URL = os.getenv("REDIS_URL", "redis://redis:6379/0")
|
||||||
|
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||||
|
|
||||||
|
CODE_MAP = {
|
||||||
|
400: "invalid_request",
|
||||||
|
401: "unauthorized",
|
||||||
|
404: "not_found",
|
||||||
|
409: "conflict",
|
||||||
|
413: "payload_too_large",
|
||||||
|
415: "unsupported_media_type",
|
||||||
|
429: "rate_limited",
|
||||||
|
503: "unavailable",
|
||||||
|
500: "internal_error",
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||||
|
from app.config import DATABASE_URL
|
||||||
|
|
||||||
|
engine = create_async_engine(
|
||||||
|
DATABASE_URL,
|
||||||
|
pool_size=5,
|
||||||
|
max_overflow=10,
|
||||||
|
pool_timeout=30,
|
||||||
|
pool_recycle=1800,
|
||||||
|
echo=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from app.database import async_session_maker
|
||||||
|
|
||||||
|
async def get_session():
|
||||||
|
async with async_session_maker() as session:
|
||||||
|
yield session
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
from fastapi import HTTPException, Request
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from app.config import CODE_MAP
|
||||||
|
|
||||||
|
|
||||||
|
def error_response(request: Request, status_code: int, code: str, message: str, extra_headers: dict = None):
|
||||||
|
request_id = getattr(request.state, "request_id", "unknown")
|
||||||
|
|
||||||
|
|
||||||
|
headers = {"X-Request-Id": request_id}
|
||||||
|
if extra_headers:
|
||||||
|
headers.update(extra_headers)
|
||||||
|
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=status_code,
|
||||||
|
content={
|
||||||
|
"error": {
|
||||||
|
"code": code,
|
||||||
|
"message": message,
|
||||||
|
"request_id": request_id,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||||
|
code = CODE_MAP.get(exc.status_code, "internal_error")
|
||||||
|
return error_response(request, exc.status_code, code, str(exc.detail), extra_headers=exc.headers)
|
||||||
|
|
||||||
|
|
||||||
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||||
|
return error_response(request, 400, "invalid_request", "Ошибка валидации данных")
|
||||||
|
|
||||||
|
async def internal_error_handler(request: Request, exc: Exception):
|
||||||
|
return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from app.middleware import RequestIdMiddleware
|
||||||
|
from app.exceptions import http_exception_handler, validation_exception_handler
|
||||||
|
from app.routers import health, users, chats, messages, auth
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="MTUSI Messenger",
|
||||||
|
version="1.1.0",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
app.add_middleware(RequestIdMiddleware)
|
||||||
|
|
||||||
|
app.add_exception_handler(HTTPException, http_exception_handler)
|
||||||
|
app.add_exception_handler(RequestValidationError, validation_exception_handler)
|
||||||
|
|
||||||
|
app.include_router(health.router)
|
||||||
|
app.include_router(users.router)
|
||||||
|
app.include_router(chats.router)
|
||||||
|
app.include_router(messages.router)
|
||||||
|
app.include_router(auth.router)
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import uuid as uuid_lib
|
||||||
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
|
||||||
|
|
||||||
|
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||||
|
async def dispatch(self, request, call_next):
|
||||||
|
request_id = str(uuid_lib.uuid4())
|
||||||
|
request.state.request_id = request_id
|
||||||
|
response = await call_next(request)
|
||||||
|
response.headers["X-Request-Id"] = request_id
|
||||||
|
return response
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import String, DateTime, ForeignKey, func
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID
|
||||||
|
|
||||||
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Chat(Base):
|
||||||
|
__tablename__ = "chats"
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||||
|
)
|
||||||
|
title: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ChatMember(Base):
|
||||||
|
__tablename__ = "chat_members"
|
||||||
|
|
||||||
|
chat_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("chats.id", ondelete="CASCADE"),
|
||||||
|
primary_key=True,
|
||||||
|
)
|
||||||
|
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("users.id", ondelete="CASCADE"),
|
||||||
|
primary_key=True,
|
||||||
|
)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import Text, DateTime, ForeignKey, Index, func
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID
|
||||||
|
|
||||||
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Message(Base):
|
||||||
|
__tablename__ = "messages"
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||||
|
)
|
||||||
|
chat_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("chats.id", ondelete="CASCADE"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
sender_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("users.id", ondelete="CASCADE"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
text: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now()
|
||||||
|
)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
Index("ix_messages_chat_created_id", "chat_id", "created_at", "id"),
|
||||||
|
)
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import String, DateTime, func
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID
|
||||||
|
|
||||||
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
__tablename__ = "users"
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||||
|
)
|
||||||
|
username: Mapped[str] = mapped_column(
|
||||||
|
String(32), unique=True, nullable=False, index=True
|
||||||
|
)
|
||||||
|
display_name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now()
|
||||||
|
)
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
def paginate(items: list, limit: int, cursor: str | None):
|
||||||
|
start = 0
|
||||||
|
if cursor is not None:
|
||||||
|
try:
|
||||||
|
start = int(cursor)
|
||||||
|
except ValueError:
|
||||||
|
start = 0
|
||||||
|
|
||||||
|
if start < 0:
|
||||||
|
start = 0
|
||||||
|
|
||||||
|
page = items[start : start + limit]
|
||||||
|
next_index = start + limit
|
||||||
|
|
||||||
|
if next_index < len(items):
|
||||||
|
next_cursor = str(next_index)
|
||||||
|
else:
|
||||||
|
next_cursor = None
|
||||||
|
|
||||||
|
return page, next_cursor
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import redis.asyncio as redis
|
||||||
|
from app.config import REDIS_URL
|
||||||
|
|
||||||
|
redis_client = redis.from_url(
|
||||||
|
REDIS_URL,
|
||||||
|
decode_responses=True,
|
||||||
|
socket_timeout=3,
|
||||||
|
socket_connect_timeout=3,
|
||||||
|
)
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from fastapi.security import HTTPBasic, HTTPBasicCredentials, HTTPAuthorizationCredentials
|
||||||
|
from pydantic import BaseModel, ConfigDict, field_serializer
|
||||||
|
from app.redis_client import redis_client
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from app.database import async_session_maker
|
||||||
|
from app.models.user import User
|
||||||
|
from app.security import verify_password, create_session, delete_session, bearer_scheme
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||||
|
security = HTTPBasic(realm="messenger")
|
||||||
|
|
||||||
|
|
||||||
|
class UserResponse(BaseModel):
|
||||||
|
id: uuid.UUID
|
||||||
|
username: str
|
||||||
|
display_name: str
|
||||||
|
created_at: datetime
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
@field_serializer('created_at')
|
||||||
|
def serialize_dt(self, dt: datetime):
|
||||||
|
return dt.isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
|
class SessionResponse(BaseModel):
|
||||||
|
token: str
|
||||||
|
token_type: str
|
||||||
|
expires_at: str
|
||||||
|
user: UserResponse
|
||||||
|
|
||||||
|
@field_serializer('expires_at')
|
||||||
|
def serialize_dt(self, dt_str: str):
|
||||||
|
if dt_str and dt_str.endswith("+00:00"):
|
||||||
|
return dt_str.replace("+00:00", "Z")
|
||||||
|
return dt_str
|
||||||
|
|
||||||
|
|
||||||
|
# Basic Auth в Bearer Token
|
||||||
|
@router.post("/sessions", status_code=201, response_model=SessionResponse)
|
||||||
|
async def login(credentials: HTTPBasicCredentials = Depends(security)):
|
||||||
|
async with async_session_maker() as session:
|
||||||
|
result = await session.execute(select(User).where(User.username == credentials.username))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not user or not verify_password(credentials.password, user.password_hash):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Incorrect username or password",
|
||||||
|
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
session_data = await create_session(user.id)
|
||||||
|
|
||||||
|
session_data["user"] = user
|
||||||
|
|
||||||
|
return session_data
|
||||||
|
|
||||||
|
@router.delete("/sessions/current", status_code=204)
|
||||||
|
async def logout(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)):
|
||||||
|
if not credentials:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Not authenticated",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
token = credentials.credentials
|
||||||
|
|
||||||
|
user_id = await redis_client.get(f"session:{token}")
|
||||||
|
if not user_id:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid or expired token",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
await delete_session(token)
|
||||||
|
return None
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
from pydantic import BaseModel, Field, field_validator, ConfigDict, field_serializer
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from app.models.chat import Chat, ChatMember
|
||||||
|
from app.models.user import User
|
||||||
|
from app.security import get_current_user
|
||||||
|
from app.dependencies import get_session
|
||||||
|
from app.pagination import paginate
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||||
|
|
||||||
|
|
||||||
|
class CreateChat(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("member_ids")
|
||||||
|
@classmethod
|
||||||
|
def unique_members(cls, v):
|
||||||
|
if len(set(v)) != len(v):
|
||||||
|
raise ValueError("member_ids должны быть уникальными")
|
||||||
|
return v
|
||||||
|
|
||||||
|
class ChatResponse(BaseModel):
|
||||||
|
id: uuid.UUID
|
||||||
|
title: str
|
||||||
|
member_ids: list[uuid.UUID]
|
||||||
|
created_at: datetime
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
@field_serializer('created_at')
|
||||||
|
def serialize_dt(self, dt: datetime):
|
||||||
|
return dt.isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", status_code=201)
|
||||||
|
async def create_chat(
|
||||||
|
payload: CreateChat,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
session: AsyncSession = Depends(get_session)
|
||||||
|
):
|
||||||
|
if str(user.id) not in payload.member_ids:
|
||||||
|
raise HTTPException(status_code=400, detail="Пользователь должен быть участником чата")
|
||||||
|
|
||||||
|
for member_id in payload.member_ids:
|
||||||
|
result = await session.execute(select(User).where(User.id == member_id))
|
||||||
|
if not result.scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=400, detail=f"несуществующий пользователь: {member_id}")
|
||||||
|
|
||||||
|
chat = Chat(title=payload.title)
|
||||||
|
session.add(chat)
|
||||||
|
await session.flush()
|
||||||
|
|
||||||
|
for member_id in payload.member_ids:
|
||||||
|
session.add(ChatMember(chat_id=chat.id, user_id=member_id))
|
||||||
|
|
||||||
|
await session.commit()
|
||||||
|
await session.refresh(chat)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": chat.id,
|
||||||
|
"title": chat.title,
|
||||||
|
"member_ids": payload.member_ids,
|
||||||
|
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{chat_id}")
|
||||||
|
async def get_chat(
|
||||||
|
chat_id: str,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
session: AsyncSession = Depends(get_session)
|
||||||
|
):
|
||||||
|
result = await session.execute(select(Chat).where(Chat.id == chat_id))
|
||||||
|
chat = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not chat:
|
||||||
|
raise HTTPException(status_code=404, detail="чат не найден")
|
||||||
|
|
||||||
|
result = await session.execute(
|
||||||
|
select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user.id)
|
||||||
|
)
|
||||||
|
if not result.scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=404, detail="чат не найден")
|
||||||
|
|
||||||
|
result = await session.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat.id))
|
||||||
|
member_ids = []
|
||||||
|
for row in result.all():
|
||||||
|
user_id = row[0]
|
||||||
|
member_ids.append(str(user_id))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": chat.id,
|
||||||
|
"title": chat.title,
|
||||||
|
"member_ids": member_ids,
|
||||||
|
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
async def list_chats(
|
||||||
|
limit: int = 20,
|
||||||
|
cursor: str | None = None,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
session: AsyncSession = Depends(get_session)
|
||||||
|
):
|
||||||
|
if limit < 1 or limit > 100:
|
||||||
|
raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100")
|
||||||
|
|
||||||
|
result = await session.execute(
|
||||||
|
select(Chat)
|
||||||
|
.join(ChatMember, Chat.id == ChatMember.chat_id)
|
||||||
|
.where(ChatMember.user_id == user.id)
|
||||||
|
.order_by(Chat.created_at, Chat.id)
|
||||||
|
)
|
||||||
|
chats = result.scalars().all()
|
||||||
|
|
||||||
|
my_chats = []
|
||||||
|
for chat in chats:
|
||||||
|
result = await session.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat.id))
|
||||||
|
member_ids = []
|
||||||
|
for row in result.all():
|
||||||
|
user_id = row[0]
|
||||||
|
member_ids.append(str(user_id))
|
||||||
|
|
||||||
|
my_chats.append({
|
||||||
|
"id": chat.id,
|
||||||
|
"title": chat.title,
|
||||||
|
"member_ids": member_ids,
|
||||||
|
"created_at": chat.created_at.isoformat().replace("+00:00", "Z"),
|
||||||
|
})
|
||||||
|
|
||||||
|
page, next_cursor = paginate(my_chats, limit, cursor)
|
||||||
|
return {"items": page, "next_cursor": next_cursor}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from sqlalchemy import text
|
||||||
|
from app.database import async_session_maker
|
||||||
|
from app.redis_client import redis_client
|
||||||
|
|
||||||
|
|
||||||
|
router = APIRouter(tags=["health"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health/live")
|
||||||
|
def live():
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health/ready")
|
||||||
|
async def ready():
|
||||||
|
try:
|
||||||
|
async with async_session_maker() as session:
|
||||||
|
await session.execute(text("SELECT 1"))
|
||||||
|
|
||||||
|
await redis_client.ping()
|
||||||
|
|
||||||
|
return {"status": "ok"}
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=503, detail="unavailable")
|
||||||
|
|
||||||
|
@router.get("/")
|
||||||
|
def home():
|
||||||
|
return {
|
||||||
|
"service": "MTUSI Messenger",
|
||||||
|
"version": "1.1.0",
|
||||||
|
"docs": "/docs",
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
from pydantic import BaseModel, Field, ConfigDict, field_serializer
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from app.models.message import Message
|
||||||
|
from app.models.chat import Chat, ChatMember
|
||||||
|
from app.models.user import User
|
||||||
|
from app.security import get_current_user
|
||||||
|
from app.dependencies import get_session
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"])
|
||||||
|
|
||||||
|
|
||||||
|
class CreateMessage(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
text: str = Field(min_length=1, max_length=4000)
|
||||||
|
|
||||||
|
|
||||||
|
class MessageResponse(BaseModel):
|
||||||
|
id: uuid.UUID
|
||||||
|
chat_id: uuid.UUID
|
||||||
|
sender_id: uuid.UUID
|
||||||
|
text: str
|
||||||
|
created_at: datetime
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
@field_serializer('created_at')
|
||||||
|
def serialize_dt(self, dt: datetime):
|
||||||
|
return dt.isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
|
async def check_chat_access(chat_id: str, user_id: uuid.UUID, session: AsyncSession):
|
||||||
|
chat = await session.get(Chat, chat_id)
|
||||||
|
if not chat:
|
||||||
|
raise HTTPException(status_code=404, detail="чат не найден")
|
||||||
|
|
||||||
|
result = await session.execute(
|
||||||
|
select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user_id)
|
||||||
|
)
|
||||||
|
if not result.scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=404, detail="чат не найден")
|
||||||
|
return chat
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", status_code=201, response_model=MessageResponse)
|
||||||
|
async def create_message(
|
||||||
|
chat_id: str,
|
||||||
|
payload: CreateMessage,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
session: AsyncSession = Depends(get_session)
|
||||||
|
):
|
||||||
|
await check_chat_access(chat_id, user.id, session)
|
||||||
|
|
||||||
|
message = Message(
|
||||||
|
chat_id=chat_id,
|
||||||
|
sender_id=user.id,
|
||||||
|
text=payload.text
|
||||||
|
)
|
||||||
|
session.add(message)
|
||||||
|
await session.commit()
|
||||||
|
await session.refresh(message)
|
||||||
|
return message
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
async def list_messages(
|
||||||
|
chat_id: str,
|
||||||
|
limit: int = 50,
|
||||||
|
cursor: str | None = None,
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
session: AsyncSession = Depends(get_session)
|
||||||
|
):
|
||||||
|
if limit < 1 or limit > 100:
|
||||||
|
raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100")
|
||||||
|
|
||||||
|
await check_chat_access(chat_id, user.id, session)
|
||||||
|
|
||||||
|
|
||||||
|
offset = int(cursor) if cursor else 0
|
||||||
|
|
||||||
|
result = await session.execute(
|
||||||
|
select(Message)
|
||||||
|
.where(Message.chat_id == chat_id)
|
||||||
|
.order_by(Message.created_at, Message.id)
|
||||||
|
.limit(limit + 1)
|
||||||
|
.offset(offset)
|
||||||
|
)
|
||||||
|
msgs = result.scalars().all()
|
||||||
|
|
||||||
|
has_next = len(msgs) > limit
|
||||||
|
if has_next:
|
||||||
|
msgs = msgs[:limit]
|
||||||
|
|
||||||
|
my_messages = [
|
||||||
|
{
|
||||||
|
"id": m.id,
|
||||||
|
"chat_id": m.chat_id,
|
||||||
|
"sender_id": m.sender_id,
|
||||||
|
"text": m.text,
|
||||||
|
"created_at": m.created_at.isoformat().replace("+00:00", "Z"),
|
||||||
|
} for m in msgs
|
||||||
|
]
|
||||||
|
|
||||||
|
next_cursor = str(offset + limit) if has_next else None
|
||||||
|
return {"items": my_messages, "next_cursor": next_cursor}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
from pydantic import BaseModel, Field, ConfigDict, field_serializer
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from app.models.user import User
|
||||||
|
from app.security import get_password_hash, get_current_user
|
||||||
|
from app.dependencies import get_session
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||||
|
|
||||||
|
class CreateUser(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||||
|
display_name: str = Field(min_length=1, max_length=100)
|
||||||
|
password: str = Field(min_length=5, max_length=128)
|
||||||
|
|
||||||
|
class UserResponse(BaseModel):
|
||||||
|
id: uuid.UUID
|
||||||
|
username: str
|
||||||
|
display_name: str
|
||||||
|
created_at: datetime
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
@field_serializer('created_at')
|
||||||
|
def serialize_dt(self, dt: datetime):
|
||||||
|
return dt.isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
@router.post("", status_code=201, response_model=UserResponse)
|
||||||
|
async def register_user(payload: CreateUser, session: AsyncSession = Depends(get_session)):
|
||||||
|
result = await session.execute(select(User).where(User.username == payload.username))
|
||||||
|
if result.scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=409, detail="Имя пользователя уже существует")
|
||||||
|
|
||||||
|
user = User(
|
||||||
|
username=payload.username,
|
||||||
|
display_name=payload.display_name,
|
||||||
|
password_hash=get_password_hash(payload.password)
|
||||||
|
)
|
||||||
|
session.add(user)
|
||||||
|
|
||||||
|
try:
|
||||||
|
await session.commit()
|
||||||
|
except IntegrityError:
|
||||||
|
await session.rollback()
|
||||||
|
raise HTTPException(status_code=409, detail="Имя пользователя уже существует")
|
||||||
|
|
||||||
|
await session.refresh(user)
|
||||||
|
return user
|
||||||
|
|
||||||
|
@router.get("/me", response_model=UserResponse)
|
||||||
|
async def current_user(user: User = Depends(get_current_user)):
|
||||||
|
return user
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import secrets
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
from passlib.context import CryptContext
|
||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||||
|
from sqlalchemy import select
|
||||||
|
from app.database import async_session_maker
|
||||||
|
from app.models.user import User
|
||||||
|
from app.redis_client import redis_client
|
||||||
|
from app.config import SESSION_TTL_SECONDS
|
||||||
|
|
||||||
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
bearer_scheme = HTTPBearer(auto_error=False)
|
||||||
|
|
||||||
|
def get_password_hash(password: str) -> str:
|
||||||
|
return pwd_context.hash(password)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(plain: str, hashed: str) -> bool:
|
||||||
|
return pwd_context.verify(plain, hashed)
|
||||||
|
|
||||||
|
|
||||||
|
async def create_session(user_id: str) -> dict:
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||||
|
|
||||||
|
await redis_client.setex(
|
||||||
|
name=f"session:{token}",
|
||||||
|
time=SESSION_TTL_SECONDS,
|
||||||
|
value=str(user_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"token": token,
|
||||||
|
"token_type": "Bearer",
|
||||||
|
"expires_at": expires_at.isoformat().replace("+00:00", "Z"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def delete_session(token: str) -> None:
|
||||||
|
await redis_client.delete(f"session:{token}")
|
||||||
|
|
||||||
|
|
||||||
|
async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)):
|
||||||
|
if not credentials:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Not authenticated",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
token = credentials.credentials
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
user_id = await redis_client.get(f"session:{token}")
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||||
|
detail="Внутренняя ошибка сервера"
|
||||||
|
)
|
||||||
|
|
||||||
|
if not user_id:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid or expired token",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
async with async_session_maker() as session:
|
||||||
|
result = await session.execute(select(User).where(User.id == user_id))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="User not found",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
return user
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import threading
|
||||||
|
|
||||||
|
users_lock = threading.Lock()
|
||||||
|
messages_lock = threading.Lock()
|
||||||
|
|
||||||
|
users_by_id: dict[str, dict] = {}
|
||||||
|
users_by_username: dict[str, dict] = {}
|
||||||
|
chats_by_id: dict[str, dict] = {}
|
||||||
|
messages_by_chat: dict[str, list[dict]] = {}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
container_name: mtusi_messenger_db
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB}
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
container_name: mtusi_messenger_redis
|
||||||
|
command: redis-server --appendonly yes
|
||||||
|
volumes:
|
||||||
|
- redis_data:/data
|
||||||
|
ports:
|
||||||
|
- "6379:6379"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
app:
|
||||||
|
build: .
|
||||||
|
container_name: mtusi_messenger_app
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: ${DATABASE_URL}
|
||||||
|
REDIS_URL: ${REDIS_URL}
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS}
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:8080:8080"
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
volumes:
|
||||||
|
- ./app:/app/app
|
||||||
|
- ./alembic:/app/alembic
|
||||||
|
- ./alembic.ini:/app/alembic.ini
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
redis_data:
|
||||||
+200294
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
|||||||
|
QUERY PLAN
|
||||||
|
-----------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=0.42..5.54 rows=50 width=66) (actual time=0.103..0.111 rows=50 loops=1)
|
||||||
|
Buffers: shared hit=4
|
||||||
|
-> Index Scan using ix_messages_chat_created_id on messages (cost=0.42..8222.03 rows=80203 width=66) (actual time=0.102..0.107 rows=50 loops=1)
|
||||||
|
Index Cond: (chat_id = '66666666-6666-4666-8666-666666666666'::uuid)
|
||||||
|
Buffers: shared hit=4
|
||||||
|
Planning:
|
||||||
|
Buffers: shared hit=107
|
||||||
|
Planning Time: 0.865 ms
|
||||||
|
Execution Time: 0.168 ms
|
||||||
|
(9 rows)
|
||||||
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
QUERY PLAN
|
||||||
|
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=6279.67..6285.42 rows=50 width=66) (actual time=7.323..8.152 rows=50 loops=1)
|
||||||
|
Buffers: shared hit=1063 read=72
|
||||||
|
-> Gather Merge (cost=6279.67..11696.05 rows=47099 width=66) (actual time=7.322..8.148 rows=50 loops=1)
|
||||||
|
Workers Planned: 1
|
||||||
|
Workers Launched: 1
|
||||||
|
Buffers: shared hit=1063 read=72
|
||||||
|
-> Sort (cost=5279.66..5397.40 rows=47099 width=66) (actual time=6.368..6.368 rows=26 loops=2)
|
||||||
|
Sort Key: created_at, id
|
||||||
|
Sort Method: top-N heapsort Memory: 38kB
|
||||||
|
Buffers: shared hit=1063 read=72
|
||||||
|
Worker 0: Sort Method: top-N heapsort Memory: 38kB
|
||||||
|
-> Parallel Index Scan using ix_messages_chat_only on messages (cost=0.42..3715.06 rows=47099 width=66) (actual time=0.031..2.837 rows=40000 loops=2)
|
||||||
|
--More-- ␍ ␍ Index Cond: (chat_id = '66666666-6666-4666-8666-66666666666--More-- ␍ ␍6'::uuid)
|
||||||
|
--More-- ␍ ␍ Buffers: shared hit=1048 read=72
|
||||||
|
--More-- ␍ ␍ Planning:
|
||||||
|
--More-- ␍ ␍ Buffers: shared hit=98 read=1
|
||||||
|
--More-- ␍ ␍ Planning Time: 0.335 ms
|
||||||
|
--More-- ␍ ␍ Execution Time: 8.200 ms
|
||||||
|
--More-- ␍ ␍(18 rows)
|
||||||
|
--More-- ␍ ␍
|
||||||
@@ -1,2 +1,13 @@
|
|||||||
# Only for full OpenAPI/JSON Schema validation; HTTP tests use stdlib.
|
# Only for full OpenAPI/JSON Schema validation; HTTP tests use stdlib.
|
||||||
openapi-spec-validator==0.7.2
|
openapi-spec-validator==0.7.2
|
||||||
|
pytest==8.3.4
|
||||||
|
fastapi==0.115.0
|
||||||
|
uvicorn[standard]==0.52.4
|
||||||
|
pydantic==2.13.5
|
||||||
|
asyncpg==0.31.0
|
||||||
|
sqlalchemy[asyncio]==2.1.0
|
||||||
|
redis==6.2.0
|
||||||
|
passlib==1.7.4
|
||||||
|
bcrypt==4.1.2
|
||||||
|
alembic==1.14.0
|
||||||
|
psycopg2-binary
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from pydantic import BaseModel, Field, field_validator, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class CreateChat(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("member_ids")
|
||||||
|
@classmethod
|
||||||
|
def unique_members(cls, v):
|
||||||
|
if len(set(v)) != len(v):
|
||||||
|
raise ValueError("member_ids должны быть уникальными")
|
||||||
|
return v
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
from pydantic import BaseModel, Field, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class CreateMessage(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
text: str = Field(min_length=1, max_length=4000)
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
from pydantic import BaseModel, Field, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class CreateUser(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||||
|
display_name: str = Field(min_length=1, max_length=100)
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||||
|
VALUES ('11111111-1111-1111-1111-111111111111', 'explain_test', 'Test', 'hash', NOW());
|
||||||
|
|
||||||
|
INSERT INTO chats (id, title, created_at)
|
||||||
|
VALUES ('22222222-2222-2222-2222-222222222222', 'Explain Chat', NOW());
|
||||||
|
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
SELECT
|
||||||
|
gen_random_uuid(),
|
||||||
|
'22222222-2222-2222-2222-222222222222',
|
||||||
|
'11111111-1111-1111-1111-111111111111',
|
||||||
|
'Message ' || i,
|
||||||
|
NOW() - (i || ' minutes')::interval
|
||||||
|
FROM generate_series(1, 10000) AS i;
|
||||||
|
|
||||||
|
Команды для теста
|
||||||
|
EXPLAIN (ANALYZE, BUFFERS)
|
||||||
|
SELECT * FROM messages
|
||||||
|
WHERE chat_id = '22222222-2222-2222-2222-222222222222'
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT 50;
|
||||||
|
|
||||||
|
Применить миграции к пустому volume (с нуля)
|
||||||
|
Задача: Показать, что база данных создается с нуля одной командой.
|
||||||
|
|
||||||
|
Удалить docker-compose down -v
|
||||||
|
Запустить docker-compose up -d --build
|
||||||
|
|
||||||
|
Применяем миграции (структура + данные):
|
||||||
|
docker exec -it -w /app mtusi_messenger_app alembic upgrade head
|
||||||
|
|
||||||
|
Проверяем, что таблицы есть:
|
||||||
|
docker exec -it mtusi_messenger_db psql -U messenger -d messenger_db -c "\dt"
|
||||||
|
curl -s http://localhost:8080/api/v1/users/me -H "Authorization: Bearer токен"
|
||||||
|
|
||||||
|
Делаем логаут проверяет корректность логина
|
||||||
|
|
||||||
|
curl -s http://localhost:8080/api/v1/users/me -H "Authorization: Bearer ВСТАВЬ_ТОКЕН"
|
||||||
|
Открываем docker-compose.yml и временно поменяй SESSION_TTL_SECONDS на 2:
|
||||||
|
|
||||||
|
docker compose up -d app
|
||||||
|
|
||||||
|
Роль Redis: Покажи в docker-compose.yml флаг --appendonly yes и в security.py вызов redis_client.setex(...).
|
||||||
|
План SQL: Покажи вывод make explain-10k (или explain-composite), где видно Index Scan и время выполнения.
|
||||||
|
Ошибка зависимости: Останови Redis (docker compose stop redis), попробуй залогиниться. Сервер вернет 503 или 500, но не пустит анонимного пользователя. (Не забудь потом запустить docker compose start redis).
|
||||||
|
Показать сравнение индексов и бэкап.
|
||||||
|
|
||||||
|
Что делать:
|
||||||
|
|
||||||
|
Запусти make explain-composite (замер с составным индексом).
|
||||||
|
Запусти make explain-simple (замер с простым индексом).
|
||||||
|
|
||||||
|
Мгновенно удаляет все сессии редиса
|
||||||
|
docker exec -it mtusi_messenger_redis redis-cli FLUSHALL
|
||||||
|
|
||||||
|
перезапуск редиса
|
||||||
|
docker compose restart redis
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import requests
|
||||||
|
|
||||||
|
BASE_URL = "http://localhost:8080"
|
||||||
|
|
||||||
|
|
||||||
|
def test_postgres_down_returns_503():
|
||||||
|
subprocess.run(["docker", "compose", "stop", "db"], check=True)
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = requests.get(f"{BASE_URL}/health/ready")
|
||||||
|
assert resp.status_code == 503, f"Ожидался 503, получен {resp.status_code}"
|
||||||
|
finally:
|
||||||
|
subprocess.run(["docker", "compose", "start", "db"], check=True)
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_redis_down_returns_500_json():
|
||||||
|
subprocess.run(["docker", "pause", "mtusi_messenger_redis"], check=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
headers = {"Authorization": "Bearer test_token"}
|
||||||
|
resp = requests.get(f"{BASE_URL}/api/v1/users/me", headers=headers)
|
||||||
|
|
||||||
|
assert resp.status_code == 500, f"Ожидался 500, получен {resp.status_code}"
|
||||||
|
body = resp.json()
|
||||||
|
assert body["error"]["code"] == "internal_error", "Неверный код ошибки"
|
||||||
|
assert "request_id" in body["error"], "Нет request_id"
|
||||||
|
finally:
|
||||||
|
subprocess.run(["docker", "unpause", "mtusi_messenger_redis"], check=True)
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import pytest
|
||||||
|
import requests
|
||||||
|
import time
|
||||||
|
|
||||||
|
BASE_URL = "http://localhost:8080"
|
||||||
|
|
||||||
|
|
||||||
|
def register_and_login(username, password):
|
||||||
|
requests.post(f"{BASE_URL}/api/v1/users", json={
|
||||||
|
"username": username, "display_name": "Test", "password": password
|
||||||
|
})
|
||||||
|
|
||||||
|
resp = requests.post(f"{BASE_URL}/api/v1/auth/sessions", auth=(username, password))
|
||||||
|
return resp.json()["token"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_wrong_password():
|
||||||
|
username = "test_wrong_pass"
|
||||||
|
password = "valid_password_123"
|
||||||
|
requests.post(f"{BASE_URL}/api/v1/users", json={
|
||||||
|
"username": username, "display_name": "Test", "password": password
|
||||||
|
})
|
||||||
|
|
||||||
|
resp = requests.post(f"{BASE_URL}/api/v1/auth/sessions", auth=(username, "wrong_password"))
|
||||||
|
assert resp.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_logout():
|
||||||
|
token = register_and_login("test_logout", "valid_password_123")
|
||||||
|
headers = {"Authorization": f"Bearer {token}"}
|
||||||
|
assert requests.get(f"{BASE_URL}/api/v1/users/me", headers=headers).status_code == 200
|
||||||
|
assert requests.delete(f"{BASE_URL}/api/v1/auth/sessions/current", headers=headers).status_code == 204
|
||||||
|
assert requests.get(f"{BASE_URL}/api/v1/users/me", headers=headers).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_expiry():
|
||||||
|
token = register_and_login("test_expiry", "valid_password_123")
|
||||||
|
headers = {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
assert requests.get(f"{BASE_URL}/api/v1/users/me", headers=headers).status_code == 200
|
||||||
|
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
assert requests.get(f"{BASE_URL}/api/v1/users/me", headers=headers).status_code == 401
|
||||||
Reference in New Issue
Block a user