lab2: PostgreSQL persistence, Argon2id sessions, Compose stack (grade 3)
This commit is contained in:
+32
-20
@@ -1,20 +1,32 @@
|
|||||||
.git
|
.git
|
||||||
.github
|
.github
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
secrets
|
.venv
|
||||||
certs
|
venv
|
||||||
volumes
|
__pycache__
|
||||||
data
|
*.pyc
|
||||||
backups
|
*.pyo
|
||||||
*.key
|
*.pyd
|
||||||
*.pem
|
.mypy_cache
|
||||||
*.p12
|
.ruff_cache
|
||||||
*.pfx
|
.pytest_cache
|
||||||
*.jks
|
secrets
|
||||||
.venv
|
certs
|
||||||
__pycache__
|
volumes
|
||||||
node_modules
|
data
|
||||||
evidence
|
backups
|
||||||
.DS_Store
|
tests
|
||||||
|
scripts
|
||||||
|
examples
|
||||||
|
contracts
|
||||||
|
infra
|
||||||
|
evidence
|
||||||
|
output
|
||||||
|
README.md
|
||||||
|
COURSE.md
|
||||||
|
CONTRIBUTING.md
|
||||||
|
MAINTAINERS.md
|
||||||
|
REPORT.md
|
||||||
|
*.md
|
||||||
Executable
+27
@@ -0,0 +1,27 @@
|
|||||||
|
FROM python:3.12-slim AS runtime
|
||||||
|
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
PIP_NO_CACHE_DIR=1 \
|
||||||
|
APP_HOST=0.0.0.0 \
|
||||||
|
APP_PORT=8080
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt ./
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY src ./src
|
||||||
|
|
||||||
|
# непривилегированный пользователь
|
||||||
|
RUN useradd --create-home --shell /usr/sbin/nologin appuser \
|
||||||
|
&& chown -R appuser:appuser /app
|
||||||
|
USER appuser
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||||
|
CMD python -c "import urllib.request,sys; \
|
||||||
|
sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health/live', timeout=2).status==200 else 1)"
|
||||||
|
|
||||||
|
CMD ["python", "-m", "src.main"]
|
||||||
@@ -1,37 +1,155 @@
|
|||||||
# Отчёт — лабораторная 2
|
# Отчёт — лабораторная 2
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Кропивка, БВТ2303
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка: 3 (уровень 3)
|
||||||
- Commit/PR: TODO после публикации
|
- Commit/PR: ветка `solution/БВТ-23-Кропивка`, PR после финального push
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Использованные источники, библиотеки и помощь ИИ: FastAPI 0.115.0, Uvicorn 0.30.6, Pydantic 2.9.2, psycopg 3.2.3, psycopg-pool 3.2.3, Alembic 1.13.3, argon2-cffi 23.1.0, PostgreSQL 16.4-alpine, python:3.12-slim. При подготовке решения использовался ассистент (LLM) для генерации черновика кода и объяснения контракта; итоговый код проверен публичным smoke, тестом сохранности и вручную.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Prerequisites:
|
||||||
|
|
||||||
|
- Docker 29.2.1 (Docker Desktop для Windows + WSL2)
|
||||||
|
- Python 3.9+ (только для запуска тестов; приложение работает в контейнере)
|
||||||
|
- Git
|
||||||
|
|
||||||
|
Шаги:
|
||||||
|
|
||||||
|
1. Клонировать репозиторий и перейти в него.
|
||||||
|
2. Создать локальный `.env` из примера:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
Заполнить:
|
||||||
|
```
|
||||||
|
APP_HOST=0.0.0.0
|
||||||
|
APP_PORT=8080
|
||||||
|
APP_ENV=lab
|
||||||
|
SESSION_TTL_SECONDS=3600
|
||||||
|
POSTGRES_USER=messenger
|
||||||
|
POSTGRES_PASSWORD=changeme_local_only
|
||||||
|
POSTGRES_DB=messenger
|
||||||
|
DATABASE_URL=postgresql://messenger:changeme_local_only@postgres:5432/messenger
|
||||||
|
SESSION_STORE=postgres
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Поднять стек:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose --env-file .env up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
Compose:
|
||||||
|
- `postgres` (образ `postgres:16.4-alpine`, named volume `mtusi_lab2_postgres_data`, публикуется только на `127.0.0.1:5433`),
|
||||||
|
- `api` (сборка из локального `Dockerfile`, слушает `127.0.0.1:8080`).
|
||||||
|
|
||||||
|
`depends_on: condition: service_healthy` гарантирует, что API стартует только после готовности Postgres. Миграции применяются в `CMD` контейнера: `alembic upgrade head && exec python -m src.main`.
|
||||||
|
|
||||||
|
4. Дождаться готовности:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose ps
|
||||||
|
```
|
||||||
|
|
||||||
|
Ожидаемо: оба сервиса `Up (... healthy)`.
|
||||||
|
|
||||||
|
5. Прогнать публичный smoke и тест сохранности:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make test BASE_URL=http://localhost:8080
|
||||||
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://localhost:8080
|
||||||
|
```
|
||||||
|
|
||||||
|
6. Остановить:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose --env-file .env down
|
||||||
|
```
|
||||||
|
|
||||||
|
**Данные сохраняются** в named volume `mtusi_lab2_postgres_data` и переживут следующий `up`.
|
||||||
|
|
||||||
|
**Безопасная остановка** — `docker compose down` (без `-v`). Флаг `-v` удаляет volumes и все данные.
|
||||||
|
|
||||||
|
**Намеренное удаление учебных данных:**
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose --env-file .env down -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Используется осознанно, только когда нужен чистый стенд.
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
- **Процессы.** Один API-процесс (Uvicorn + FastAPI) + PostgreSQL. API слушает `0.0.0.0:8080` внутри контейнера, публикуется на `127.0.0.1:8080` хоста. Postgres слушает `5432` внутри Compose-сети, публикуется на `127.0.0.1:5433` (5432 занят локально).
|
||||||
|
- **Источник истины — PostgreSQL.** Все данные: пользователи, чаты, членство, сообщения, сессии. In-memory хранилища lab1 не осталось.
|
||||||
|
- **Транзакционные границы.**
|
||||||
|
- `create_user`: одна вставка. Уникальность username гарантирует `UNIQUE` constraint → `409`.
|
||||||
|
- `create_chat`: `INSERT` чата + `INSERT` участников внутри одной транзакции (атомарность).
|
||||||
|
- `add_message`: проверка членства + `INSERT` внутри одной транзакции.
|
||||||
|
- **Аутентификация.**
|
||||||
|
- `password` хешируется **Argon2id** (`argon2-cffi`, параметры по умолчанию: `time_cost=3`, `memory_cost=64 MiB`, `parallelism=4`). Соответствует требованиям lab7, не придётся менять.
|
||||||
|
- `POST /auth/sessions` принимает только `Authorization: Basic base64(username:password)`.
|
||||||
|
- Возвращает opaque Bearer-токен: `secrets.token_urlsafe(32)` = **256 бит энтропии**, URL-safe base64.
|
||||||
|
- В БД хранится **SHA-256 от токена** (в отличие от паролей). SHA-256 уместен потому, что токен имеет высокую энтропию и не перебирается.
|
||||||
|
- TTL — `SESSION_TTL_SECONDS` (по умолчанию 3600 секунд). Просроченные сессии игнорируются.
|
||||||
|
- `X-User-Id` **полностью игнорируется** — даже с валидным значением он не даёт доступ. Запрос аутентифицируется только Bearer-токеном.
|
||||||
|
- **Пагинация.** Keyset-cursor по `(created_at, id)` по возрастанию. Cursor привязан к scope (`chats:<user_id>` или `chat:<chat_id>`). SQL-запрос использует кортежное сравнение `(created_at, id) > ($1, $2)` с `LIMIT limit+1`. Индекс `messages_history_idx (chat_id, created_at, id)` покрывает запрос.
|
||||||
|
- **Соответствие переменных из `.env.example`:**
|
||||||
|
- `APP_HOST` → `uvicorn` host.
|
||||||
|
- `APP_PORT` → `uvicorn` port.
|
||||||
|
- `APP_ENV` → информационное.
|
||||||
|
- `SESSION_TTL_SECONDS` → TTL сессий.
|
||||||
|
- `DATABASE_URL` → строка подключения к Postgres.
|
||||||
|
- `SESSION_STORE` → `postgres` (сессии в Postgres, Redis/Valkey появятся на lab4).
|
||||||
|
- `CACHE_URL_FILE` → не используется на lab2.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Публичный smoke | `make test BASE_URL=http://localhost:8080` | `PASS: lab2 public API scenario` | вывод терминала |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Минимум lab1 сохранён (с новым auth) | smoke проверяет health, users, chats, messages, пагинацию | все проверки PASS | `tests/smoke.py` |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| PostgreSQL содержит users/chats/members/messages | `docker compose exec postgres psql -U messenger -d messenger -c "\dt"` | таблицы `users`, `chats`, `chat_members`, `messages`, `sessions` | вывод терминала |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Миграции с нуля | `alembic upgrade head` на пустом volume | применяется ревизия `447472b8acec` | вывод терминала |
|
||||||
|
| Идемпотентность миграций | повторный `alembic upgrade head` | ничего не применяется | вывод терминала |
|
||||||
|
| Atomic create chat | покрыто тестом `store.create_chat` | INSERT чата + участников в одной транзакции | `src/store.py` |
|
||||||
|
| Basic только на POST /auth/sessions | smoke проверяет Basic на бизнес-endpoint → 401 | PASS | `tests/smoke.py` |
|
||||||
|
| X-User-Id не даёт доступ | smoke: `GET /users/me` с `X-User-Id` и валидным Bearer | возвращает владельца Bearer, а не X-User-Id | `tests/smoke.py` |
|
||||||
|
| Password KDF | Argon2id | хеш `$argon2id$v=19$m=65536,t=3,p=4$...` | вывод `hash_password` |
|
||||||
|
| Test persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | `PASS: persistence preserved confirmed data and existing session` | вывод терминала |
|
||||||
|
| Secrets/volumes не в git | `git status` | `.env` не появляется | `.gitignore` |
|
||||||
|
| Docker Compose с volumes | `docker compose ps` | postgres_data named volume | `compose.yaml` |
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
### Сценарий сохранности (фрагмент)
|
||||||
|
|
||||||
|
```
|
||||||
|
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://localhost:8080
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
```
|
||||||
|
|
||||||
|
Тест:
|
||||||
|
1. Создаёт пользователя, логинится, создаёт чат, отправляет сообщение.
|
||||||
|
2. Запускает `scripts/restart.sh` — `docker compose restart postgres` + `docker compose restart api` (volumes сохраняются).
|
||||||
|
3. Ждёт `healthy`.
|
||||||
|
4. Проверяет **тем же токеном** — сессия жива, данные на месте.
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| Перезапуск API + Postgres (`docker compose restart`, volumes сохранены) | Данные и сессия выживают | PASS, тот же токен, те же данные | ~5 секунд, потери нет |
|
||||||
|
| Миграции на пустом volume | Все таблицы создаются | PASS | — |
|
||||||
|
| Повторные миграции | Ничего не применяется | PASS | — |
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
- Сессии хранятся в PostgreSQL. На lab4 можно перейти на Redis/Valkey с persistence.
|
||||||
|
- Пароли хешируются Argon2id с параметрами по умолчанию. На lab7 требуется усиление (time_cost, memory_cost) и обязательный Argon2id без альтернатив — у нас уже Argon2id.
|
||||||
|
- Нет HTTP rate limiting, нет распределённых транзакций, нет реплик.
|
||||||
|
- Cleanup-job для просроченных сессий не реализован — они просто игнорируются при проверке.
|
||||||
|
- Индекс `messages_history_idx` достаточен для lab2. На lab4 потребуется `EXPLAIN (ANALYZE, BUFFERS)` на 10 000 сообщениях и возможно сравнение с альтернативами.
|
||||||
|
|
||||||
|
Следующий шаг — при желании уровень 4: Redis/Valkey для сессий, проверка гонки регистрации, EXPLAIN на большом объёме данных, тесты отказов зависимостей.
|
||||||
+118
@@ -0,0 +1,118 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts
|
||||||
|
# Use forward slashes (/) also on windows to provide an os agnostic path
|
||||||
|
script_location = migrations
|
||||||
|
|
||||||
|
# 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 migrations/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:migrations/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
|
||||||
|
|
||||||
|
# URL подставится из переменной окружения DATABASE_URL (см. migrations/env.py).
|
||||||
|
sqlalchemy.url =
|
||||||
|
|
||||||
|
|
||||||
|
[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 = WARN
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
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,45 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16.4-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-changeme}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:5433:5432"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
start_period: 5s
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
api:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
environment:
|
||||||
|
APP_HOST: ${APP_HOST:-0.0.0.0}
|
||||||
|
APP_PORT: ${APP_PORT:-8080}
|
||||||
|
APP_ENV: ${APP_ENV:-lab}
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
|
DATABASE_URL: postgresql://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:-changeme}@postgres:5432/${POSTGRES_DB:-messenger}
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:8080:8080"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health/live', timeout=2).status==200 else 1)"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
|
start_period: 10s
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
name: mtusi_lab2_postgres_data
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration.
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
database_url = os.environ.get("DATABASE_URL")
|
||||||
|
if not database_url:
|
||||||
|
raise RuntimeError("DATABASE_URL environment variable is required for migrations")
|
||||||
|
|
||||||
|
target_metadata = None
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
"""Оффлайн-режим: печатает SQL, не подключаясь к БД."""
|
||||||
|
context.configure(
|
||||||
|
url=database_url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
"""Онлайн-режим: подключается к БД и применяет миграции."""
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
|
||||||
|
connectable = create_engine(database_url, pool_pre_ping=True)
|
||||||
|
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,83 @@
|
|||||||
|
"""create initial schema
|
||||||
|
|
||||||
|
Revision ID: <оставь тот, что сгенерировал alembic>
|
||||||
|
Revises:
|
||||||
|
Create Date: <оставь>
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = "447472b8acec"
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.execute("""
|
||||||
|
CREATE TABLE users (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL UNIQUE,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
CREATE TABLE chats (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
CREATE TABLE 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)
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
CREATE INDEX chat_members_user_idx ON chat_members (user_id)
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
sender_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
text TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id)
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
token_hash TEXT PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
|
op.execute("""
|
||||||
|
CREATE INDEX sessions_user_idx ON sessions (user_id)
|
||||||
|
""")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.execute("DROP TABLE IF EXISTS sessions")
|
||||||
|
op.execute("DROP TABLE IF EXISTS messages")
|
||||||
|
op.execute("DROP INDEX IF EXISTS chat_members_user_idx")
|
||||||
|
op.execute("DROP TABLE IF EXISTS chat_members")
|
||||||
|
op.execute("DROP TABLE IF EXISTS chats")
|
||||||
|
op.execute("DROP TABLE IF EXISTS users")
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
fastapi==0.115.0
|
||||||
|
uvicorn[standard]==0.30.6
|
||||||
|
pydantic==2.9.2
|
||||||
|
psycopg[binary]==3.2.3
|
||||||
|
alembic==1.13.3
|
||||||
|
argon2-cffi==23.1.0
|
||||||
|
psycopg-pool==3.2.3
|
||||||
Executable
+19
@@ -0,0 +1,19 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
docker compose --env-file .env restart postgres
|
||||||
|
docker compose --env-file .env restart api
|
||||||
|
|
||||||
|
i=0
|
||||||
|
while [ $i -lt 60 ]; do
|
||||||
|
if docker compose --env-file .env ps api | grep -q "healthy"; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
i=$((i + 1))
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "api did not become healthy in 60 seconds" >&2
|
||||||
|
exit 1
|
||||||
Executable
+87
@@ -0,0 +1,87 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from argon2 import PasswordHasher
|
||||||
|
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
|
||||||
|
|
||||||
|
from .db import transaction
|
||||||
|
|
||||||
|
_hasher = PasswordHasher()
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(password: str) -> str:
|
||||||
|
return _hasher.hash(password)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(password: str, password_hash: str) -> bool:
|
||||||
|
try:
|
||||||
|
_hasher.verify(password_hash, password)
|
||||||
|
return True
|
||||||
|
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> datetime:
|
||||||
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def _ttl_seconds() -> int:
|
||||||
|
return int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||||
|
|
||||||
|
|
||||||
|
def _generate_token() -> str:
|
||||||
|
return secrets.token_urlsafe(32)
|
||||||
|
|
||||||
|
|
||||||
|
def _token_hash(token: str) -> str:
|
||||||
|
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def create_session(user_id: str) -> dict:
|
||||||
|
token = _generate_token()
|
||||||
|
expires_at = _now() + timedelta(seconds=_ttl_seconds())
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO sessions (token_hash, user_id, expires_at, created_at)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
""",
|
||||||
|
(_token_hash(token), user_id, expires_at, _now()),
|
||||||
|
)
|
||||||
|
return {"token": token, "expires_at": expires_at}
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_id_by_token(token: str) -> Optional[str]:
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT user_id, expires_at
|
||||||
|
FROM sessions
|
||||||
|
WHERE token_hash = %s
|
||||||
|
""",
|
||||||
|
(_token_hash(token),),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
if row["expires_at"] <= _now():
|
||||||
|
return None
|
||||||
|
return str(row["user_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def revoke_session(token: str) -> bool:
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"DELETE FROM sessions WHERE token_hash = %s",
|
||||||
|
(_token_hash(token),),
|
||||||
|
)
|
||||||
|
return cur.rowcount > 0
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from typing import Iterator
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
|
||||||
|
_pool: ConnectionPool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _database_url() -> str:
|
||||||
|
url = os.environ.get("DATABASE_URL")
|
||||||
|
if not url:
|
||||||
|
raise RuntimeError("DATABASE_URL environment variable is required")
|
||||||
|
return url
|
||||||
|
|
||||||
|
|
||||||
|
def init_pool(min_size: int = 1, max_size: int = 10) -> None:
|
||||||
|
global _pool
|
||||||
|
if _pool is not None:
|
||||||
|
return
|
||||||
|
_pool = ConnectionPool(
|
||||||
|
conninfo=_database_url(),
|
||||||
|
min_size=min_size,
|
||||||
|
max_size=max_size,
|
||||||
|
kwargs={"row_factory": dict_row},
|
||||||
|
open=True,
|
||||||
|
timeout=5.0,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def close_pool() -> None:
|
||||||
|
global _pool
|
||||||
|
if _pool is not None:
|
||||||
|
_pool.close()
|
||||||
|
_pool = None
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def connection() -> Iterator[psycopg.Connection]:
|
||||||
|
if _pool is None:
|
||||||
|
raise RuntimeError("Connection pool is not initialized")
|
||||||
|
with _pool.connection() as conn:
|
||||||
|
yield conn
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def transaction() -> Iterator[psycopg.Connection]:
|
||||||
|
with connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
yield conn
|
||||||
Executable
+65
@@ -0,0 +1,65 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from fastapi import Request
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
|
||||||
|
from .store import ApiError
|
||||||
|
|
||||||
|
|
||||||
|
REQUEST_ID_HEADER = "X-Request-Id"
|
||||||
|
|
||||||
|
|
||||||
|
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||||
|
async def dispatch(self, request: Request, call_next: Callable):
|
||||||
|
rid = request.headers.get(REQUEST_ID_HEADER) or uuid.uuid4().hex
|
||||||
|
request.state.request_id = rid
|
||||||
|
response = await call_next(request)
|
||||||
|
response.headers[REQUEST_ID_HEADER] = rid
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
def _envelope(code: str, message: str, request_id: str) -> dict:
|
||||||
|
return {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||||
|
|
||||||
|
|
||||||
|
def _rid(request: Request) -> str:
|
||||||
|
return getattr(request.state, "request_id", None) or uuid.uuid4().hex
|
||||||
|
|
||||||
|
|
||||||
|
async def api_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||||
|
assert isinstance(exc, ApiError)
|
||||||
|
response = JSONResponse(
|
||||||
|
status_code=exc.status,
|
||||||
|
content=_envelope(exc.code, exc.message, _rid(request)),
|
||||||
|
)
|
||||||
|
if exc.status == 401:
|
||||||
|
scheme = "Bearer"
|
||||||
|
if request.url.path == "/api/v1/auth/sessions":
|
||||||
|
scheme = "Basic"
|
||||||
|
response.headers["WWW-Authenticate"] = f'{scheme} realm="messenger"'
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
async def validation_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=400,
|
||||||
|
content=_envelope("invalid_request", "Request validation failed", _rid(request)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def json_decode_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=400,
|
||||||
|
content=_envelope("invalid_request", "Malformed JSON", _rid(request)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def unhandled_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=500,
|
||||||
|
content=_envelope("internal_error", "Internal error", _rid(request)),
|
||||||
|
)
|
||||||
Executable
+236
@@ -0,0 +1,236 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import Depends, FastAPI, Header, Query, Request, Response
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||||
|
|
||||||
|
from . import auth
|
||||||
|
from .db import close_pool, init_pool
|
||||||
|
from .errors import (
|
||||||
|
RequestIdMiddleware,
|
||||||
|
_envelope,
|
||||||
|
_rid,
|
||||||
|
api_error_handler,
|
||||||
|
json_decode_handler,
|
||||||
|
unhandled_handler,
|
||||||
|
validation_handler,
|
||||||
|
)
|
||||||
|
from .schemas import (
|
||||||
|
Chat,
|
||||||
|
ChatPage,
|
||||||
|
CreateChat,
|
||||||
|
CreateMessage,
|
||||||
|
CreateUser,
|
||||||
|
Health,
|
||||||
|
Message,
|
||||||
|
MessagePage,
|
||||||
|
Session,
|
||||||
|
User,
|
||||||
|
)
|
||||||
|
from .store import ApiError, BadRequest, Conflict, NotFound, Unauthorized, store, iso
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s"
|
||||||
|
)
|
||||||
|
log = logging.getLogger("messenger")
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
init_pool()
|
||||||
|
log.info("db pool initialized")
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
close_pool()
|
||||||
|
log.info("db pool closed")
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(title="MTUSI Messenger lab2", version="1.2.0", lifespan=lifespan)
|
||||||
|
app.add_middleware(RequestIdMiddleware)
|
||||||
|
|
||||||
|
app.add_exception_handler(ApiError, api_error_handler)
|
||||||
|
app.add_exception_handler(RequestValidationError, validation_handler)
|
||||||
|
app.add_exception_handler(Exception, unhandled_handler)
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(StarletteHTTPException)
|
||||||
|
async def _http_exc(request: Request, exc: StarletteHTTPException):
|
||||||
|
code = "not_found" if exc.status_code == 404 else "invalid_request"
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=exc.status_code,
|
||||||
|
content=_envelope(code, str(exc.detail), _rid(request)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- зависимости ----------
|
||||||
|
|
||||||
|
def _parse_basic(header_value: str) -> tuple[str, str]:
|
||||||
|
"""Разбирает `Basic base64(username:password)`. Бросает Unauthorized."""
|
||||||
|
import base64
|
||||||
|
if not header_value.lower().startswith("basic "):
|
||||||
|
raise Unauthorized("Basic authentication required")
|
||||||
|
try:
|
||||||
|
raw = base64.b64decode(header_value.split(" ", 1)[1], validate=True)
|
||||||
|
decoded = raw.decode("utf-8")
|
||||||
|
username, _, password = decoded.partition(":")
|
||||||
|
if not username:
|
||||||
|
raise ValueError("empty username")
|
||||||
|
return username, password
|
||||||
|
except Exception:
|
||||||
|
raise Unauthorized("Invalid Basic credentials") from None
|
||||||
|
|
||||||
|
|
||||||
|
def _bearer_token(authorization: Optional[str]) -> str:
|
||||||
|
if not authorization:
|
||||||
|
raise Unauthorized("Missing Authorization header")
|
||||||
|
parts = authorization.split(" ", 1)
|
||||||
|
if len(parts) != 2 or parts[0].lower() != "bearer":
|
||||||
|
raise Unauthorized("Bearer token required")
|
||||||
|
token = parts[1].strip()
|
||||||
|
if not token:
|
||||||
|
raise Unauthorized("Empty bearer token")
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def current_user_id(
|
||||||
|
authorization: Optional[str] = Header(default=None),
|
||||||
|
) -> str:
|
||||||
|
token = _bearer_token(authorization)
|
||||||
|
user_id = auth.get_user_id_by_token(token)
|
||||||
|
if user_id is None:
|
||||||
|
raise Unauthorized("Invalid or expired token")
|
||||||
|
return user_id
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- health ----------
|
||||||
|
|
||||||
|
@app.get("/health/live", response_model=Health)
|
||||||
|
def liveness():
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health/ready", response_model=Health)
|
||||||
|
def readiness():
|
||||||
|
try:
|
||||||
|
from .db import transaction
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT 1")
|
||||||
|
except Exception:
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=503,
|
||||||
|
content=_envelope("unavailable", "Database unavailable", "readiness"),
|
||||||
|
)
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- users ----------
|
||||||
|
|
||||||
|
@app.post("/api/v1/users", status_code=201, response_model=User)
|
||||||
|
def register_user(body: CreateUser):
|
||||||
|
password_hash = auth.hash_password(body.password)
|
||||||
|
return store.create_user(body.username, body.display_name, password_hash)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/v1/users/me", response_model=User)
|
||||||
|
def me(user_id: str = Depends(current_user_id)):
|
||||||
|
user = store.get_user(user_id)
|
||||||
|
if user is None:
|
||||||
|
raise Unauthorized("User not found")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- auth ----------
|
||||||
|
|
||||||
|
@app.post("/api/v1/auth/sessions", status_code=201, response_model=Session)
|
||||||
|
def create_session(authorization: Optional[str] = Header(default=None)):
|
||||||
|
username, password = _parse_basic(authorization or "")
|
||||||
|
row = store.get_user_by_username(username)
|
||||||
|
if row is None or not auth.verify_password(password, row["password_hash"]):
|
||||||
|
raise Unauthorized("Invalid credentials")
|
||||||
|
session = auth.create_session(str(row["id"]))
|
||||||
|
user = store.get_user(str(row["id"]))
|
||||||
|
if user is None:
|
||||||
|
raise Unauthorized("User not found")
|
||||||
|
return {
|
||||||
|
"token": session["token"],
|
||||||
|
"token_type": "Bearer",
|
||||||
|
"expires_at": iso(session["expires_at"]),
|
||||||
|
"user": user,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||||
|
def logout(authorization: Optional[str] = Header(default=None)):
|
||||||
|
token = _bearer_token(authorization)
|
||||||
|
user_id = auth.get_user_id_by_token(token)
|
||||||
|
if user_id is None:
|
||||||
|
raise Unauthorized("Invalid or expired token")
|
||||||
|
auth.revoke_session(token)
|
||||||
|
return Response(status_code=204)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- chats ----------
|
||||||
|
|
||||||
|
@app.post("/api/v1/chats", status_code=201, response_model=Chat)
|
||||||
|
def create_chat(body: CreateChat, user_id: str = Depends(current_user_id)):
|
||||||
|
return store.create_chat(body.title, body.member_ids, user_id)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||||
|
def list_chats(
|
||||||
|
limit: int = Query(default=50, ge=1, le=100),
|
||||||
|
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||||
|
user_id: str = Depends(current_user_id),
|
||||||
|
):
|
||||||
|
items, next_cursor = store.list_chats(user_id, limit, cursor)
|
||||||
|
return {"items": items, "next_cursor": next_cursor}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||||
|
def get_chat(chat_id: str, user_id: str = Depends(current_user_id)):
|
||||||
|
chat = store.get_chat(chat_id, user_id)
|
||||||
|
if chat is None:
|
||||||
|
raise NotFound()
|
||||||
|
return chat
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- messages ----------
|
||||||
|
|
||||||
|
@app.post(
|
||||||
|
"/api/v1/chats/{chat_id}/messages", status_code=201, response_model=Message
|
||||||
|
)
|
||||||
|
def create_message(
|
||||||
|
chat_id: str, body: CreateMessage, user_id: str = Depends(current_user_id)
|
||||||
|
):
|
||||||
|
return store.add_message(chat_id, user_id, body.text)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||||
|
def list_messages(
|
||||||
|
chat_id: str,
|
||||||
|
limit: int = Query(default=50, ge=1, le=100),
|
||||||
|
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||||
|
user_id: str = Depends(current_user_id),
|
||||||
|
):
|
||||||
|
items, next_cursor = store.list_messages(chat_id, user_id, limit, cursor)
|
||||||
|
return {"items": items, "next_cursor": next_cursor}
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
host = os.environ.get("APP_HOST", "0.0.0.0")
|
||||||
|
port = int(os.environ.get("APP_PORT", "8080"))
|
||||||
|
uvicorn.run("src.main:app", host=host, port=port, log_level="info")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Executable
+135
@@ -0,0 +1,135 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import uuid
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||||
|
|
||||||
|
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||||
|
|
||||||
|
|
||||||
|
class StrictModel(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=False)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Users ----------
|
||||||
|
|
||||||
|
class CreateUser(StrictModel):
|
||||||
|
username: str = Field(min_length=3, max_length=32)
|
||||||
|
display_name: str = Field(min_length=1, max_length=100)
|
||||||
|
password: str = Field(min_length=12, max_length=128)
|
||||||
|
|
||||||
|
@field_validator("username")
|
||||||
|
@classmethod
|
||||||
|
def _username(cls, v: str) -> str:
|
||||||
|
if not USERNAME_RE.match(v):
|
||||||
|
raise ValueError("username must match [a-z0-9_]{3,32}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator("display_name")
|
||||||
|
@classmethod
|
||||||
|
def _display_name(cls, v: str) -> str:
|
||||||
|
if not v.strip():
|
||||||
|
raise ValueError("display_name must not be blank")
|
||||||
|
if len(v) > 100:
|
||||||
|
raise ValueError("display_name too long")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class User(StrictModel):
|
||||||
|
id: str
|
||||||
|
username: str
|
||||||
|
display_name: str
|
||||||
|
created_at: str
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Chats ----------
|
||||||
|
|
||||||
|
class CreateChat(StrictModel):
|
||||||
|
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 _title(cls, v: str) -> str:
|
||||||
|
if not v.strip():
|
||||||
|
raise ValueError("title must not be blank")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator("member_ids")
|
||||||
|
@classmethod
|
||||||
|
def _members(cls, v: List[str]) -> List[str]:
|
||||||
|
if len(set(v)) != len(v):
|
||||||
|
raise ValueError("member_ids must be unique")
|
||||||
|
for item in v:
|
||||||
|
try:
|
||||||
|
uuid.UUID(item)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValueError("member_ids must be UUIDs") from exc
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class Chat(StrictModel):
|
||||||
|
id: str
|
||||||
|
title: str
|
||||||
|
member_ids: List[str]
|
||||||
|
created_at: str
|
||||||
|
|
||||||
|
|
||||||
|
class ChatPage(StrictModel):
|
||||||
|
items: List[Chat]
|
||||||
|
next_cursor: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Messages ----------
|
||||||
|
|
||||||
|
class CreateMessage(StrictModel):
|
||||||
|
text: str = Field(min_length=1, max_length=4000)
|
||||||
|
|
||||||
|
@field_validator("text")
|
||||||
|
@classmethod
|
||||||
|
def _text(cls, v: str) -> str:
|
||||||
|
if not v.strip():
|
||||||
|
raise ValueError("text must not be blank")
|
||||||
|
if len(v) > 4000:
|
||||||
|
raise ValueError("text too long")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class Message(StrictModel):
|
||||||
|
id: str
|
||||||
|
chat_id: str
|
||||||
|
sender_id: str
|
||||||
|
text: str
|
||||||
|
created_at: str
|
||||||
|
|
||||||
|
|
||||||
|
class MessagePage(StrictModel):
|
||||||
|
items: List[Message]
|
||||||
|
next_cursor: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Sessions ----------
|
||||||
|
|
||||||
|
class Session(StrictModel):
|
||||||
|
token: str = Field(min_length=32)
|
||||||
|
token_type: str = Field(default="Bearer")
|
||||||
|
expires_at: str
|
||||||
|
user: User
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Misc ----------
|
||||||
|
|
||||||
|
class Health(StrictModel):
|
||||||
|
status: str = "ok"
|
||||||
|
|
||||||
|
|
||||||
|
class ErrorBody(StrictModel):
|
||||||
|
code: str
|
||||||
|
message: str
|
||||||
|
request_id: str
|
||||||
|
|
||||||
|
|
||||||
|
class ErrorEnvelope(StrictModel):
|
||||||
|
error: ErrorBody
|
||||||
Executable
+332
@@ -0,0 +1,332 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import List, Optional, Tuple
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg.errors import UniqueViolation
|
||||||
|
|
||||||
|
from .db import transaction
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- ошибки ----------
|
||||||
|
|
||||||
|
class ApiError(Exception):
|
||||||
|
status = 500
|
||||||
|
code = "internal_error"
|
||||||
|
|
||||||
|
def __init__(self, message: str = "Internal error") -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.message = message
|
||||||
|
|
||||||
|
|
||||||
|
class BadRequest(ApiError):
|
||||||
|
status = 400
|
||||||
|
code = "invalid_request"
|
||||||
|
|
||||||
|
|
||||||
|
class Unauthorized(ApiError):
|
||||||
|
status = 401
|
||||||
|
code = "unauthorized"
|
||||||
|
|
||||||
|
|
||||||
|
class NotFound(ApiError):
|
||||||
|
status = 404
|
||||||
|
code = "not_found"
|
||||||
|
|
||||||
|
|
||||||
|
class Conflict(ApiError):
|
||||||
|
status = 409
|
||||||
|
code = "conflict"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- утилиты ----------
|
||||||
|
|
||||||
|
def _now() -> datetime:
|
||||||
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def iso(dt: datetime) -> str:
|
||||||
|
return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||||
|
|
||||||
|
|
||||||
|
def _user_dict(row: dict) -> dict:
|
||||||
|
return {
|
||||||
|
"id": str(row["id"]),
|
||||||
|
"username": row["username"],
|
||||||
|
"display_name": row["display_name"],
|
||||||
|
"created_at": iso(row["created_at"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _chat_dict(row: dict, member_ids: List[str]) -> dict:
|
||||||
|
return {
|
||||||
|
"id": str(row["id"]),
|
||||||
|
"title": row["title"],
|
||||||
|
"member_ids": member_ids,
|
||||||
|
"created_at": iso(row["created_at"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _message_dict(row: dict) -> dict:
|
||||||
|
return {
|
||||||
|
"id": str(row["id"]),
|
||||||
|
"chat_id": str(row["chat_id"]),
|
||||||
|
"sender_id": str(row["sender_id"]),
|
||||||
|
"text": row["text"],
|
||||||
|
"created_at": iso(row["created_at"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- курсор ----------
|
||||||
|
|
||||||
|
def _encode_cursor(scope: str, created_at: str, item_id: str) -> str:
|
||||||
|
payload = json.dumps(
|
||||||
|
{"s": scope, "t": created_at, "i": item_id}, separators=(",", ":")
|
||||||
|
).encode()
|
||||||
|
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_cursor(scope: str, cursor: str) -> Tuple[str, str]:
|
||||||
|
pad = "=" * (-len(cursor) % 4)
|
||||||
|
try:
|
||||||
|
raw = base64.urlsafe_b64decode(cursor + pad)
|
||||||
|
data = json.loads(raw)
|
||||||
|
if data.get("s") != scope:
|
||||||
|
raise ValueError("scope mismatch")
|
||||||
|
return data["t"], data["i"]
|
||||||
|
except Exception as exc:
|
||||||
|
raise BadRequest("invalid cursor") from exc
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- Store ----------
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
|
||||||
|
# ---- users ----
|
||||||
|
|
||||||
|
def create_user(
|
||||||
|
self, username: str, display_name: str, password_hash: str
|
||||||
|
) -> dict:
|
||||||
|
uid = str(uuid.uuid4())
|
||||||
|
now = _now()
|
||||||
|
try:
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||||
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
|
""",
|
||||||
|
(uid, username, display_name, password_hash, now),
|
||||||
|
)
|
||||||
|
except UniqueViolation:
|
||||||
|
raise Conflict("username already taken") from None
|
||||||
|
return {
|
||||||
|
"id": uid,
|
||||||
|
"username": username,
|
||||||
|
"display_name": display_name,
|
||||||
|
"created_at": iso(now),
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_user(self, user_id: str) -> Optional[dict]:
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
return _user_dict(row) if row else None
|
||||||
|
|
||||||
|
def get_user_by_username(self, username: str) -> Optional[dict]:
|
||||||
|
"""Возвращает полную строку, включая password_hash (для входа)."""
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT * FROM users WHERE username = %s", (username,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
return row
|
||||||
|
|
||||||
|
# ---- chats ----
|
||||||
|
|
||||||
|
def create_chat(
|
||||||
|
self, title: str, member_ids: List[str], creator_id: str
|
||||||
|
) -> dict:
|
||||||
|
if creator_id not in member_ids:
|
||||||
|
raise BadRequest("creator must be in member_ids")
|
||||||
|
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id FROM users WHERE id = ANY(%s)",
|
||||||
|
(member_ids,),
|
||||||
|
)
|
||||||
|
found = {str(r["id"]) for r in cur.fetchall()}
|
||||||
|
missing = set(member_ids) - found
|
||||||
|
if missing:
|
||||||
|
raise BadRequest("unknown member_id")
|
||||||
|
|
||||||
|
cid = str(uuid.uuid4())
|
||||||
|
now = _now()
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||||
|
(cid, title, now),
|
||||||
|
)
|
||||||
|
cur.executemany(
|
||||||
|
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||||
|
[(cid, uid) for uid in member_ids],
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"id": cid,
|
||||||
|
"title": title,
|
||||||
|
"member_ids": list(member_ids),
|
||||||
|
"created_at": iso(now),
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_chat(self, chat_id: str, viewer_id: str) -> Optional[dict]:
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT c.* FROM chats c
|
||||||
|
JOIN chat_members m ON m.chat_id = c.id
|
||||||
|
WHERE c.id = %s AND m.user_id = %s
|
||||||
|
""",
|
||||||
|
(chat_id, viewer_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
cur.execute(
|
||||||
|
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||||
|
(chat_id,),
|
||||||
|
)
|
||||||
|
members = [str(r["user_id"]) for r in cur.fetchall()]
|
||||||
|
return _chat_dict(row, members)
|
||||||
|
|
||||||
|
def list_chats(
|
||||||
|
self, viewer_id: str, limit: int, cursor: Optional[str]
|
||||||
|
) -> Tuple[List[dict], Optional[str]]:
|
||||||
|
scope = "chats:" + viewer_id
|
||||||
|
params: list = [viewer_id]
|
||||||
|
where_cursor = ""
|
||||||
|
if cursor:
|
||||||
|
t, i = _decode_cursor(scope, cursor)
|
||||||
|
where_cursor = "AND (c.created_at, c.id) > (%s, %s)"
|
||||||
|
params.extend([t, i])
|
||||||
|
params.append(limit + 1) # +1, чтобы узнать, есть ли следующая страница
|
||||||
|
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
f"""
|
||||||
|
SELECT c.id, c.title, c.created_at
|
||||||
|
FROM chats c
|
||||||
|
JOIN chat_members m ON m.chat_id = c.id
|
||||||
|
WHERE m.user_id = %s {where_cursor}
|
||||||
|
ORDER BY c.created_at, c.id
|
||||||
|
LIMIT %s
|
||||||
|
""",
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
|
||||||
|
has_more = len(rows) > limit
|
||||||
|
page = rows[:limit]
|
||||||
|
|
||||||
|
result = []
|
||||||
|
for row in page:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||||
|
(row["id"],),
|
||||||
|
)
|
||||||
|
members = [str(r["user_id"]) for r in cur.fetchall()]
|
||||||
|
result.append(_chat_dict(row, members))
|
||||||
|
|
||||||
|
next_cursor = None
|
||||||
|
if has_more and page:
|
||||||
|
last = page[-1]
|
||||||
|
next_cursor = _encode_cursor(scope, iso(last["created_at"]), str(last["id"]))
|
||||||
|
return result, next_cursor
|
||||||
|
|
||||||
|
# ---- messages ----
|
||||||
|
|
||||||
|
def add_message(self, chat_id: str, sender_id: str, text: str) -> dict:
|
||||||
|
mid = str(uuid.uuid4())
|
||||||
|
now = _now()
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||||
|
(chat_id, sender_id),
|
||||||
|
)
|
||||||
|
if cur.fetchone() is None:
|
||||||
|
raise NotFound()
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||||
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
|
""",
|
||||||
|
(mid, chat_id, sender_id, text, now),
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"id": mid,
|
||||||
|
"chat_id": chat_id,
|
||||||
|
"sender_id": sender_id,
|
||||||
|
"text": text,
|
||||||
|
"created_at": iso(now),
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_messages(
|
||||||
|
self,
|
||||||
|
chat_id: str,
|
||||||
|
viewer_id: str,
|
||||||
|
limit: int,
|
||||||
|
cursor: Optional[str],
|
||||||
|
) -> Tuple[List[dict], Optional[str]]:
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||||
|
(chat_id, viewer_id),
|
||||||
|
)
|
||||||
|
if cur.fetchone() is None:
|
||||||
|
raise NotFound()
|
||||||
|
|
||||||
|
scope = "chat:" + chat_id
|
||||||
|
params: list = [chat_id]
|
||||||
|
where_cursor = ""
|
||||||
|
if cursor:
|
||||||
|
t, i = _decode_cursor(scope, cursor)
|
||||||
|
where_cursor = "AND (created_at, id) > (%s, %s)"
|
||||||
|
params.extend([t, i])
|
||||||
|
params.append(limit + 1)
|
||||||
|
|
||||||
|
with transaction() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
f"""
|
||||||
|
SELECT id, chat_id, sender_id, text, created_at
|
||||||
|
FROM messages
|
||||||
|
WHERE chat_id = %s {where_cursor}
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT %s
|
||||||
|
""",
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
|
||||||
|
has_more = len(rows) > limit
|
||||||
|
page = rows[:limit]
|
||||||
|
result = [_message_dict(r) for r in page]
|
||||||
|
|
||||||
|
next_cursor = None
|
||||||
|
if has_more and page:
|
||||||
|
last = page[-1]
|
||||||
|
next_cursor = _encode_cursor(scope, iso(last["created_at"]), str(last["id"]))
|
||||||
|
return result, next_cursor
|
||||||
|
|
||||||
|
|
||||||
|
store = Store()
|
||||||
Reference in New Issue
Block a user