feat: реализация второй лабы по тз

This commit is contained in:
Enterxx2
2026-10-11 18:14:20 +03:00
parent a6c74c9bb0
commit ea2b432a22
100 changed files with 3416 additions and 428 deletions
+21 -5
View File
@@ -5,9 +5,25 @@ APP_PORT=8080
APP_ENV=lab
LOG_LEVEL=INFO
SHUTDOWN_TIMEOUT_SEC=5
DB_USER=test
DB_PASS=test
DB_NAME=test
DB_HOST=localhost
DB_PORT=5432
DB_POOL_MIN_SIZE=2
DB_POOL_MAX_SIZE=10
DB_CONNECT_TIMEOUT_SEC=3
DB_COMMAND_TIMEOUT_SEC=5
DB_STARTUP_TIMEOUT_SEC=30
VALKEY_HOST=localhost
VALKEY_PORT=6379
VALKEY_PASS=test
VALKEY_POOL_MAX_SIZE=20
VALKEY_TIMEOUT_SEC=0.5
VALKEY_RETRY_AFTER_SEC=5
SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values.
DATABASE_URL_FILE=/run/secrets/database_url
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
SESSION_CACHE_TTL_SECONDS=60
PASSWORD_HASH_WORKERS=4
+1
View File
@@ -8,6 +8,7 @@ WORKDIR /app
COPY poetry.lock pyproject.toml ./
RUN pip install --no-cache-dir "poetry==2.2.1" \
&& poetry install --only main --no-root --no-interaction
COPY migrations ./migrations
COPY src ./src
# Процесс работает не от root
+41 -36
View File
@@ -4,19 +4,12 @@ CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
ENV_FILE ?= .env
-include $(ENV_FILE)
IMAGE ?= mtusi-messenger:lab2
CONTAINER ?= mtusi-messenger-lab2
PUBLISH ?= 127.0.0.1:$(APP_PORT):$(APP_PORT)
READY_TIMEOUT_SEC ?= 30
POETRY ?= poetry
.PHONY: help check validate test load test-persistence install build run wait-ready stop restart logs student-test concurrency-test sigterm-check up_local down_local
.PHONY: help check validate test load test-persistence install up down restart ps logs wait-ready destroy-data student-test concurrency-test test-expiry test-failures test-migrations explain sigterm-check
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@echo "install: dev venv; build/run/stop/restart/logs: container; up_local/down_local: docker compose; student-test: own tests; concurrency-test, sigterm-check: evidence"
@echo "up/down/restart/ps/logs: compose stack; destroy-data: DELETE volumes intentionally"
@echo "student-test: own tests; test-migrations: from empty volume; test-expiry: short SESSION_TTL; test-failures: stop Valkey/PostgreSQL; explain: EXPLAIN history"
check:
$(PYTHON) scripts/check_contract.py
@@ -35,42 +28,54 @@ test-persistence:
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
install:
$(POETRY) install --no-root
poetry install --no-root
build:
docker build -t $(IMAGE) .
up:
docker compose up -d --build --wait
run:
docker run --rm -d --name $(CONTAINER) -p $(PUBLISH) --env-file $(ENV_FILE) $(IMAGE)
@$(MAKE) --no-print-directory wait-ready
wait-ready:
@for i in $$(seq 1 $(READY_TIMEOUT_SEC)); do \
curl -fsS "$(BASE_URL)/health/ready" >/dev/null 2>&1 && echo "ready: $(BASE_URL)" && exit 0; \
sleep 1; \
done; echo "API is not ready after $(READY_TIMEOUT_SEC)s"; exit 1
stop:
docker stop $(CONTAINER)
down:
docker compose --profile expiry down
restart:
docker restart $(CONTAINER)
./scripts/restart.sh
@$(MAKE) --no-print-directory wait-ready
ps:
docker compose ps
logs:
docker logs -f $(CONTAINER)
docker compose logs -f api
wait-ready:
@for i in $$(seq 1 60); do \
curl -fsS "$(BASE_URL)/health/ready" >/dev/null 2>&1 && echo "ready: $(BASE_URL)" && exit 0; \
sleep 1; \
done; echo "API is not ready after 60s"; exit 1
destroy-data:
docker compose --profile expiry down -v
student-test:
BASE_URL="$(BASE_URL)" $(POETRY) run pytest
BASE_URL="$(BASE_URL)" poetry run pytest
concurrency-test:
BASE_URL="$(BASE_URL)" $(POETRY) run pytest student-tests/test_concurrency.py -s
BASE_URL="$(BASE_URL)" poetry run pytest student-tests/test_concurrency.py -s
test-expiry:
docker compose --profile expiry up -d --build --wait api-short-ttl
EXPIRY_BASE_URL=http://localhost:8081 poetry run pytest student-tests/test_expiry.py -s; \
status=$$?; docker compose --profile expiry stop api-short-ttl; exit $$status
test-failures:
BASE_URL="$(BASE_URL)" RUN_FAILURE_TESTS=1 poetry run pytest student-tests/test_dependency_failures.py -s
test-migrations:
./scripts/check_migrations.sh
explain:
docker compose exec -T postgres sh -c 'psql -X -q -v ON_ERROR_STOP=1 -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"' \
< scripts/explain_history.sql > evidence/explain_history.txt
@echo "saved: evidence/explain_history.txt"
sigterm-check:
CONTAINER="$(CONTAINER)" $(PYTHON) scripts/sigterm_check.py --base-url "$(BASE_URL)"
up_local:
docker compose -f docker-compose-local.yaml up --build -d
down_local:
docker compose -f docker-compose-local.yaml down
$(PYTHON) scripts/sigterm_check.py --base-url "$(BASE_URL)"
+147 -16
View File
@@ -1,37 +1,168 @@
# Отчёт — лабораторная 2
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Автор, группа: Саватеев Артём, БВТ2302
- Целевая оценка: **4** (все пункты уровней 3 и 4)
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Использованные источники, библиотеки и помощь ИИ: FastAPI, Pydantic, Uvicorn, loguru, asyncpg, redis-py, argon2-cffi; для тестов pytest, httpx; документация PostgreSQL (transactions, EXPLAIN, advisory locks, `uuidv7`) и Valkey
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Версии: Docker Engine 29.0.1, Docker Compose v2.40.3 (проверено на Docker Desktop, linux/arm64). Образы закреплены явными тегами: `python:3.12.12-slim`, `postgres:18.22`, `valkey/valkey:8.1.4`. Python-зависимости закреплены в `pyproject.toml` (точные версии) и `poetry.lock`.
Prerequisites: Docker с Compose, make, curl, Python ≥ 3.9 для публичных тестов. Для собственных тестов дополнительно Python 3.12 и Poetry 2.2.1.
```sh
# Запуск
cp .env.example .env
make up # docker compose up -d --build --wait; миграции API применяет сам при старте
# Проверки
make check # структура skeleton
make test # публичный smoke
make test-persistence ACTION_SCRIPT=scripts/restart.sh # рестарт api, postgres, valkey с сохранением volume
make install # dev-окружение Poetry (один раз)
make student-test # собственные тесты, одна команда
make test-migrations # миграции на пустом volume отдельного compose-проекта
make test-expiry # второй API с SESSION_TTL_SECONDS=2 на :8081
make test-failures # останавливает и запускает valkey и postgres
make explain # сид ≥10 000 сообщений и планы запроса истории
# Безопасная остановка без потери данных
make down # = docker compose --profile expiry down
```
Намеренное удаление учебных данных — `make destroy-data` (`docker compose down -v`): volume `postgres_data` будет стёрт. Остальные команды volume не удаляют.
Операторских действий кроме создания `.env` не требуется. `make up` ждёт healthcheck всех сервисов, готовность API — `GET /health/ready`. `.env` в образ не копируется (`.dockerignore`), конфигурация передаётся через `env_file` в `compose.yaml`.
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
```
Клиент ──HTTP :8080──▶ api (FastAPI, uvicorn) ──asyncpg pool 2..10──▶ postgres источник истины, volume postgres_data
│
└──redis-py pool ≤20, timeout 0.5 s──▶ valkey read-through кэш сессий, без persistence
сети: default (только api, 127.0.0.1:8080) + backend (internal: api, postgres, valkey)
```
Слои в `src/`:
| Каталог | Ответственность |
| --- | --- |
| `config/` | чтение окружения через envparse, логирование loguru в stdout |
| `domain/` | Pydantic-схемы запросов/ответов, сессии и учётные данные, коды и исключения ошибок |
| `interfaces/` | ABC-репозитории и кэш сессий: сервисы зависят от абстракций, а не от PostgreSQL/Valkey |
| `infrastructure/` | репозитории PostgreSQL, кэш Valkey, сервисы, Argon2id и токены (`security/`), пул БД и кэша, пагинация/cursor, `ServiceCreator` для DI |
| `application/api/` | роутеры, Basic/Bearer зависимости, middleware, обработчики ошибок |
| `gateway.py` | сборка приложения, lifespan (пул, миграции, кэш), запуск uvicorn |
Миграции — нумерованные SQL-файлы в `migrations/`.
Роли и сервисы `compose.yaml`:
| Роль | Сервис | Версия | Health / readiness | Volume | Сеть / порт | Credentials |
| --- | --- | --- | --- | --- | --- | --- |
| API | `api` | сборка из `Dockerfile` | `src/healthcheck.py` → `/health/ready` | нет | default + backend, `127.0.0.1:8080` | `DB_*`, `VALKEY_*` из `.env` (env_file) |
| PostgreSQL | `postgres` | `postgres:18.2-alpine3.22` | `pg_isready` | `postgres_data:/var/lib/postgresql` | backend (internal), не публикуется | `POSTGRES_PASSWORD` ← `DB_PASS` |
| Valkey | `valkey` | `valkey/valkey:8.1.4-alpine3.22` | `valkey-cli ping` | нет (чистый кэш) | backend (internal), не публикуется | `--requirepass` ← `VALKEY_PASS` |
| API с коротким TTL | `api-short-ttl` (profile `expiry`) | тот же образ | как у API | нет | `127.0.0.1:8081` | как у API, `SESSION_TTL_SECONDS=2` |
**Что перенесено из lab1.** Слои `application/domain/interfaces/infrastructure`, контракт ошибок, `X-Request-Id`, keyset-cursor, graceful shutdown, Dockerfile с пользователем не root. In-memory хранилище удалено, вместо него репозитории `Postgres*Repository` и `ValkeySessionCache` за теми же интерфейсами.
**Переходы API по COURSE.md.** Регистрация требует `password` (12–128 code points). Вход только через `POST /api/v1/auth/sessions` с Basic. Все бизнес-endpoint требуют Bearer. Basic на бизнес-endpoint и `X-User-Id` возвращают 401 и не влияют на владельца сессии.
**Источник истины** — PostgreSQL. Схема — `migrations/0001_init.sql`:
| Таблица | Ключи и ограничения |
| --- | --- |
| `users` | PK `id uuid DEFAULT uuidv7()`, `UNIQUE (username)`, CHECK формата username и длины display_name, `password_hash` (PHC Argon2id) |
| `sessions` | PK `token_hash bytea` (SHA-256 токена, 32 байта), FK `user_id → users`, `expires_at`, `revoked_at`, CHECK `expires_at > created_at` |
| `chats` | PK uuid v7, FK `created_by → users`, CHECK длины title |
| `chat_members` | PK `(chat_id, user_id)`, FK на chats и users, `position` (порядок `member_ids`), `UNIQUE (chat_id, position)`, индекс `(user_id, chat_id)` |
| `messages` | PK uuid v7, FK `(chat_id, sender_id) → chat_members`: отправитель обязан быть участником; CHECK длины text; индекс `(chat_id, created_at, id)` |
UUID v7 упорядочен по времени, поэтому вставки в B-tree PK идут в правую часть, как у bigint, а наружу отдаётся UUID, как требует контракт.
**Регистрация** — один `INSERT`. Гонку одинаковых username разрешает `UNIQUE`, `UniqueViolationError` превращается в 409. Проверки «сначала SELECT» нет.
**Вход.** `SELECT` пользователя, проверка Argon2id в отдельном пуле потоков, затем `INSERT sessions` с `expires_at = clock_timestamp() + TTL` по часам БД. Токен — 32 случайных байта (256 бит), в БД хранится только его SHA-256. Для неизвестного username проверяется dummy-hash, поэтому ответ и время одинаковы.
**Создание чата** — `BEGIN` → `INSERT chats` → `INSERT chat_members` (unnest) → `COMMIT`. Неизвестный участник нарушает FK, транзакция откатывается целиком, клиент получает 400. Предварительной проверки участников нет: она была бы гонкой и маскировала бы откат.
**Сообщение** — `BEGIN` → `pg_advisory_xact_lock(2, hashtext(chat_id))` → `INSERT … created_at = GREATEST(clock_timestamp(), MAX(created_at) + 1 µs)` → `COMMIT`. Внутри чата `created_at` строго возрастает, и порядок коммитов совпадает с порядком `(created_at, id)`. Поэтому читатель с cursor не пропустит сообщение, вставленное «задним числом» конкурентной транзакцией. Это замена `asyncio.Lock` и `MonotonicClock` из lab1, корректная для нескольких процессов. Записи в один чат сериализуются, записи в разные чаты нет.
**Logout** — `UPDATE sessions SET revoked_at` для действующей сессии (0 строк → 401), затем `DEL` ключа в Valkey.
**Valkey.** Read-through кэш сессий: ключ `session:<sha256(token) hex>`, значение `{user, expires_at}`. При попадании в кэш аутентификация выполняется без SQL. Источник истины — таблица `sessions`, Valkey хранит только копию. TTL записи — `min(остаток жизни сессии, SESSION_CACHE_TTL_SECONDS=60)`, приложение дополнительно сверяет `expires_at`. Logout удаляет ключ после фиксации отзыва в БД; если Valkey в этот момент недоступен, запись может остаться не дольше 60 с, это логируется как warning.
**Persistence Valkey выключена** (`--save "" --appendonly no`). Valkey не единственное хранилище сессий: после рестарта или flush кэш пуст и заполняется из PostgreSQL, сессии не теряются. Заодно запись, не удалённая при logout во время сбоя, не «воскресает» после рестарта Valkey.
**Отказ Valkey.** Ошибка (таймаут 0.5 с, без встроенных повторов) переводит кэш в режим обхода на `VALKEY_RETRY_AFTER_SEC=5` с: все запросы идут в PostgreSQL без сетевых попыток к Valkey, сервис работает, `/health/ready` = 200.
**Readiness.** Критичен только PostgreSQL: `/health/ready` выполняет `SELECT 1`, без него ответ — `503 unavailable` без деталей SQL. Анонимный запрос — 401. Неизвестный токен при недоступной БД — 503, а не 200: доверие без проверки невозможно. Valkey не критичен.
**Пул и таймауты.** asyncpg: `min_size=2`, `max_size=10`, connect/acquire timeout 3 с, `command_timeout` 5 с и серверный `statement_timeout` 5 с. Ошибки соединения превращаются в `UnavailableError` (503); первая такая ошибка вызывает `pool.expire_connections()`, чтобы после рестарта PostgreSQL 503 получил один запрос, а не все соединения пула по очереди. Запросы только параметризованные (`$1…$n`), SQL написан в методах репозиториев, значения в текст запроса не подставляются.
| Переменная | Где используется | Значение в примере |
| --- | --- | --- |
| `APP_HOST` | адрес bind uvicorn; в контейнере обязательно `0.0.0.0` | `0.0.0.0` |
| `APP_PORT` | порт uvicorn, healthcheck, публикация порта в `compose.yaml` | `8080` |
| `APP_ENV` | имя окружения в логе запуска приложения | `lab` |
| `LOG_LEVEL` | уровень loguru | `INFO` |
| `SHUTDOWN_TIMEOUT_SEC` | `timeout_graceful_shutdown` uvicorn | `5` |
| `DB_USER`, `DB_PASS`, `DB_NAME`, `DB_HOST`, `DB_PORT` | подключение asyncpg; учётные данные сервиса `postgres`. В контейнере API `compose.yaml` подставляет `DB_HOST=postgres` | `test`, `test`, `test`, `localhost`, `5432` |
| `DB_POOL_MIN_SIZE`, `DB_POOL_MAX_SIZE` | границы пула asyncpg | `2`, `10` |
| `DB_CONNECT_TIMEOUT_SEC`, `DB_COMMAND_TIMEOUT_SEC` | таймаут подключения/ожидания соединения и выполнения запроса | `3`, `5` |
| `DB_STARTUP_TIMEOUT_SEC` | сколько ждать БД при старте API | `30` |
| `VALKEY_HOST`, `VALKEY_PORT`, `VALKEY_PASS` | подключение к Valkey; пароль сервиса `valkey`. В контейнере API `compose.yaml` подставляет `VALKEY_HOST=valkey` | `localhost`, `6379`, `test` |
| `VALKEY_POOL_MAX_SIZE`, `VALKEY_TIMEOUT_SEC`, `VALKEY_RETRY_AFTER_SEC` | пул redis-py, таймаут операции, пауза обхода кэша после ошибки | `20`, `0.5`, `5` |
| `SESSION_TTL_SECONDS` | срок жизни сессии | `3600` |
| `SESSION_CACHE_TTL_SECONDS` | верхняя граница TTL записи в Valkey | `60` |
| `PASSWORD_HASH_WORKERS` | потоки Argon2id: ограничение CPU/RAM на одновременные входы | `4` |
Переменные skeleton: `DATABASE_URL_FILE` заменён на `DB_*`, `CACHE_URL_FILE` — на `VALKEY_*`; `SESSION_STORE=postgres` соответствует реализации: сессии в PostgreSQL, Valkey — кэш.
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
Полный вывод команд сохранён в каталоге `evidence/`, имя файла указано в скобках.
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
| Критерий README | Команда/сценарий | Наблюдаемый результат |
| --- | --- | --- |
| 3: публичный smoke | `make check && make test` | `PASS: lab2 public API scenario` (smoke.txt) |
| 3: данные и действующие сессии переживают рестарт API и хранилищ | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | `PASS`; `StartedAt` у api, postgres, valkey изменился, volume сохранён, токен до рестарта работает после (persistence.txt) |
| 3: PK/FK, уникальность username, индексы | `\d+ messages`, `\di` | ограничения и индексы из миграции (migrations.txt) |
| 3: миграции с нуля и повторно без дублирования | `make test-migrations` | пустой volume: 0 таблиц → запуск 1 применяет `0001_init` → запуски 2–3 ничего не меняют (migrations_from_zero.txt) |
| 3: атомарное создание чата | `test_failed_chat_creation_is_rolled_back` | 400; в БД 0 строк `chats` с этим title и 0 участников-сирот (race_rollback.txt) |
| 3: Basic только на `POST /auth/sessions`, Bearer на остальных, X-User-Id не даёт доступа | `test_auth.py`, `test_users.py`, smoke | 401 с `WWW-Authenticate: Basic …` / `Bearer …`; Basic на бизнес-endpoint — 401; `X-User-Id` игнорируется (student_tests.txt) |
| 3: KDF паролей | `test_password_is_not_stored_in_plaintext` | в `users.password_hash` строка `$argon2id$…`, пароля нет (student_tests.txt) |
| 3: секреты и volumes не в Git | `git check-ignore .env`, `.gitignore` | `.env`, `volumes/`, `data/`, `secrets/` игнорируются |
| 4: Valkey реально используется для сессий с TTL | `test_valkey_down_cache_is_bypassed`, раздел «Valkey» | read-through кэш, TTL ≤ min(сессия, 60 с), DEL при logout (dependency_failures.txt) |
| 4: параметризованные запросы, ограниченный пул и таймауты | `infrastructure/repositories/*/postgres.py`, `dependencies/database.py`, `dependencies/cache.py` | только `$n`; пул 2..10; таймауты 3/5 с; Valkey ≤20, 0.5 с |
| 4: гонка регистрации одинакового username | `test_same_username_race_creates_exactly_one_user` | 20 параллельных запросов → 1×201, 19×409, 1 строка в БД (race_rollback.txt) |
| 4: rollback составной операции | `test_failed_chat_creation_is_rolled_back` | откат проверен по содержимому БД, а не только по ответу (race_rollback.txt) |
| 4: индекс истории и `EXPLAIN (ANALYZE, BUFFERS)` на ≥10 000 сообщениях | `make explain` | 138 769 сообщений, в чате 20 000. Страница из середины: `Index Scan … Index Cond: chat_id AND ROW(created_at,id) > ROW(…)`, 5 буферов, 0.036 мс; generic plan (как в asyncpg) — тот же Index Scan. Без индекса — `Parallel Seq Scan`, 128 768 строк отброшено, 1 792 буфера, 7.28 мс (explain_history.txt) |
| 4: expiry при коротком `SESSION_TTL_SECONDS` | `make test-expiry` | токен работает и попадает в кэш, через 3 с — 401 на `/users/me`, `/chats`, logout (expiry.txt) |
| 4: logout, неверный пароль | `test_logout_revokes_only_current_session`, `test_wrong_password_and_unknown_user_are_indistinguishable` | 204 без тела → 401 → повторный logout 401; другая сессия жива; неверный пароль и неизвестный логин дают одинаковый 401 (student_tests.txt) |
| 4: недоступность Valkey/БД | `make test-failures` | без Valkey вход, запись и logout работают, ответ < 3 с. Без PostgreSQL — `/health/ready` 503, аноним 401, неизвестный токен 503, регистрация/вход 503 без деталей. После рестарта PostgreSQL прежний токен работает (dependency_failures.txt) |
Сводка собственных тестов: `make student-test` — 87 passed, 6 skipped (их запускают `make test-expiry` и `make test-failures`).
## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
| `scripts/restart.sh`: рестарт postgres, valkey, api | данные и сессии на месте | PASS, прежний токен читает те же сообщения | ~2 с до ready; потерь нет |
| `docker compose stop valkey` | кэш обходится, API работает | вход, Bearer, запись, logout — OK, ready 200; один warning, далее 5 с без попыток | мгновенно; потерь нет (кэш) |
| logout при остановленном valkey, затем его старт | отозванный токен не принимается | 401 после подъёма: кэш без persistence пуст | — |
| `docker compose stop postgres` | ограниченный 503, без доверия анониму | ready 503, аноним 401, неизвестный токен 503, ответ < 3 с | — |
| `docker compose restart postgres` при живом API | API переподключается сам | после ready прежний токен работает | до ~2 с; данные на volume |
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
- Один Docker-host: отказ хоста, диска или единственного экземпляра PostgreSQL не переживается, реплик и бэкапов нет. HA для Valkey тоже нет, но он не критичен.
- `COMMIT` подтверждается после записи WAL на диск (`synchronous_commit=on`, `fsync=on`); гарантия ограничена честностью fsync в Docker Desktop VM и одним диском.
- Если Valkey недоступен ровно в момент logout, но не перезапускался (например, сетевой разрыв), отозванная сессия может приниматься ещё до 60 с. Граница задаётся `SESSION_CACHE_TTL_SECONDS`.
- Запись в один чат сериализуется advisory lock: пропускная способность одного «горячего» чата ограничена. Коллизии `hashtext` изредка сериализуют разные чаты.
- Символ U+0000 в `text`/`title`/`display_name` отклоняется с 400: тип `text` в PostgreSQL его не хранит. Тест lab1 с `\u0000` заменён на отдельный тест отказа.
- Список чатов пользователя сортируется по `(created_at, id)` после соединения `chat_members` → `chats`, отдельного keyset-индекса нет. Для пользователя с тысячами чатов понадобится денормализация `created_at` в `chat_members`.
- Устаревшие строки `sessions` не удаляются: фоновой очистки пока нет.
- `expire_connections` срабатывает на первой ошибке соединения; запрос, который на неё попал, получает 503 и не повторяется прозрачно — автоматических повторов POST нет намеренно.
+88
View File
@@ -0,0 +1,88 @@
name: messenger-lab2
x-api: &api
build: .
image: mtusi-messenger:lab2
restart: unless-stopped
env_file:
- .env
environment:
DB_HOST: postgres
VALKEY_HOST: valkey
depends_on:
postgres:
condition: service_healthy
valkey:
condition: service_started
networks:
- backend
- default
stop_grace_period: 10s
services:
postgres:
image: postgres:18.2-alpine3.22
restart: unless-stopped
environment:
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASS}
POSTGRES_DB: ${DB_NAME}
volumes:
- postgres_data:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\""]
interval: 2s
timeout: 3s
retries: 15
start_period: 10s
networks:
- backend
stop_grace_period: 30s
valkey:
image: valkey/valkey:8.1.4-alpine3.22
restart: unless-stopped
environment:
VALKEY_PASS: ${VALKEY_PASS}
command:
- valkey-server
- --requirepass
- ${VALKEY_PASS}
- --save
- ""
- --appendonly
- "no"
- --maxmemory
- 64mb
- --maxmemory-policy
- allkeys-lru
healthcheck:
test: ["CMD-SHELL", "valkey-cli --no-auth-warning -a \"$$VALKEY_PASS\" ping | grep -q PONG"]
interval: 2s
timeout: 3s
retries: 15
networks:
- backend
api:
<<: *api
ports:
- "127.0.0.1:${APP_PORT}:${APP_PORT}"
api-short-ttl:
<<: *api
profiles:
- expiry
environment:
DB_HOST: postgres
VALKEY_HOST: valkey
SESSION_TTL_SECONDS: "2"
ports:
- "127.0.0.1:8081:${APP_PORT}"
networks:
backend:
internal: true
volumes:
postgres_data:
-9
View File
@@ -1,9 +0,0 @@
services:
messenger:
build: .
image: mtusi-messenger:lab2
container_name: mtusi-messenger-lab2
env_file:
- .env
ports:
- "127.0.0.1:${APP_PORT}:${APP_PORT}"
+27
View File
@@ -0,0 +1,27 @@
$ make test-failures
BASE_URL="http://localhost:8080" RUN_FAILURE_TESTS=1 poetry run pytest student-tests/test_dependency_failures.py -s
/Users/enterxx/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
============================= test session starts ==============================
platform darwin -- Python 3.12.12, pytest-9.1.1, pluggy-1.6.0 -- /Users/enterxx/Library/Caches/pypoetry/virtualenvs/max2-TbR4RJXC-py3.12/bin/python
cachedir: .pytest_cache
rootdir: /Users/enterxx/Desktop/university/4course/mtusi2026lab2
configfile: pyproject.toml
plugins: anyio-4.15.1
collecting ... collected 4 items
student-tests/test_dependency_failures.py::test_valkey_down_cache_is_bypassed PASSED
student-tests/test_dependency_failures.py::test_logout_during_valkey_outage_is_not_resurrected PASSED
student-tests/test_dependency_failures.py::test_postgres_down_returns_bounded_503_and_no_anonymous_access PASSED
student-tests/test_dependency_failures.py::test_session_survives_postgres_restart PASSED
============================== 4 passed in 11.94s ==============================
$ docker compose logs --no-log-prefix --since 2026-10-11T14:41:19Z api | grep WARNING
2026-10-11 14:41:20.418 | WARNING | infrastructure.dependencies.cache:mark_failed:69 - Valkey недоступен (ConnectionError): кэш сессий обходится 5.0 с, запросы идут в PostgreSQL
2026-10-11 14:41:20.434 | WARNING | infrastructure.services.auth_service.auth_service:logout:88 - Сессия отозвана в PostgreSQL, но запись кэша не удалена: она истечёт по TTL кэша
2026-10-11 14:41:23.079 | WARNING | infrastructure.services.auth_service.auth_service:logout:88 - Сессия отозвана в PostgreSQL, но запись кэша не удалена: она истечёт по TTL кэша
2026-10-11 14:41:25.665 | WARNING | infrastructure.utils.repository_utils:wrapper:34 - Request to DATABASE || Object: PostgresSessionRepository || Function: get_active || failed || Error: gaierror
2026-10-11 14:41:25.712 | WARNING | infrastructure.utils.repository_utils:wrapper:34 - Request to DATABASE || Object: PostgresUserRepository || Function: create || failed || Error: gaierror
2026-10-11 14:41:25.719 | WARNING | infrastructure.utils.repository_utils:wrapper:34 - Request to DATABASE || Object: PostgresUserRepository || Function: get_credentials || failed || Error: gaierror
+89
View File
@@ -0,0 +1,89 @@
$ make test-expiry
docker compose --profile expiry up -d --build --wait api-short-ttl
#1 [internal] load local bake definitions
#1 reading from stdin 597B done
#1 DONE 0.0s
#2 [internal] load build definition from Dockerfile
#2 transferring dockerfile: 642B done
#2 DONE 0.0s
#3 [internal] load metadata for docker.io/library/python:3.12.12-slim-bookworm
#3 DONE 0.0s
#4 [internal] load .dockerignore
#4 transferring context: 328B done
#4 DONE 0.0s
#5 [1/7] FROM docker.io/library/python:3.12.12-slim-bookworm@sha256:593bd06efe90efa80dc4eee3948be7c0fde4134606dd40d8dd8dbcade98e669c
#5 resolve docker.io/library/python:3.12.12-slim-bookworm@sha256:593bd06efe90efa80dc4eee3948be7c0fde4134606dd40d8dd8dbcade98e669c done
#5 DONE 0.0s
#6 [internal] load build context
#6 transferring context: 117.69kB 0.0s done
#6 DONE 0.0s
#7 [3/7] COPY poetry.lock pyproject.toml ./
#7 CACHED
#8 [2/7] WORKDIR /app
#8 CACHED
#9 [5/7] COPY migrations ./migrations
#9 CACHED
#10 [4/7] RUN pip install --no-cache-dir "poetry==2.2.1" && poetry install --only main --no-root --no-interaction
#10 CACHED
#11 [6/7] COPY src ./src
#11 CACHED
#12 [7/7] RUN useradd --system --uid 10001 --no-create-home app
#12 CACHED
#13 exporting to image
#13 exporting layers done
#13 exporting manifest sha256:38c2dfc7141796ce2219a46fa351316f15c1c687a9a09ec702887d0f351165ce done
#13 exporting config sha256:1ab109ba0df31f1aa4ef7fca42802a75b11b456dfa73dcb4ec54117b4909cbc0 done
#13 exporting attestation manifest sha256:0131ba669988c7b2d51762370da624bd434ef64b4ea09b95b4a6e12458b0a1f8 done
#13 exporting manifest list sha256:95d9d58148c7c6842d3fbb4b4531522da5e203f013ddedd1e566fcd118a6c71c done
#13 naming to docker.io/library/mtusi-messenger:lab2 done
#13 unpacking to docker.io/library/mtusi-messenger:lab2 done
#13 DONE 0.0s
#14 resolving provenance for metadata file
#14 DONE 0.0s
mtusi-messenger:lab2 Built
Container messenger-lab2-valkey-1 Running
Container messenger-lab2-postgres-1 Running
Container messenger-lab2-api-short-ttl-1 Recreate
Container messenger-lab2-api-short-ttl-1 Recreated
Container messenger-lab2-postgres-1 Waiting
Container messenger-lab2-postgres-1 Healthy
Container messenger-lab2-api-short-ttl-1 Starting
Container messenger-lab2-api-short-ttl-1 Started
Container messenger-lab2-valkey-1 Waiting
Container messenger-lab2-api-short-ttl-1 Waiting
Container messenger-lab2-postgres-1 Waiting
Container messenger-lab2-valkey-1 Healthy
Container messenger-lab2-postgres-1 Healthy
Container messenger-lab2-api-short-ttl-1 Healthy
EXPIRY_BASE_URL=http://localhost:8081 poetry run pytest student-tests/test_expiry.py -s; \
status=$?; docker compose --profile expiry stop api-short-ttl; exit $status
/Users/enterxx/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
============================= test session starts ==============================
platform darwin -- Python 3.12.12, pytest-9.1.1, pluggy-1.6.0 -- /Users/enterxx/Library/Caches/pypoetry/virtualenvs/max2-TbR4RJXC-py3.12/bin/python
cachedir: .pytest_cache
rootdir: /Users/enterxx/Desktop/university/4course/mtusi2026lab2
configfile: pyproject.toml
plugins: anyio-4.15.1
collecting ... collected 2 items
student-tests/test_expiry.py::test_session_expires_after_short_ttl PASSED
student-tests/test_expiry.py::test_expires_at_matches_short_ttl PASSED
============================== 2 passed in 3.26s ===============================
Container messenger-lab2-api-short-ttl-1 Stopping
Container messenger-lab2-api-short-ttl-1 Stopped
+96
View File
@@ -0,0 +1,96 @@
== Объём данных
messages_total | messages_in_big_chat | messages_heap | history_index
----------------+----------------------+---------------+---------------
138769 | 20000 | 14 MB | 8000 kB
(1 row)
== 1. Первая страница истории (limit 50 + 1), как list_for_chat
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------
Limit (actual time=0.008..0.012 rows=51.00 loops=1)
Buffers: shared hit=4
-> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.007..0.009 rows=51.00 loops=1)
Index Cond: (chat_id = '01a10705-59d7-70b2-aa32-64965b148b34'::uuid)
Index Searches: 1
Buffers: shared hit=4
Planning:
Buffers: shared hit=6
Planning Time: 0.092 ms
Execution Time: 0.026 ms
(10 rows)
== 2. Страница из середины по cursor (после 10 000-го), как list_for_chat_after
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=0.007..0.012 rows=51.00 loops=1)
Buffers: shared hit=5
-> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.007..0.010 rows=51.00 loops=1)
Index Cond: ((chat_id = '01a10705-59d7-70b2-aa32-64965b148b34'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 02:46:40+00'::timestamp with time zone, '01a10705-59eb-73d8-aa15-9a1a496ee297'::uuid)))
Index Searches: 1
Buffers: shared hit=5
Planning Time: 0.044 ms
Execution Time: 0.036 ms
(8 rows)
== 3. Тот же запрос как generic plan prepared statement (так его исполняет asyncpg)
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------
Limit (actual time=0.008..0.012 rows=51.00 loops=1)
Buffers: shared hit=5
-> Index Scan using messages_chat_id_created_at_id_idx on messages (actual time=0.007..0.009 rows=51.00 loops=1)
Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3)))
Index Searches: 1
Buffers: shared hit=5
Planning Time: 0.041 ms
Execution Time: 0.022 ms
(8 rows)
== 4. MAX(created_at) при вставке сообщения (монотонное время чата)
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------
Result (actual time=0.008..0.008 rows=1.00 loops=1)
Buffers: shared hit=4
InitPlan 1
-> Limit (actual time=0.007..0.007 rows=1.00 loops=1)
Buffers: shared hit=4
-> Index Only Scan Backward using messages_chat_id_created_at_id_idx on messages (actual time=0.007..0.007 rows=1.00 loops=1)
Index Cond: (chat_id = '01a10705-59d7-70b2-aa32-64965b148b34'::uuid)
Heap Fetches: 0
Index Searches: 1
Buffers: shared hit=4
Planning:
Buffers: shared hit=3
Planning Time: 0.041 ms
Execution Time: 0.015 ms
(14 rows)
== 5. Для сравнения: тот же запрос из середины БЕЗ индекса истории
(DROP INDEX внутри транзакции с ROLLBACK — индекс не теряется)
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=6.360..7.265 rows=51.00 loops=1)
Buffers: shared hit=1792
-> Gather Merge (actual time=6.360..7.262 rows=51.00 loops=1)
Workers Planned: 1
Workers Launched: 1
Buffers: shared hit=1792
-> Sort (actual time=2.069..2.073 rows=25.50 loops=2)
Sort Key: created_at, id
Sort Method: top-N heapsort Memory: 31kB
Buffers: shared hit=1792
Worker 0: Sort Method: quicksort Memory: 25kB
-> Parallel Seq Scan on messages (actual time=0.183..1.840 rows=5000.00 loops=2)
Filter: ((chat_id = '01a10705-59d7-70b2-aa32-64965b148b34'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 02:46:40+00'::timestamp with time zone, '01a10705-59eb-73d8-aa15-9a1a496ee297'::uuid)))
Rows Removed by Filter: 64384
Buffers: shared hit=1777
Planning:
Buffers: shared hit=4
Planning Time: 0.045 ms
Execution Time: 7.283 ms
(19 rows)
+54
View File
@@ -0,0 +1,54 @@
$ docker compose logs --no-log-prefix api | grep -E 'миграци|Схема БД'
2026-10-11 14:40:39.798 | INFO | infrastructure.dependencies.database:apply_migrations:156 - Схема БД в актуальной версии
2026-10-11 14:40:48.046 | INFO | infrastructure.dependencies.database:apply_migrations:156 - Схема БД в актуальной версии
$ docker compose exec -T postgres sh -c 'psql -X -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT * FROM schema_migrations"'
version | name | applied_at
---------+-----------+-------------------------------
1 | 0001_init | 2026-10-04 13:01:32.330387+00
(1 row)
$ docker compose exec -T postgres sh -c 'psql -X -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "\d+ messages"'
Table "public.messages"
Column | Type | Collation | Nullable | Default | Storage | Compression | Stats target | Description
------------+--------------------------+-----------+----------+----------+----------+-------------+--------------+-------------
id | uuid | | not null | uuidv7() | plain | | |
chat_id | uuid | | not null | | plain | | |
sender_id | uuid | | not null | | plain | | |
text | text | | not null | | extended | | |
created_at | timestamp with time zone | | not null | | plain | | |
Indexes:
"messages_pkey" PRIMARY KEY, btree (id)
"messages_chat_id_created_at_id_idx" btree (chat_id, created_at, id)
Check constraints:
"messages_text_len" CHECK (char_length(text) >= 1 AND char_length(text) <= 4000)
Foreign-key constraints:
"messages_sender_member_fkey" FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id) ON DELETE CASCADE
Not-null constraints:
"messages_id_not_null" NOT NULL "id"
"messages_chat_id_not_null" NOT NULL "chat_id"
"messages_sender_id_not_null" NOT NULL "sender_id"
"messages_text_not_null" NOT NULL "text"
"messages_created_at_not_null" NOT NULL "created_at"
Access method: heap
$ docker compose exec -T postgres sh -c 'psql -X -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "\di"'
List of indexes
Schema | Name | Type | Owner | Table
--------+------------------------------------+-------+-----------+-------------------
public | chat_members_pkey | index | messenger | chat_members
public | chat_members_position_key | index | messenger | chat_members
public | chat_members_user_id_chat_id_idx | index | messenger | chat_members
public | chats_pkey | index | messenger | chats
public | messages_chat_id_created_at_id_idx | index | messenger | messages
public | messages_pkey | index | messenger | messages
public | schema_migrations_pkey | index | messenger | schema_migrations
public | sessions_pkey | index | messenger | sessions
public | sessions_user_id_idx | index | messenger | sessions
public | users_pkey | index | messenger | users
public | users_username_key | index | messenger | users
(11 rows)
+15
View File
@@ -0,0 +1,15 @@
$ make test-migrations
./scripts/check_migrations.sh
Network messenger-lab2-migrations-check_default Creating
Network messenger-lab2-migrations-check_default Created
2026-10-11 14:40:55.908 | INFO | infrastructure.dependencies.database:create_pool:69 - Установка соединения с базой данных psql
2026-10-11 14:40:55.938 | INFO | infrastructure.dependencies.database:create_pool:99 - Соединение с базой данных psql установлено. DB_NAME: messenger, pool: 2..10
пустой volume: таблиц в public = 0
2026-10-11 14:40:55.960 | INFO | infrastructure.dependencies.database:apply_migrations:151 - Применена миграция 0001_init.sql
2026-10-11 14:40:55.961 | INFO | infrastructure.dependencies.database:apply_migrations:156 - Схема БД в актуальной версии
запуск 1: schema_migrations = [(1, '0001_init')], таблиц = 6
2026-10-11 14:40:55.962 | INFO | infrastructure.dependencies.database:apply_migrations:156 - Схема БД в актуальной версии
запуск 2: schema_migrations = [(1, '0001_init')], таблиц = 6
2026-10-11 14:40:55.963 | INFO | infrastructure.dependencies.database:apply_migrations:156 - Схема БД в актуальной версии
запуск 3: schema_migrations = [(1, '0001_init')], таблиц = 6
+23
View File
@@ -0,0 +1,23 @@
$ docker inspect -f '{{.Name}} {{.State.StartedAt}}' messenger-lab2-api-1 messenger-lab2-postgres-1 messenger-lab2-valkey-1
/messenger-lab2-api-1 2026-10-11T14:40:38.947015458Z
/messenger-lab2-postgres-1 2026-10-11T12:57:22.164526672Z
/messenger-lab2-valkey-1 2026-10-11T12:57:22.228188756Z
$ docker volume ls --filter name=messenger-lab2
DRIVER VOLUME NAME
local messenger-lab2_postgres_data
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
python3 tests/resilience.py --mode 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.
$ docker inspect -f '{{.Name}} {{.State.StartedAt}}' messenger-lab2-api-1 messenger-lab2-postgres-1 messenger-lab2-valkey-1
/messenger-lab2-api-1 2026-10-11T14:40:47.267238587Z
/messenger-lab2-postgres-1 2026-10-11T14:40:46.679260379Z
/messenger-lab2-valkey-1 2026-10-11T14:40:46.639763379Z
$ docker volume ls --filter name=messenger-lab2
DRIVER VOLUME NAME
local messenger-lab2_postgres_data
+22
View File
@@ -0,0 +1,22 @@
$ poetry run pytest student-tests/test_transactions.py student-tests/test_concurrency.py -s
/Users/enterxx/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
============================= test session starts ==============================
platform darwin -- Python 3.12.12, pytest-9.1.1, pluggy-1.6.0 -- /Users/enterxx/Library/Caches/pypoetry/virtualenvs/max2-TbR4RJXC-py3.12/bin/python
cachedir: .pytest_cache
rootdir: /Users/enterxx/Desktop/university/4course/mtusi2026lab2
configfile: pyproject.toml
plugins: anyio-4.15.1
collecting ... collected 4 items
student-tests/test_transactions.py::test_same_username_race_creates_exactly_one_user
REGISTRATION RACE: {"requests": 20, "status_201": 1, "status_409": 19, "rows_in_db": 1}
PASSED
student-tests/test_transactions.py::test_failed_chat_creation_is_rolled_back PASSED
student-tests/test_transactions.py::test_successful_chat_creation_commits_all_members PASSED
student-tests/test_concurrency.py::test_parallel_messages_are_not_lost_or_duplicated
CONCURRENCY RESULT: {"clients": 10, "messages_sent": 100, "status_201": 100, "messages_read": 100, "unique_ids": 100, "unique_texts": 100, "pages_read": 4, "send_seconds": 0.275}
PASSED
============================== 4 passed in 1.95s ===============================
+8
View File
@@ -0,0 +1,8 @@
$ make check
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
$ make test
python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
+109
View File
@@ -0,0 +1,109 @@
$ make student-test
BASE_URL="http://localhost:8080" poetry run pytest
/Users/enterxx/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
============================= test session starts ==============================
platform darwin -- Python 3.12.12, pytest-9.1.1, pluggy-1.6.0 -- /Users/enterxx/Library/Caches/pypoetry/virtualenvs/max2-TbR4RJXC-py3.12/bin/python
cachedir: .pytest_cache
rootdir: /Users/enterxx/Desktop/university/4course/mtusi2026lab2
configfile: pyproject.toml
testpaths: student-tests
plugins: anyio-4.15.1
collecting ... collected 93 items
student-tests/test_auth.py::test_login_returns_opaque_bearer_session PASSED [ 1%]
student-tests/test_auth.py::test_wrong_password_and_unknown_user_are_indistinguishable PASSED [ 2%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[None] PASSED [ 3%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[] PASSED [ 4%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[Basic] PASSED [ 5%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[Basic !!!not-base64!!!] PASSED [ 6%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[Basic bm8tY29sb24taGVyZQ==] PASSED [ 7%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[Basic //46cGFzc3dvcmQ=] PASSED [ 8%]
student-tests/test_auth.py::test_malformed_basic_is_unauthorized[Bearer some-token] PASSED [ 9%]
student-tests/test_auth.py::test_utf8_password_with_colon PASSED [ 10%]
student-tests/test_auth.py::test_basic_is_rejected_on_business_endpoints PASSED [ 11%]
student-tests/test_auth.py::test_logout_revokes_only_current_session PASSED [ 12%]
student-tests/test_auth.py::test_logout_without_token PASSED [ 13%]
student-tests/test_auth.py::test_relogin_after_logout PASSED [ 15%]
student-tests/test_auth.py::test_password_is_not_stored_in_plaintext PASSED [ 16%]
student-tests/test_concurrency.py::test_parallel_messages_are_not_lost_or_duplicated PASSED [ 17%]
student-tests/test_dependency_failures.py::test_valkey_down_cache_is_bypassed SKIPPED [ 18%]
student-tests/test_dependency_failures.py::test_logout_during_valkey_outage_is_not_resurrected SKIPPED [ 19%]
student-tests/test_dependency_failures.py::test_postgres_down_returns_bounded_503_and_no_anonymous_access SKIPPED [ 20%]
student-tests/test_dependency_failures.py::test_session_survives_postgres_restart SKIPPED [ 21%]
student-tests/test_expiry.py::test_session_expires_after_short_ttl SKIPPED [ 22%]
student-tests/test_expiry.py::test_expires_at_matches_short_ttl SKIPPED [ 23%]
student-tests/test_foreign_chat.py::test_outsider_cannot_access_chat PASSED [ 24%]
student-tests/test_foreign_chat.py::test_foreign_and_missing_chat_are_indistinguishable PASSED [ 25%]
student-tests/test_foreign_chat.py::test_chat_list_contains_only_own_chats PASSED [ 26%]
student-tests/test_health.py::test_health_endpoints_have_request_id PASSED [ 27%]
student-tests/test_health.py::test_unknown_route_uses_error_format PASSED [ 29%]
student-tests/test_invalid_json.py::test_malformed_json_on_register[{"username": "abc",] PASSED [ 30%]
student-tests/test_invalid_json.py::test_malformed_json_on_register[not json at all] PASSED [ 31%]
student-tests/test_invalid_json.py::test_malformed_json_on_register[{"text": "\xff\xfe"}] PASSED [ 32%]
student-tests/test_invalid_json.py::test_malformed_json_on_register[] PASSED [ 33%]
student-tests/test_invalid_json.py::test_malformed_json_on_create_chat_and_message[{"username": "abc",] PASSED [ 34%]
student-tests/test_invalid_json.py::test_malformed_json_on_create_chat_and_message[not json at all] PASSED [ 35%]
student-tests/test_invalid_json.py::test_malformed_json_on_create_chat_and_message[{"text": "\xff\xfe"}] PASSED [ 36%]
student-tests/test_invalid_json.py::test_malformed_json_on_create_chat_and_message[] PASSED [ 37%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body0] PASSED [ 38%]
student-tests/test_invalid_json.py::test_invalid_user_payload[alice] PASSED [ 39%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body2] PASSED [ 40%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body3] PASSED [ 41%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body4] PASSED [ 43%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body5] PASSED [ 44%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body6] PASSED [ 45%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body7] PASSED [ 46%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body8] PASSED [ 47%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body9] PASSED [ 48%]
student-tests/test_invalid_json.py::test_invalid_user_payload[body10] PASSED [ 49%]
student-tests/test_invalid_json.py::test_invalid_message_payload[body0] PASSED [ 50%]
student-tests/test_invalid_json.py::test_invalid_message_payload[body1] PASSED [ 51%]
student-tests/test_invalid_json.py::test_invalid_message_payload[body2] PASSED [ 52%]
student-tests/test_invalid_json.py::test_invalid_chat_payload PASSED [ 53%]
student-tests/test_messages.py::test_empty_or_blank_message_is_rejected[] PASSED [ 54%]
student-tests/test_messages.py::test_empty_or_blank_message_is_rejected[ ] PASSED [ 55%]
student-tests/test_messages.py::test_empty_or_blank_message_is_rejected[ \n\t ] PASSED [ 56%]
student-tests/test_messages.py::test_empty_or_blank_message_is_rejected[\u3000] PASSED [ 58%]
student-tests/test_messages.py::test_message_length_is_counted_in_code_points PASSED [ 59%]
student-tests/test_messages.py::test_unicode_is_preserved PASSED [ 60%]
student-tests/test_messages.py::test_nul_character_is_rejected PASSED [ 61%]
student-tests/test_messages.py::test_sender_is_taken_from_session PASSED [ 62%]
student-tests/test_pagination.py::test_walk_message_pages[7-3-3] PASSED [ 63%]
student-tests/test_pagination.py::test_walk_message_pages[6-3-2] PASSED [ 64%]
student-tests/test_pagination.py::test_walk_message_pages[5-1-5] PASSED [ 65%]
student-tests/test_pagination.py::test_walk_message_pages[3-100-1] PASSED [ 66%]
student-tests/test_pagination.py::test_limit_can_change_between_pages PASSED [ 67%]
student-tests/test_pagination.py::test_new_message_appears_after_cursor PASSED [ 68%]
student-tests/test_pagination.py::test_cursor_is_bound_to_chat PASSED [ 69%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params0] PASSED [ 70%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params1] PASSED [ 72%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params2] PASSED [ 73%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params3] PASSED [ 74%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params4] PASSED [ 75%]
student-tests/test_pagination.py::test_invalid_limit_or_cursor[params5] PASSED [ 76%]
student-tests/test_pagination.py::test_walk_chat_list_pages PASSED [ 77%]
student-tests/test_pagination.py::test_chat_cursor_is_bound_to_user PASSED [ 78%]
student-tests/test_transactions.py::test_same_username_race_creates_exactly_one_user PASSED [ 79%]
student-tests/test_transactions.py::test_failed_chat_creation_is_rolled_back PASSED [ 80%]
student-tests/test_transactions.py::test_successful_chat_creation_commits_all_members PASSED [ 81%]
student-tests/test_users.py::test_duplicate_username_is_conflict PASSED [ 82%]
student-tests/test_users.py::test_registration_never_returns_password PASSED [ 83%]
student-tests/test_users.py::test_invalid_password_is_rejected[None] PASSED [ 84%]
student-tests/test_users.py::test_invalid_password_is_rejected[] PASSED [ 86%]
student-tests/test_users.py::test_invalid_password_is_rejected[\u043a\u043e\u0440\u043e\u0442\u043a\u0438\u0439] PASSED [ 87%]
student-tests/test_users.py::test_invalid_password_is_rejected[xxxxxxxxxxx] PASSED [ 88%]
student-tests/test_users.py::test_invalid_password_is_rejected[xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx] PASSED [ 89%]
student-tests/test_users.py::test_invalid_password_is_rejected[123456789012] PASSED [ 90%]
student-tests/test_users.py::test_password_length_is_counted_in_code_points PASSED [ 91%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers0] PASSED [ 92%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers1] PASSED [ 93%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers2] PASSED [ 94%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers3] PASSED [ 95%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers4] PASSED [ 96%]
student-tests/test_users.py::test_missing_or_unknown_token_is_unauthorized[headers5] PASSED [ 97%]
student-tests/test_users.py::test_x_user_id_gives_no_access PASSED [ 98%]
student-tests/test_users.py::test_current_user PASSED [100%]
======================== 87 passed, 6 skipped in 7.11s =========================
+60
View File
@@ -0,0 +1,60 @@
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT uuidv7(),
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT users_username_key UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
-- Источник истины для сессий; токен хранится только как SHA-256
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
CONSTRAINT sessions_token_hash_len CHECK (octet_length(token_hash) = 32),
CONSTRAINT sessions_expiry_order CHECK (expires_at > created_at)
);
CREATE INDEX sessions_user_id_idx ON sessions (user_id);
CREATE TABLE chats (
id uuid PRIMARY KEY DEFAULT uuidv7(),
title text NOT NULL,
created_by uuid NOT NULL REFERENCES users (id),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
);
-- position сохраняет порядок member_ids из запроса создания
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id),
position smallint NOT NULL,
PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_position_key UNIQUE (chat_id, position)
);
-- Список чатов пользователя: WHERE user_id = $1
CREATE INDEX chat_members_user_id_chat_id_idx ON chat_members (user_id, chat_id);
-- created_at назначает приложение под блокировкой чата (строго возрастает в чате)
CREATE TABLE messages (
id uuid PRIMARY KEY DEFAULT uuidv7(),
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000),
-- отправитель обязан быть участником этого чата
CONSTRAINT messages_sender_member_fkey FOREIGN KEY (chat_id, sender_id)
REFERENCES chat_members (chat_id, user_id) ON DELETE CASCADE
);
-- Keyset-пагинация истории: WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
-- ORDER BY created_at, id LIMIT $4 — Index Scan без сортировки и полного прохода
CREATE INDEX messages_chat_id_created_at_id_idx ON messages (chat_id, created_at, id);
Generated
+283 -1
View File
@@ -43,6 +43,145 @@ typing_extensions = {version = ">=4.16.0", markers = "python_version < \"3.15\""
[package.extras]
trio = ["trio (>=0.32.0)"]
[[package]]
name = "argon2-cffi"
version = "25.1.0"
description = "Argon2 for Python"
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "argon2_cffi-25.1.0-py3-none-any.whl", hash = "sha256:fdc8b074db390fccb6eb4a3604ae7231f219aa669a2652e0f20e16ba513d5741"},
{file = "argon2_cffi-25.1.0.tar.gz", hash = "sha256:694ae5cc8a42f4c4e2bf2ca0e64e51e23a040c6a517a85074683d3959e1346c1"},
]
[package.dependencies]
argon2-cffi-bindings = "*"
[[package]]
name = "argon2-cffi-bindings"
version = "26.1.0"
description = "Low-level CFFI bindings for Argon2"
optional = false
python-versions = ">=3.10"
groups = ["main"]
files = [
{file = "argon2_cffi_bindings-26.1.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:21ca0396fe5ec995dd54431c32698189666f9224810acfa752e50d2bd94d9df2"},
{file = "argon2_cffi_bindings-26.1.0-cp310-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:78de2d65e0b9ea7ce9d1b1c3e87297b2d7305a02c266ee2a2d6910daddd7ee69"},
{file = "argon2_cffi_bindings-26.1.0-cp310-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:27f1821903e2ceadcb88ec2b45ef190897b7682449c772f4d9b53e42c520cf29"},
{file = "argon2_cffi_bindings-26.1.0-cp310-abi3-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d88e5f7e60f28ae0b0cc6b2f16c43e87cd642a196a86f85e0d8bb6fe016fc16d"},
{file = "argon2_cffi_bindings-26.1.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:34b7d9c24a4165a2c61cc8ae11d44d48c9ce2830fb536cb7914e11fdd9962728"},
{file = "argon2_cffi_bindings-26.1.0-cp310-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:224865cbbcb7a2bd1356741dff12b0134df726b6d44bb7b500df8e303cbd9e81"},
{file = "argon2_cffi_bindings-26.1.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ffff613aaa9ce6236766e2fc6dc560bb5abde7a2e2416e3db1f9ae395a2b4dd4"},
{file = "argon2_cffi_bindings-26.1.0-cp310-abi3-win32.whl", hash = "sha256:a86c069c91a747a2c4e5c51473590aeb48172fff9b2130d23729a42d98665ecb"},
{file = "argon2_cffi_bindings-26.1.0-cp310-abi3-win_amd64.whl", hash = "sha256:2c36ff87b5dfaa477d0bd51e9d7f6abdae7c8955d2983c97419085d842154b3e"},
{file = "argon2_cffi_bindings-26.1.0-cp310-abi3-win_arm64.whl", hash = "sha256:f9c4420a7a864fe1b86ce35befc95b8e39fb852493b81cf798671ddc265de638"},
{file = "argon2_cffi_bindings-26.1.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:af11ac37a7c53dc16cb7950a6190851b0870fe218b6c60c0bb7ac355234e3083"},
{file = "argon2_cffi_bindings-26.1.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:db0fcd827ca61622a01b220aadfbece01939acf53888f2cb98cd93e9b1e2c97e"},
{file = "argon2_cffi_bindings-26.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:28524438cd3e723f25412f63d4fd516ff5bae9ae5aa56acbe2a1404398a0cf31"},
{file = "argon2_cffi_bindings-26.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ac82fc756a446b6ccd7139ce70efa9d8bbe541e7ad579a12dcb52764b7175c5f"},
{file = "argon2_cffi_bindings-26.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6a4e68eed961a8de6928d1c17ff3dc2a547e0e923c17f8f1cd79fb7bc9502f98"},
{file = "argon2_cffi_bindings-26.1.0-cp314-cp314t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:151dfaad9de753f4af2a7854e707e4784f2acc434340ade64239c5b104b2d605"},
{file = "argon2_cffi_bindings-26.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:061a6919145bbf282ebf1f9c59d3135d4833c25313c8595c0d68cf7712ddfce2"},
{file = "argon2_cffi_bindings-26.1.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:62ff20cd130c956c7c9144d5fe35228f98b51c579b2439e988b27ef93e16c02a"},
{file = "argon2_cffi_bindings-26.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:19423e5d7ac1cc354baab59eaabf18db2ec04ef6593b5abe5a34f323c4a8f87a"},
{file = "argon2_cffi_bindings-26.1.0-cp314-cp314t-win32.whl", hash = "sha256:4f84cdd868978d7b7350a566c254042d44216d9e37f241f3a6d3b1dfebeede35"},
{file = "argon2_cffi_bindings-26.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:2b741888c93147444fdfc851abd81cc207f37f7f7da42062a00deb3888e57da8"},
{file = "argon2_cffi_bindings-26.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:6ab674f668d5962a3a4136ae0812519b0f1586874263723a32181d60d64137e1"},
{file = "argon2_cffi_bindings-26.1.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1d98e33bd8bd67d7206c124e200bf2229c4cfa8c9c19f7b44a897f0fc71837eb"},
{file = "argon2_cffi_bindings-26.1.0-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ccaf0a46cbb380f1fd102a874e32aa629fd3cb0c0e94f4943fa1f6d5edc5dac6"},
{file = "argon2_cffi_bindings-26.1.0-cp315-cp315t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f0c3103fcff20183e593459cfea6e012281c0e76ae3ed8b5565ad1b92eac3990"},
{file = "argon2_cffi_bindings-26.1.0-cp315-cp315t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c49e853a3bef9dd10329f31f702e7fa9b5c58229ff9c2ff6d069efaf09177c08"},
{file = "argon2_cffi_bindings-26.1.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:6376d4b3aca039375ca8bf92f770da0ec424a1ce3a37077a8d3c557411aa56ca"},
{file = "argon2_cffi_bindings-26.1.0-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:9bacedc04b0402837586a17f0919e3dfdd95291f441f1f56bd80ec274c2840a1"},
{file = "argon2_cffi_bindings-26.1.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:76ae29acace5d33355344612844d588e19deaaba4639d8bb01601e4b1418ef36"},
{file = "argon2_cffi_bindings-26.1.0-cp315-cp315t-win32.whl", hash = "sha256:df612391feca41c44d20118f3b88d1b86419465cd1f5496859f715ca60ec2210"},
{file = "argon2_cffi_bindings-26.1.0-cp315-cp315t-win_amd64.whl", hash = "sha256:1a0a29ed86960e44eaace7e081bdfab4f08b012fd96ec8edba71e2ad020939e4"},
{file = "argon2_cffi_bindings-26.1.0-cp315-cp315t-win_arm64.whl", hash = "sha256:d157ddfab1e8b21f2f1dedda9c09645d98b5ed0b667b0626be600a345d426440"},
{file = "argon2_cffi_bindings-26.1.0-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:7014ab7e6f5d8511af92544667a0346ea6dfc314ea9a7cad1dba9fdb5c9a6e33"},
{file = "argon2_cffi_bindings-26.1.0-pp310-pypy310_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:242bb0cda2ae3650764fc194593d9ea45fc9e72729acd89778c7cfe184cec2a5"},
{file = "argon2_cffi_bindings-26.1.0-pp310-pypy310_pp73-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b70225b5fd1e0d2ef4f7fd30d24658454535f0924dff0caca5dc08efbbbadfbb"},
{file = "argon2_cffi_bindings-26.1.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:1af817e84578ef8b7295ad17de0f9896e4c8520dbf2233c7aa5aa3d487256fc4"},
{file = "argon2_cffi_bindings-26.1.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:19b562b1de4b9052ef1214a2821c44b6e6f22945daa102c32ae4eff929d8b6d8"},
{file = "argon2_cffi_bindings-26.1.0-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49d525938467d52c923a890153c99087c9d5a937d1f6b585dbdba34ec82e397a"},
{file = "argon2_cffi_bindings-26.1.0-pp311-pypy311_pp73-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1b0bcac4d490a237e18cf91f57352920c29f77f2fa39efd0813fb81298bf17ba"},
{file = "argon2_cffi_bindings-26.1.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:0cc40f7b4050bb93eb67de95d2d759322fc7ce4930b9d645581ecf4913ec651e"},
{file = "argon2_cffi_bindings-26.1.0.tar.gz", hash = "sha256:63505c71542a44b68b1e38060450fb006404170da375feb31af153e7f9c6205d"},
]
[package.dependencies]
cffi = {version = ">=1.0.1", markers = "python_version < \"3.14\""}
[[package]]
name = "asyncpg"
version = "0.31.0"
description = "An asyncio PostgreSQL driver"
optional = false
python-versions = ">=3.9.0"
groups = ["main"]
files = [
{file = "asyncpg-0.31.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:831712dd3cf117eec68575a9b50da711893fd63ebe277fc155ecae1c6c9f0f61"},
{file = "asyncpg-0.31.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0b17c89312c2f4ccea222a3a6571f7df65d4ba2c0e803339bfc7bed46a96d3be"},
{file = "asyncpg-0.31.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3faa62f997db0c9add34504a68ac2c342cfee4d57a0c3062fcf0d86c7f9cb1e8"},
{file = "asyncpg-0.31.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8ea599d45c361dfbf398cb67da7fd052affa556a401482d3ff1ee99bd68808a1"},
{file = "asyncpg-0.31.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:795416369c3d284e1837461909f58418ad22b305f955e625a4b3a2521d80a5f3"},
{file = "asyncpg-0.31.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:a8d758dac9d2e723e173d286ef5e574f0b350ec00e9186fce84d0fc5f6a8e6b8"},
{file = "asyncpg-0.31.0-cp310-cp310-win32.whl", hash = "sha256:2d076d42eb583601179efa246c5d7ae44614b4144bc1c7a683ad1222814ed095"},
{file = "asyncpg-0.31.0-cp310-cp310-win_amd64.whl", hash = "sha256:9ea33213ac044171f4cac23740bed9a3805abae10e7025314cfbd725ec670540"},
{file = "asyncpg-0.31.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:eee690960e8ab85063ba93af2ce128c0f52fd655fdff9fdb1a28df01329f031d"},
{file = "asyncpg-0.31.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2657204552b75f8288de08ca60faf4a99a65deef3a71d1467454123205a88fab"},
{file = "asyncpg-0.31.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a429e842a3a4b4ea240ea52d7fe3f82d5149853249306f7ff166cb9948faa46c"},
{file = "asyncpg-0.31.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c0807be46c32c963ae40d329b3a686356e417f674c976c07fa49f1b30303f109"},
{file = "asyncpg-0.31.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:e5d5098f63beeae93512ee513d4c0c53dc12e9aa2b7a1af5a81cddf93fe4e4da"},
{file = "asyncpg-0.31.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37fc6c00a814e18eef51833545d1891cac9aa69140598bb076b4cd29b3e010b9"},
{file = "asyncpg-0.31.0-cp311-cp311-win32.whl", hash = "sha256:5a4af56edf82a701aece93190cc4e094d2df7d33f6e915c222fb09efbb5afc24"},
{file = "asyncpg-0.31.0-cp311-cp311-win_amd64.whl", hash = "sha256:480c4befbdf079c14c9ca43c8c5e1fe8b6296c96f1f927158d4f1e750aacc047"},
{file = "asyncpg-0.31.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b44c31e1efc1c15188ef183f287c728e2046abb1d26af4d20858215d50d91fad"},
{file = "asyncpg-0.31.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0c89ccf741c067614c9b5fc7f1fc6f3b61ab05ae4aaa966e6fd6b93097c7d20d"},
{file = "asyncpg-0.31.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:12b3b2e39dc5470abd5e98c8d3373e4b1d1234d9fbdedf538798b2c13c64460a"},
{file = "asyncpg-0.31.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:aad7a33913fb8bcb5454313377cc330fbb19a0cd5faa7272407d8a0c4257b671"},
{file = "asyncpg-0.31.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3df118d94f46d85b2e434fd62c84cb66d5834d5a890725fe625f498e72e4d5ec"},
{file = "asyncpg-0.31.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:bd5b6efff3c17c3202d4b37189969acf8927438a238c6257f66be3c426beba20"},
{file = "asyncpg-0.31.0-cp312-cp312-win32.whl", hash = "sha256:027eaa61361ec735926566f995d959ade4796f6a49d3bde17e5134b9964f9ba8"},
{file = "asyncpg-0.31.0-cp312-cp312-win_amd64.whl", hash = "sha256:72d6bdcbc93d608a1158f17932de2321f68b1a967a13e014998db87a72ed3186"},
{file = "asyncpg-0.31.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:c204fab1b91e08b0f47e90a75d1b3c62174dab21f670ad6c5d0f243a228f015b"},
{file = "asyncpg-0.31.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:54a64f91839ba59008eccf7aad2e93d6e3de688d796f35803235ea1c4898ae1e"},
{file = "asyncpg-0.31.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c0e0822b1038dc7253b337b0f3f676cadc4ac31b126c5d42691c39691962e403"},
{file = "asyncpg-0.31.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bef056aa502ee34204c161c72ca1f3c274917596877f825968368b2c33f585f4"},
{file = "asyncpg-0.31.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:0bfbcc5b7ffcd9b75ab1558f00db2ae07db9c80637ad1b2469c43df79d7a5ae2"},
{file = "asyncpg-0.31.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:22bc525ebbdc24d1261ecbf6f504998244d4e3be1721784b5f64664d61fbe602"},
{file = "asyncpg-0.31.0-cp313-cp313-win32.whl", hash = "sha256:f890de5e1e4f7e14023619399a471ce4b71f5418cd67a51853b9910fdfa73696"},
{file = "asyncpg-0.31.0-cp313-cp313-win_amd64.whl", hash = "sha256:dc5f2fa9916f292e5c5c8b2ac2813763bcd7f58e130055b4ad8a0531314201ab"},
{file = "asyncpg-0.31.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:f6b56b91bb0ffc328c4e3ed113136cddd9deefdf5f79ab448598b9772831df44"},
{file = "asyncpg-0.31.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:334dec28cf20d7f5bb9e45b39546ddf247f8042a690bff9b9573d00086e69cb5"},
{file = "asyncpg-0.31.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:98cc158c53f46de7bb677fd20c417e264fc02b36d901cc2a43bd6cb0dc6dbfd2"},
{file = "asyncpg-0.31.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9322b563e2661a52e3cdbc93eed3be7748b289f792e0011cb2720d278b366ce2"},
{file = "asyncpg-0.31.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:19857a358fc811d82227449b7ca40afb46e75b33eb8897240c3839dd8b744218"},
{file = "asyncpg-0.31.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ba5f8886e850882ff2c2ace5732300e99193823e8107e2c53ef01c1ebfa1e85d"},
{file = "asyncpg-0.31.0-cp314-cp314-win32.whl", hash = "sha256:cea3a0b2a14f95834cee29432e4ddc399b95700eb1d51bbc5bfee8f31fa07b2b"},
{file = "asyncpg-0.31.0-cp314-cp314-win_amd64.whl", hash = "sha256:04d19392716af6b029411a0264d92093b6e5e8285ae97a39957b9a9c14ea72be"},
{file = "asyncpg-0.31.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:bdb957706da132e982cc6856bb2f7b740603472b54c3ebc77fe60ea3e57e1bd2"},
{file = "asyncpg-0.31.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:6d11b198111a72f47154fa03b85799f9be63701e068b43f84ac25da0bda9cb31"},
{file = "asyncpg-0.31.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:18c83b03bc0d1b23e6230f5bf8d4f217dc9bc08644ce0502a9d91dc9e634a9c7"},
{file = "asyncpg-0.31.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e009abc333464ff18b8f6fd146addffd9aaf63e79aa3bb40ab7a4c332d0c5e9e"},
{file = "asyncpg-0.31.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:3b1fbcb0e396a5ca435a8826a87e5c2c2cc0c8c68eb6fadf82168056b0e53a8c"},
{file = "asyncpg-0.31.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8df714dba348efcc162d2adf02d213e5fab1bd9f557e1305633e851a61814a7a"},
{file = "asyncpg-0.31.0-cp314-cp314t-win32.whl", hash = "sha256:1b41f1afb1033f2b44f3234993b15096ddc9cd71b21a42dbd87fc6a57b43d65d"},
{file = "asyncpg-0.31.0-cp314-cp314t-win_amd64.whl", hash = "sha256:bd4107bb7cdd0e9e65fae66a62afd3a249663b844fa34d479f6d5b3bef9c04c3"},
{file = "asyncpg-0.31.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:ebb3cde58321a1f89ce41812be3f2a98dddedc1e76d0838aba1d724f1e4e1a95"},
{file = "asyncpg-0.31.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e6974f36eb9a224d8fb428bcf66bd411aa12cf57c2967463178149e73d4de366"},
{file = "asyncpg-0.31.0-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bc2b685f400ceae428f79f78b58110470d7b4466929a7f78d455964b17ad1008"},
{file = "asyncpg-0.31.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bb223567dea5f47c45d347f2bde5486be8d9f40339f27217adb3fb1c3be51298"},
{file = "asyncpg-0.31.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:22be6e02381bab3101cd502d9297ac71e2f966c86e20e78caead9934c98a8af6"},
{file = "asyncpg-0.31.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:37a58919cfef2448a920df00d1b2f821762d17194d0dbf355d6dde8d952c04f9"},
{file = "asyncpg-0.31.0-cp39-cp39-win32.whl", hash = "sha256:c1a9c5b71d2371a2290bc93336cd05ba4ec781683cab292adbddc084f89443c6"},
{file = "asyncpg-0.31.0-cp39-cp39-win_amd64.whl", hash = "sha256:c1e1ab5bc65373d92dd749d7308c5b26fb2dc0fbe5d3bf68a32b676aa3bcd24a"},
{file = "asyncpg-0.31.0.tar.gz", hash = "sha256:c989386c83940bfbd787180f2b1519415e2d3d6277a70d9d0f0145ac73500735"},
]
[package.extras]
gssauth = ["gssapi ; platform_system != \"Windows\"", "sspilib ; platform_system == \"Windows\""]
[[package]]
name = "certifi"
version = "2026.7.22"
@@ -55,6 +194,119 @@ files = [
{file = "certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55"},
]
[[package]]
name = "cffi"
version = "2.1.1"
description = "Foreign Function Interface for Python calling C code."
optional = false
python-versions = ">=3.10"
groups = ["main"]
files = [
{file = "cffi-2.1.1-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be"},
{file = "cffi-2.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b"},
{file = "cffi-2.1.1-cp310-cp310-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004"},
{file = "cffi-2.1.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9"},
{file = "cffi-2.1.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98"},
{file = "cffi-2.1.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9"},
{file = "cffi-2.1.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6"},
{file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf"},
{file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659"},
{file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9"},
{file = "cffi-2.1.1-cp310-cp310-win32.whl", hash = "sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41"},
{file = "cffi-2.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1"},
{file = "cffi-2.1.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12"},
{file = "cffi-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1"},
{file = "cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0"},
{file = "cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813"},
{file = "cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990"},
{file = "cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af"},
{file = "cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632"},
{file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd"},
{file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a"},
{file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa"},
{file = "cffi-2.1.1-cp311-cp311-win32.whl", hash = "sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3"},
{file = "cffi-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0"},
{file = "cffi-2.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455"},
{file = "cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0"},
{file = "cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf"},
{file = "cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a"},
{file = "cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890"},
{file = "cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50"},
{file = "cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e"},
{file = "cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf"},
{file = "cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517"},
{file = "cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735"},
{file = "cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e"},
{file = "cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a"},
{file = "cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80"},
{file = "cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e"},
{file = "cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c"},
{file = "cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6"},
{file = "cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971"},
{file = "cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c"},
{file = "cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125"},
{file = "cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264"},
{file = "cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3"},
{file = "cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2"},
{file = "cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b"},
{file = "cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7"},
{file = "cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac"},
{file = "cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d"},
{file = "cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973"},
{file = "cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c"},
{file = "cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb"},
{file = "cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54"},
{file = "cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72"},
{file = "cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1"},
{file = "cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062"},
{file = "cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03"},
{file = "cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96"},
{file = "cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527"},
{file = "cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13"},
{file = "cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c"},
{file = "cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48"},
{file = "cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836"},
{file = "cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3"},
{file = "cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2"},
{file = "cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94"},
{file = "cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc"},
{file = "cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29"},
{file = "cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676"},
{file = "cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e"},
{file = "cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f"},
{file = "cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4"},
{file = "cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e"},
{file = "cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5"},
{file = "cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d"},
{file = "cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b"},
{file = "cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4"},
{file = "cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8"},
{file = "cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6"},
{file = "cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80"},
{file = "cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779"},
{file = "cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399"},
{file = "cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688"},
{file = "cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7"},
{file = "cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac"},
{file = "cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960"},
{file = "cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1"},
{file = "cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc"},
{file = "cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab"},
{file = "cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e"},
{file = "cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358"},
{file = "cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231"},
{file = "cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6"},
{file = "cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94"},
{file = "cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5"},
{file = "cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66"},
{file = "cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3"},
{file = "cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692"},
{file = "cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be"},
]
[package.dependencies]
pycparser = {version = "*", markers = "implementation_name != \"PyPy\""}
[[package]]
name = "click"
version = "8.5.0"
@@ -268,6 +520,19 @@ files = [
dev = ["pre-commit", "tox"]
testing = ["coverage", "pytest", "pytest-benchmark"]
[[package]]
name = "pycparser"
version = "3.0"
description = "C parser in Python"
optional = false
python-versions = ">=3.10"
groups = ["main"]
markers = "implementation_name != \"PyPy\""
files = [
{file = "pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992"},
{file = "pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29"},
]
[[package]]
name = "pydantic"
version = "2.13.5"
@@ -460,6 +725,23 @@ pygments = ">=2.7.2"
[package.extras]
dev = ["argcomplete", "attrs (>=19.2)", "hypothesis (>=3.56)", "mock", "requests", "setuptools", "xmlschema"]
[[package]]
name = "redis"
version = "6.4.0"
description = "Python client for Redis database and key-value store"
optional = false
python-versions = ">=3.9"
groups = ["main"]
files = [
{file = "redis-6.4.0-py3-none-any.whl", hash = "sha256:f0544fa9604264e9464cdf4814e7d4830f74b165d52f2a330a760a88dd248b7f"},
{file = "redis-6.4.0.tar.gz", hash = "sha256:b01bc7282b8444e28ec36b261df5375183bb47a07eb9c603f284e89cbc5ef010"},
]
[package.extras]
hiredis = ["hiredis (>=3.2.0)"]
jwt = ["pyjwt (>=2.9.0)"]
ocsp = ["cryptography (>=36.0.1)", "pyopenssl (>=20.0.1)", "requests (>=2.31.0)"]
[[package]]
name = "starlette"
version = "1.7.0"
@@ -544,4 +826,4 @@ dev = ["black (>=19.3b0) ; python_version >= \"3.6\"", "pytest (>=4.6.2)"]
[metadata]
lock-version = "2.1"
python-versions = ">=3.12,<3.13"
content-hash = "0fa9cbd0321b256afe0bfead469acfb6ff52bb827c224b2ce16a16beb07b9b22"
content-hash = "69e25ec2435541d7cdd8ffcea503313332dda8958ff07fcbe81fe125f1521346"
+3
View File
@@ -12,6 +12,9 @@ uvicorn = "0.54.0"
pydantic = "2.13.5"
envparse = "0.2.0"
loguru = "0.7.3"
asyncpg = "0.31.0"
redis = "6.4.0"
argon2-cffi = "25.1.0"
[tool.poetry.group.dev.dependencies]
pytest = "9.1.1"
+45
View File
@@ -0,0 +1,45 @@
#!/bin/sh
set -eu
# Миграции с нуля и повторно: отдельный compose-проект с собственным пустым
# volume. Рабочий стенд и его данные не затрагиваются; временный volume
# этого проекта удаляется в конце.
cd "$(dirname "$0")/.."
PROJECT=messenger-lab2-migrations-check
COMPOSE="docker compose --env-file ${ENV_FILE:-.env} -p $PROJECT"
trap '$COMPOSE down -v --remove-orphans >/dev/null 2>&1' EXIT
$COMPOSE up -d --wait postgres >/dev/null 2>&1
$COMPOSE run --rm --no-deps -T api python - <<'EOF'
import asyncio
import sys
sys.path.insert(0, "src")
from infrastructure.dependencies.database import database_pool_manager as db
async def main() -> None:
await db.create_pool(30)
async with db.acquire() as conn:
tables = await conn.fetchval(
"SELECT count(*) FROM pg_tables WHERE schemaname = 'public';"
)
print(f"пустой volume: таблиц в public = {tables}")
for attempt in (1, 2, 3):
await db.apply_migrations()
async with db.acquire() as conn:
versions = await conn.fetch(
"SELECT version, name FROM schema_migrations ORDER BY version;"
)
tables = await conn.fetchval(
"SELECT count(*) FROM pg_tables WHERE schemaname = 'public';"
)
print(
f"запуск {attempt}: schema_migrations = "
f"{[(r['version'], r['name']) for r in versions]}, таблиц = {tables}"
)
await db.close()
asyncio.run(main())
EOF
+111
View File
@@ -0,0 +1,111 @@
-- Обоснование индекса истории: EXPLAIN (ANALYZE, BUFFERS) на ≥10 000 сообщений.
-- Запуск: make explain → evidence/explain_history.txt
-- Сид синтетический и идемпотентный: повторный запуск данных не дублирует.
-- Пользователь explain_seed не может войти: password_hash не является hash Argon2.
\pset pager off
\timing off
DO $$
DECLARE
seed_user uuid;
big_chat uuid;
noise uuid;
BEGIN
IF EXISTS (SELECT 1 FROM chats WHERE title = 'explain-big') THEN
RETURN;
END IF;
INSERT INTO users (username, display_name, password_hash)
VALUES ('explain_seed', 'EXPLAIN seed', 'not-an-argon2-hash')
ON CONFLICT (username) DO UPDATE SET display_name = EXCLUDED.display_name
RETURNING id INTO seed_user;
-- Большой чат: 20 000 сообщений
INSERT INTO chats (title, created_by) VALUES ('explain-big', seed_user)
RETURNING id INTO big_chat;
INSERT INTO chat_members (chat_id, user_id, position) VALUES (big_chat, seed_user, 0);
INSERT INTO messages (chat_id, sender_id, text, created_at)
SELECT big_chat, seed_user, 'synthetic message #' || n,
timestamptz '2026-01-01 00:00:00+00' + n * interval '1 second'
FROM generate_series(1, 20000) AS n;
-- Шум: 50 чатов по 1 000 сообщений, чтобы таблица была больше одного чата
FOR i IN 1..50 LOOP
INSERT INTO chats (title, created_by) VALUES ('explain-noise-' || i, seed_user)
RETURNING id INTO noise;
INSERT INTO chat_members (chat_id, user_id, position) VALUES (noise, seed_user, 0);
INSERT INTO messages (chat_id, sender_id, text, created_at)
SELECT noise, seed_user, 'noise #' || n,
timestamptz '2026-01-01 00:00:00+00' + n * interval '1 second'
FROM generate_series(1, 1000) AS n;
END LOOP;
END $$;
ANALYZE users, chats, chat_members, messages;
SELECT id AS big_chat FROM chats WHERE title = 'explain-big' \gset
-- Cursor из середины истории: ключ 10 000-го сообщения
SELECT created_at AS cursor_created_at, id AS cursor_id
FROM messages WHERE chat_id = :'big_chat'
ORDER BY created_at, id OFFSET 9999 LIMIT 1 \gset
\echo '== Объём данных'
SELECT
(SELECT count(*) FROM messages) AS messages_total,
(SELECT count(*) FROM messages WHERE chat_id = :'big_chat') AS messages_in_big_chat,
pg_size_pretty(pg_relation_size('messages')) AS messages_heap,
pg_size_pretty(pg_relation_size('messages_chat_id_created_at_id_idx')) AS history_index;
\echo ''
\echo '== 1. Первая страница истории (limit 50 + 1), как list_for_chat'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = :'big_chat'
ORDER BY created_at, id
LIMIT 51;
\echo ''
\echo '== 2. Страница из середины по cursor (после 10 000-го), как list_for_chat_after'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = :'big_chat'
AND (created_at, id) > (:'cursor_created_at'::timestamptz, :'cursor_id'::uuid)
ORDER BY created_at, id
LIMIT 51;
\echo ''
\echo '== 3. Тот же запрос как generic plan prepared statement (так его исполняет asyncpg)'
SET plan_cache_mode = force_generic_plan;
PREPARE history_page(uuid, timestamptz, uuid, int) AS
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
ORDER BY created_at, id
LIMIT $4;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
EXECUTE history_page(:'big_chat', :'cursor_created_at', :'cursor_id', 51);
DEALLOCATE history_page;
RESET plan_cache_mode;
\echo ''
\echo '== 4. MAX(created_at) при вставке сообщения (монотонное время чата)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT max(created_at) FROM messages WHERE chat_id = :'big_chat';
\echo ''
\echo '== 5. Для сравнения: тот же запрос из середины БЕЗ индекса истории'
\echo ' (DROP INDEX внутри транзакции с ROLLBACK — индекс не теряется)'
BEGIN;
DROP INDEX messages_chat_id_created_at_id_idx;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = :'big_chat'
AND (created_at, id) > (:'cursor_created_at'::timestamptz, :'cursor_id'::uuid)
ORDER BY created_at, id
LIMIT 51;
ROLLBACK;
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
# Перезапуск API и всех используемых хранилищ (PostgreSQL, Valkey) с сохранением
# volumes: никаких down -v, flush или повторного seed. Готовность ждёт тест.
cd "$(dirname "$0")/.."
ENV_FILE="${ENV_FILE:-.env}"
docker compose --env-file "$ENV_FILE" restart postgres valkey
docker compose --env-file "$ENV_FILE" restart api
+1 -1
View File
@@ -53,7 +53,7 @@ def main() -> None:
"--base-url", default=os.environ.get("BASE_URL") or DEFAULT_BASE_URL
)
parser.add_argument(
"--container", default=os.environ.get("CONTAINER", "mtusi-messenger-lab2")
"--container", default=os.environ.get("CONTAINER", "messenger-lab2-api-1")
)
args = parser.parse_args()
+2 -2
View File
@@ -1,4 +1,4 @@
from .auth import get_current_user
from .security import USER_ID_HEADER, user_id_header
from .security import basic_credentials, bearer_token
__all__ = ["get_current_user", "user_id_header", "USER_ID_HEADER"]
__all__ = ["get_current_user", "basic_credentials", "bearer_token"]
+6 -6
View File
@@ -2,14 +2,14 @@ from fastapi import Depends
from domain import UserSchema
from infrastructure.dependencies import ServiceCreator
from infrastructure.services import UserService
from infrastructure.services import AuthService
from .security import user_id_header
from .security import bearer_token
async def get_current_user(
raw_user_id: str | None = Depends(user_id_header),
service: UserService = Depends(ServiceCreator.get_user_service),
token: str | None = Depends(bearer_token),
service: AuthService = Depends(ServiceCreator.get_auth_service),
) -> UserSchema:
"""Текущий пользователь из X-User-Id; иначе 401"""
return await service.authenticate(raw_user_id)
"""Владелец действующей Bearer-сессии; X-User-Id не учитывается; иначе 401"""
return await service.authenticate(token)
+48 -6
View File
@@ -1,10 +1,52 @@
from fastapi.security import APIKeyHeader
import base64
import binascii
USER_ID_HEADER = "X-User-Id"
from fastapi import Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.security.http import HTTPBase
user_id_header = APIKeyHeader(
name=USER_ID_HEADER,
scheme_name="devUser",
description="uuid существующего пользователя",
from domain import BasicCredentialsSchema
from domain.errors import InvalidCredentialsError
BASIC_SCHEME = "basic"
basic_scheme = HTTPBase(
scheme=BASIC_SCHEME,
scheme_name="basicAuth",
description="Только для POST /auth/sessions",
auto_error=False,
)
bearer_scheme = HTTPBearer(
scheme_name="bearerAuth",
bearerFormat="opaque session token",
auto_error=False,
)
async def basic_credentials(
authorization: HTTPAuthorizationCredentials | None = Depends(basic_scheme),
) -> BasicCredentialsSchema:
"""
Authorization: Basic base64(username:password)
username — до первого двоеточия, остальное — пароль
Любая ошибка формата — тот же 401, что и неверный пароль.
"""
if authorization is None or authorization.scheme.lower() != BASIC_SCHEME:
raise InvalidCredentialsError()
try:
decoded = base64.b64decode(authorization.credentials, validate=True)
username, separator, password = decoded.decode("utf-8").partition(":")
except (binascii.Error, UnicodeDecodeError):
raise InvalidCredentialsError() from None
if not separator or not username.isascii():
raise InvalidCredentialsError()
return BasicCredentialsSchema(username=username, password=password)
async def bearer_token(
authorization: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
) -> str | None:
"""Токен из Authorization: Bearer; другие схемы (Basic) — как отсутствие"""
return authorization.credentials if authorization is not None else None
+5 -1
View File
@@ -13,7 +13,11 @@ async def app_error_handler(request: Request, error: Exception) -> JSONResponse:
"""Доменные ошибки сервисов и репозиториев"""
assert isinstance(error, AppError)
return error_response(
get_request_id(request), error.status_code, error.code, error.message
get_request_id(request),
error.status_code,
error.code,
error.message,
error.headers,
)
+11 -3
View File
@@ -1,7 +1,8 @@
from fastapi import APIRouter, Request, status
from fastapi import APIRouter, Depends, Request, status
from domain import HealthSchema
from domain.errors import UnavailableError
from infrastructure.dependencies import DatabasePoolManager, get_database
health_router = APIRouter(prefix="/health", tags=["Health"])
@@ -21,8 +22,15 @@ async def liveness() -> HealthSchema:
status_code=status.HTTP_200_OK,
response_model=HealthSchema,
)
async def readiness(request: Request) -> HealthSchema:
"""Хранилище создано и приложение не завершается"""
async def readiness(
request: Request, database: DatabasePoolManager = Depends(get_database)
) -> HealthSchema:
"""
Приложение не завершается и PostgreSQL отвечает. Valkey не критичен:
без него сессии читаются из PostgreSQL, поэтому он не влияет на готовность.
"""
if not getattr(request.app.state, "is_ready", False):
raise UnavailableError()
if not await database.check():
raise UnavailableError("бд недоступна")
return HealthSchema()
+2
View File
@@ -1,5 +1,6 @@
from fastapi import APIRouter
from .auth import auth_router
from .chats import chats_router
from .messages import messages_router
from .users import users_router
@@ -7,6 +8,7 @@ from .users import users_router
app = APIRouter(prefix="/v1")
app.include_router(users_router)
app.include_router(auth_router)
app.include_router(chats_router)
app.include_router(messages_router)
@@ -0,0 +1,3 @@
from .endpoints import auth_router
__all__ = ["auth_router"]
@@ -0,0 +1,35 @@
from fastapi import APIRouter, Depends, Response, status
from application.api.dependencies import basic_credentials, bearer_token
from domain import BasicCredentialsSchema, SessionSchema
from infrastructure.dependencies import ServiceCreator
from infrastructure.services import AuthService
auth_router = APIRouter(prefix="/auth/sessions", tags=["Auth"])
@auth_router.post(
"",
status_code=status.HTTP_201_CREATED,
response_model=SessionSchema,
)
async def create_session(
credentials: BasicCredentialsSchema = Depends(basic_credentials),
service: AuthService = Depends(ServiceCreator.get_auth_service),
) -> SessionSchema:
"""Вход по Basic, без JSON body; возвращает Bearer-токен"""
return await service.login(credentials)
@auth_router.delete(
"/current",
status_code=status.HTTP_204_NO_CONTENT,
response_class=Response,
)
async def revoke_session(
token: str | None = Depends(bearer_token),
service: AuthService = Depends(ServiceCreator.get_auth_service),
) -> Response:
"""Logout: текущий токен перестаёт действовать; повтор — 401"""
await service.logout(token)
return Response(status_code=status.HTTP_204_NO_CONTENT)
+38
View File
@@ -3,8 +3,27 @@ from .settings import (
APP_ENV,
APP_HOST,
APP_PORT,
DB_COMMAND_TIMEOUT_SEC,
DB_CONNECT_TIMEOUT_SEC,
DB_HOST,
DB_NAME,
DB_PASS,
DB_POOL_MAX_SIZE,
DB_POOL_MIN_SIZE,
DB_PORT,
DB_STARTUP_TIMEOUT_SEC,
DB_USER,
LOG_LEVEL,
PASSWORD_HASH_WORKERS,
SESSION_CACHE_TTL_SECONDS,
SESSION_TTL_SECONDS,
SHUTDOWN_TIMEOUT_SEC,
VALKEY_HOST,
VALKEY_PASS,
VALKEY_POOL_MAX_SIZE,
VALKEY_PORT,
VALKEY_RETRY_AFTER_SEC,
VALKEY_TIMEOUT_SEC,
)
__all__ = [
@@ -14,4 +33,23 @@ __all__ = [
"APP_ENV",
"LOG_LEVEL",
"SHUTDOWN_TIMEOUT_SEC",
"DB_USER",
"DB_PASS",
"DB_NAME",
"DB_HOST",
"DB_PORT",
"DB_POOL_MIN_SIZE",
"DB_POOL_MAX_SIZE",
"DB_CONNECT_TIMEOUT_SEC",
"DB_COMMAND_TIMEOUT_SEC",
"DB_STARTUP_TIMEOUT_SEC",
"VALKEY_HOST",
"VALKEY_PORT",
"VALKEY_PASS",
"VALKEY_POOL_MAX_SIZE",
"VALKEY_TIMEOUT_SEC",
"VALKEY_RETRY_AFTER_SEC",
"SESSION_TTL_SECONDS",
"SESSION_CACHE_TTL_SECONDS",
"PASSWORD_HASH_WORKERS",
]
+22
View File
@@ -15,3 +15,25 @@ APP_ENV = env.str("APP_ENV")
LOG_LEVEL = env.str("LOG_LEVEL")
SHUTDOWN_TIMEOUT_SEC = env.int("SHUTDOWN_TIMEOUT_SEC")
DB_USER = env.str("DB_USER")
DB_PASS = env.str("DB_PASS")
DB_NAME = env.str("DB_NAME")
DB_HOST = env.str("DB_HOST")
DB_PORT = env.int("DB_PORT")
DB_POOL_MIN_SIZE = env.int("DB_POOL_MIN_SIZE")
DB_POOL_MAX_SIZE = env.int("DB_POOL_MAX_SIZE")
DB_CONNECT_TIMEOUT_SEC = env.float("DB_CONNECT_TIMEOUT_SEC")
DB_COMMAND_TIMEOUT_SEC = env.float("DB_COMMAND_TIMEOUT_SEC")
DB_STARTUP_TIMEOUT_SEC = env.float("DB_STARTUP_TIMEOUT_SEC")
VALKEY_HOST = env.str("VALKEY_HOST")
VALKEY_PORT = env.int("VALKEY_PORT")
VALKEY_PASS = env.str("VALKEY_PASS")
VALKEY_POOL_MAX_SIZE = env.int("VALKEY_POOL_MAX_SIZE")
VALKEY_TIMEOUT_SEC = env.float("VALKEY_TIMEOUT_SEC")
VALKEY_RETRY_AFTER_SEC = env.float("VALKEY_RETRY_AFTER_SEC")
SESSION_TTL_SECONDS = env.int("SESSION_TTL_SECONDS")
SESSION_CACHE_TTL_SECONDS = env.int("SESSION_CACHE_TTL_SECONDS")
PASSWORD_HASH_WORKERS = env.int("PASSWORD_HASH_WORKERS")
+6 -1
View File
@@ -1,12 +1,17 @@
from .auth import ActiveSessionSchema, BasicCredentialsSchema, SessionSchema
from .chats import ChatPageSchema, ChatSchema, CreateChatSchema
from .health import HealthSchema
from .messages import CreateMessageSchema, MessagePageSchema, MessageSchema
from .pagination import PageCursorSchema, PageKey
from .users import CreateUserSchema, UserSchema
from .users import CreateUserSchema, UserCredentialsSchema, UserSchema
__all__ = [
"CreateUserSchema",
"UserSchema",
"UserCredentialsSchema",
"BasicCredentialsSchema",
"SessionSchema",
"ActiveSessionSchema",
"CreateChatSchema",
"ChatSchema",
"ChatPageSchema",
+7
View File
@@ -0,0 +1,7 @@
from .schemas import ActiveSessionSchema, BasicCredentialsSchema, SessionSchema
__all__ = [
"BasicCredentialsSchema",
"SessionSchema",
"ActiveSessionSchema",
]
+35
View File
@@ -0,0 +1,35 @@
from typing import Literal
from pydantic import BaseModel, ConfigDict
from domain.users import UserSchema
from domain.utils import UtcDateTime
class BasicCredentialsSchema(BaseModel):
"""Разобранный заголовок Authorization: Basic"""
model_config = ConfigDict(frozen=True)
username: str
password: str
class SessionSchema(BaseModel):
"""Ответ входа: непрозрачный токен показывается клиенту один раз"""
model_config = ConfigDict(frozen=True)
token: str
token_type: Literal["Bearer"] = "Bearer"
expires_at: UtcDateTime
user: UserSchema
class ActiveSessionSchema(BaseModel):
"""Действующая серверная сессия: владелец и срок; так же лежит в кэше"""
model_config = ConfigDict(frozen=True)
user: UserSchema
expires_at: UtcDateTime
-3
View File
@@ -1,10 +1,7 @@
from .constants import CHAT_MEMBERS_MAX_COUNT, CHAT_TITLE_MAX_LENGTH
from .schemas import ChatPageSchema, ChatSchema, CreateChatSchema
__all__ = [
"CreateChatSchema",
"ChatSchema",
"ChatPageSchema",
"CHAT_TITLE_MAX_LENGTH",
"CHAT_MEMBERS_MAX_COUNT",
]
-3
View File
@@ -1,3 +0,0 @@
CHAT_TITLE_MAX_LENGTH = 100
CHAT_MEMBERS_MAX_COUNT = 100
+2 -6
View File
@@ -5,11 +5,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator
from domain.utils import NotBlankStr, UtcDateTime
from .constants import CHAT_MEMBERS_MAX_COUNT, CHAT_TITLE_MAX_LENGTH
ChatTitle = Annotated[
NotBlankStr, Field(min_length=1, max_length=CHAT_TITLE_MAX_LENGTH)
]
ChatTitle = Annotated[NotBlankStr, Field(min_length=1, max_length=100)]
class CreateChatSchema(BaseModel):
@@ -18,7 +14,7 @@ class CreateChatSchema(BaseModel):
model_config = ConfigDict(extra="forbid")
title: ChatTitle
member_ids: list[UUID] = Field(min_length=1, max_length=CHAT_MEMBERS_MAX_COUNT)
member_ids: list[UUID] = Field(min_length=1, max_length=100)
@field_validator("member_ids")
@classmethod
+2
View File
@@ -2,6 +2,7 @@ from .codes import ErrorCode
from .exceptions import (
AppError,
ConflictError,
InvalidCredentialsError,
InvalidRequestError,
NotFoundError,
UnauthorizedError,
@@ -14,6 +15,7 @@ __all__ = [
"AppError",
"InvalidRequestError",
"UnauthorizedError",
"InvalidCredentialsError",
"NotFoundError",
"ConflictError",
"UnavailableError",
+11 -2
View File
@@ -9,6 +9,7 @@ class AppError(Exception):
status_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR
code: ErrorCode = ErrorCode.INTERNAL_ERROR
default_message: str = "Внутренняя ошибка сервера"
headers: dict[str, str] = {}
def __init__(self, message: str | None = None) -> None:
self.message = message or self.default_message
@@ -24,11 +25,19 @@ class InvalidRequestError(AppError):
class UnauthorizedError(AppError):
"""Нет действительной идентификации пользователя"""
"""Нет действительной Bearer-сессии: токена нет, он истёк, отозван или неизвестен"""
status_code = HTTPStatus.UNAUTHORIZED
code = ErrorCode.UNAUTHORIZED
default_message = "Требуется заголовок X-User-Id существующего пользователя"
default_message = "Требуется действительная сессия: Authorization: Bearer <token>"
headers = {"WWW-Authenticate": 'Bearer realm="messenger"'}
class InvalidCredentialsError(UnauthorizedError):
"""Неверные Basic-credentials: одинаковый ответ для неизвестного логина и пароля"""
default_message = "Неверное имя пользователя или пароль"
headers = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
class NotFoundError(AppError):
-2
View File
@@ -1,9 +1,7 @@
from .constants import MESSAGE_TEXT_MAX_LENGTH
from .schemas import CreateMessageSchema, MessagePageSchema, MessageSchema
__all__ = [
"CreateMessageSchema",
"MessageSchema",
"MessagePageSchema",
"MESSAGE_TEXT_MAX_LENGTH",
]
-1
View File
@@ -1 +0,0 @@
MESSAGE_TEXT_MAX_LENGTH = 4000
+2 -6
View File
@@ -5,15 +5,11 @@ from pydantic import BaseModel, ConfigDict, Field
from domain.utils import NotBlankStr, UtcDateTime
from .constants import MESSAGE_TEXT_MAX_LENGTH
MessageText = Annotated[
NotBlankStr, Field(min_length=1, max_length=MESSAGE_TEXT_MAX_LENGTH)
]
MessageText = Annotated[NotBlankStr, Field(min_length=1, max_length=4000)]
class CreateMessageSchema(BaseModel):
"""Запрос отправки сообщения: отправитель берётся из X-User-Id"""
"""Запрос отправки сообщения: отправитель берётся из текущей сессии"""
model_config = ConfigDict(extra="forbid")
+2 -4
View File
@@ -1,9 +1,7 @@
from .constants import DISPLAY_NAME_MAX_LENGTH, USERNAME_PATTERN
from .schemas import CreateUserSchema, UserSchema
from .schemas import CreateUserSchema, UserCredentialsSchema, UserSchema
__all__ = [
"CreateUserSchema",
"UserSchema",
"USERNAME_PATTERN",
"DISPLAY_NAME_MAX_LENGTH",
"UserCredentialsSchema",
]
-3
View File
@@ -1,3 +0,0 @@
USERNAME_PATTERN = r"^[a-z0-9_]{3,32}$"
DISPLAY_NAME_MAX_LENGTH = 100
+15 -8
View File
@@ -5,25 +5,23 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr
from domain.utils import NotBlankStr, UtcDateTime
from .constants import DISPLAY_NAME_MAX_LENGTH, USERNAME_PATTERN
Username = Annotated[StrictStr, Field(pattern=USERNAME_PATTERN)]
DisplayName = Annotated[
NotBlankStr, Field(min_length=1, max_length=DISPLAY_NAME_MAX_LENGTH)
]
Username = Annotated[StrictStr, Field(pattern=r"^[a-z0-9_]{3,32}$")]
DisplayName = Annotated[NotBlankStr, Field(min_length=1, max_length=100)]
Password = Annotated[StrictStr, Field(min_length=12, max_length=128)]
class CreateUserSchema(BaseModel):
"""Запрос регистрации пользователя"""
"""Запрос регистрации пользователя; длина пароля — в Unicode code points"""
model_config = ConfigDict(extra="forbid")
username: Username
display_name: DisplayName
password: Password = Field(json_schema_extra={"writeOnly": True})
class UserSchema(BaseModel):
"""Пользователь"""
"""Пользователь: пароль и его hash сюда никогда не попадают"""
model_config = ConfigDict(frozen=True)
@@ -31,3 +29,12 @@ class UserSchema(BaseModel):
username: str
display_name: str
created_at: UtcDateTime
class UserCredentialsSchema(BaseModel):
"""Пользователь вместе с hash пароля — только для проверки входа"""
model_config = ConfigDict(frozen=True)
user: UserSchema
password_hash: str
+14 -2
View File
@@ -1,3 +1,15 @@
from .types import NotBlankStr, UtcDateTime, ensure_not_blank, to_rfc3339_utc
from .types import (
NotBlankStr,
UtcDateTime,
ensure_not_blank,
ensure_storable,
to_rfc3339_utc,
)
__all__ = ["NotBlankStr", "UtcDateTime", "ensure_not_blank", "to_rfc3339_utc"]
__all__ = [
"NotBlankStr",
"UtcDateTime",
"ensure_not_blank",
"ensure_storable",
"to_rfc3339_utc",
]
+12 -1
View File
@@ -3,6 +3,8 @@ from typing import Annotated
from pydantic import AfterValidator, PlainSerializer, StrictStr
NUL_CHARACTER = "\x00"
def ensure_not_blank(value: str) -> str:
"""Обязательная строка не может состоять только из пробельных символов"""
@@ -11,6 +13,13 @@ def ensure_not_blank(value: str) -> str:
return value
def ensure_storable(value: str) -> str:
"""Тип text в потсгре"""
if NUL_CHARACTER in value:
raise ValueError("Строка не может содержать символ NUL")
return value
def to_rfc3339_utc(value: datetime) -> str:
"""RFC 3339 в UTC с суффиксом Z и микросекундами"""
return (
@@ -18,7 +27,9 @@ def to_rfc3339_utc(value: datetime) -> str:
)
NotBlankStr = Annotated[StrictStr, AfterValidator(ensure_not_blank)]
NotBlankStr = Annotated[
StrictStr, AfterValidator(ensure_not_blank), AfterValidator(ensure_storable)
]
UtcDateTime = Annotated[
datetime, PlainSerializer(to_rfc3339_utc, return_type=str, when_used="json")
+25 -5
View File
@@ -7,18 +7,38 @@ from fastapi import FastAPI
from application import api_endpoints, health_endpoints
from application.api.handlers import register_exception_handlers
from application.api.middlewares import RequestContextMiddleware
from config import APP_ENV, APP_HOST, APP_PORT, LOGGER, SHUTDOWN_TIMEOUT_SEC
from infrastructure import InMemoryStorage
from config import (
APP_ENV,
APP_HOST,
APP_PORT,
DB_STARTUP_TIMEOUT_SEC,
LOGGER,
PASSWORD_HASH_WORKERS,
SESSION_TTL_SECONDS,
SHUTDOWN_TIMEOUT_SEC,
)
from infrastructure import PasswordHasher, cache_manager, database_pool_manager
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
app.state.storage = InMemoryStorage()
await database_pool_manager.create_pool(DB_STARTUP_TIMEOUT_SEC)
await database_pool_manager.apply_migrations()
cache_manager.create_client()
password_hasher = PasswordHasher(PASSWORD_HASH_WORKERS)
app.state.database = database_pool_manager
app.state.cache = cache_manager
app.state.password_hasher = password_hasher
app.state.is_ready = True
LOGGER.info(f"Application started, env={APP_ENV}, state is in-memory only")
LOGGER.info(
f"Application started, env={APP_ENV}, session ttl={SESSION_TTL_SECONDS} s"
)
yield
app.state.is_ready = False
LOGGER.info("Application stopped, in-memory state discarded")
await cache_manager.close()
await database_pool_manager.close()
password_hasher.close()
LOGGER.info("Application stopped, connections closed")
app = FastAPI(
+3 -2
View File
@@ -1,3 +1,4 @@
from .storage import InMemoryStorage
from .dependencies import cache_manager, database_pool_manager
from .security import PasswordHasher
__all__ = ["InMemoryStorage"]
__all__ = ["database_pool_manager", "cache_manager", "PasswordHasher"]
+11 -2
View File
@@ -1,4 +1,13 @@
from .cache import CacheManager, cache_manager, get_cache
from .database import DatabasePoolManager, database_pool_manager, get_database
from .service_creator import ServiceCreator
from .storage import get_storage
__all__ = ["ServiceCreator", "get_storage"]
__all__ = [
"ServiceCreator",
"DatabasePoolManager",
"database_pool_manager",
"get_database",
"CacheManager",
"cache_manager",
"get_cache",
]
+94
View File
@@ -0,0 +1,94 @@
import time
from redis.asyncio import BlockingConnectionPool, Redis
from redis.asyncio.retry import Retry
from redis.backoff import NoBackoff
from starlette.requests import HTTPConnection
from config import (
LOGGER,
VALKEY_HOST,
VALKEY_PASS,
VALKEY_POOL_MAX_SIZE,
VALKEY_PORT,
VALKEY_RETRY_AFTER_SEC,
VALKEY_TIMEOUT_SEC,
)
class CacheManager:
"""
Клиент Valkey: ограниченный пул, короткие таймауты, без встроенных повторов.
"""
def __init__(
self,
host: str,
port: int,
password: str,
max_size: int,
timeout: float,
retry_after: float,
) -> None:
self._host = host
self._port = port
self._password = password
self.max_size = max_size
self.timeout = timeout
self.retry_after = retry_after
self.client: Redis | None = None
self._disabled_until = 0.0
def create_client(self) -> Redis:
"""Создание клиента; соединения открываются лениво при первом запросе"""
if self.client is None:
pool = BlockingConnectionPool(
host=self._host,
port=self._port,
password=self._password,
max_connections=self.max_size,
timeout=self.timeout,
socket_timeout=self.timeout,
socket_connect_timeout=self.timeout,
retry=Retry(NoBackoff(), 0),
)
self.client = Redis(connection_pool=pool)
LOGGER.info(
f"Клиент Valkey создан: {self._host}:{self._port}, "
f"pool: {self.max_size}, timeout: {self.timeout} с"
)
return self.client
@property
def is_available(self) -> bool:
return time.monotonic() >= self._disabled_until
def mark_failed(self, error: Exception) -> None:
"""Обход кэша на retry_after секунд после ошибки Valkey"""
if self.is_available:
LOGGER.warning(
f"Valkey недоступен ({type(error).__name__}): кэш сессий "
f"обходится {self.retry_after} с, запросы идут в PostgreSQL"
)
self._disabled_until = time.monotonic() + self.retry_after
async def close(self) -> None:
if self.client is not None:
await self.client.aclose()
self.client = None
def get_cache(connection: HTTPConnection) -> CacheManager:
"""Получение менеджера кэша, созданного в lifespan."""
cache: CacheManager = connection.app.state.cache
return cache
cache_manager = CacheManager(
host=VALKEY_HOST,
port=VALKEY_PORT,
password=VALKEY_PASS,
max_size=VALKEY_POOL_MAX_SIZE,
timeout=VALKEY_TIMEOUT_SEC,
retry_after=VALKEY_RETRY_AFTER_SEC,
)
+206
View File
@@ -0,0 +1,206 @@
import asyncio
import time
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from pathlib import Path
import asyncpg
from starlette.requests import HTTPConnection
from config import (
DB_COMMAND_TIMEOUT_SEC,
DB_CONNECT_TIMEOUT_SEC,
DB_HOST,
DB_NAME,
DB_PASS,
DB_POOL_MAX_SIZE,
DB_POOL_MIN_SIZE,
DB_PORT,
DB_USER,
LOGGER,
)
from infrastructure.utils import DATABASE_UNAVAILABLE_ERRORS
MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations"
MIGRATIONS_LOCK_NAMESPACE = 1
STARTUP_RETRY_INTERVAL_SEC = 1
BROKEN_CONNECTION_ERRORS: tuple[type[Exception], ...] = (
asyncpg.PostgresConnectionError,
asyncpg.InterfaceError,
asyncpg.exceptions.OperatorInterventionError,
)
MIGRATIONS_TIMEOUT_SEC = 300
class DatabasePoolManager:
"""Класс для управления пулом соединений и версионируемыми миграциями."""
def __init__(
self,
user: str,
password: str,
db: str,
host: str,
port: int,
min_size: int,
max_size: int,
connect_timeout: float,
command_timeout: float,
) -> None:
self._user = user
self._password = password
self._host = host
self._port = port
self._database = db
self.min_size = min_size
self.max_size = max_size
self.connect_timeout = connect_timeout
self.command_timeout = command_timeout
self.pool: asyncpg.Pool | None = None
async def create_pool(self, startup_timeout: float) -> asyncpg.Pool:
"""
Создание ограниченного пула соединений.
"""
LOGGER.info("Установка соединения с базой данных psql")
deadline = time.monotonic() + startup_timeout
while self.pool is None:
try:
self.pool = await asyncpg.create_pool(
user=self._user,
password=self._password,
host=self._host,
port=self._port,
database=self._database,
min_size=self.min_size,
max_size=self.max_size,
timeout=self.connect_timeout,
command_timeout=self.command_timeout,
server_settings={
"application_name": "messenger-api",
"statement_timeout": str(int(self.command_timeout * 1000)),
},
)
except (*DATABASE_UNAVAILABLE_ERRORS, asyncpg.PostgresError) as error:
if time.monotonic() >= deadline:
LOGGER.error(
"Не удалось подключиться к psql за "
f"{startup_timeout} с: {type(error).__name__}"
)
raise
LOGGER.warning(
f"PostgreSQL ещё недоступен: {type(error).__name__}, повтор"
)
await asyncio.sleep(STARTUP_RETRY_INTERVAL_SEC)
LOGGER.info(
f"Соединение с базой данных psql установлено. DB_NAME: "
f"{self._database}, pool: {self.min_size}..{self.max_size}"
)
return self.pool
async def apply_migrations(self, directory: Path = MIGRATIONS_DIR) -> None:
"""
Применение миграций NNNN_name.sql по порядку версий.
Каждая миграция и запись о ней в schema_migrations — одна транзакция.
Advisory lock не даёт двум процессам API применять миграции одновременно;
уже применённые версии пропускаются, поэтому повторный запуск безопасен.
"""
async with self.acquire() as conn:
await conn.execute("SET statement_timeout = 0;")
await conn.execute(
"SELECT pg_advisory_lock($1, 0);",
MIGRATIONS_LOCK_NAMESPACE,
timeout=MIGRATIONS_TIMEOUT_SEC,
)
try:
await conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version integer PRIMARY KEY,
name text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
"""
)
applied = {
record["version"]
for record in await conn.fetch(
"SELECT version FROM schema_migrations;"
)
}
for path in sorted(directory.glob("*.sql")):
version = int(path.name.split("_", 1)[0])
if version in applied:
continue
async with conn.transaction():
await conn.execute(
path.read_text(encoding="utf-8"),
timeout=MIGRATIONS_TIMEOUT_SEC,
)
await conn.execute(
"INSERT INTO schema_migrations (version, name) "
"VALUES ($1, $2);",
version,
path.stem,
)
LOGGER.info(f"Применена миграция {path.name}")
finally:
await conn.execute(
"SELECT pg_advisory_unlock($1, 0);", MIGRATIONS_LOCK_NAMESPACE
)
LOGGER.info("Схема БД в актуальной версии")
@asynccontextmanager
async def acquire(self) -> AsyncIterator[asyncpg.Connection]:
"""
Получение соединения из пула с ограниченным ожиданием свободного.
После рестарта PostgreSQL все соединения пула мертвы. На первой же
ошибке соединения пул помечает их на переподключение, чтобы 503
получил один запрос, а не каждый из max_size следующих.
"""
assert self.pool is not None
try:
async with self.pool.acquire(timeout=self.connect_timeout) as connection:
yield connection
except BROKEN_CONNECTION_ERRORS:
await self.pool.expire_connections()
raise
async def check(self) -> bool:
"""PostgreSQL отвечает на запрос — для readiness"""
try:
async with self.acquire() as conn:
await conn.fetchval("SELECT 1;", timeout=self.connect_timeout)
except DATABASE_UNAVAILABLE_ERRORS:
return False
return True
async def close(self) -> None:
if self.pool:
await self.pool.close()
self.pool = None
def get_database(connection: HTTPConnection) -> DatabasePoolManager:
"""Получение менеджера пула соединений, созданного в lifespan."""
database: DatabasePoolManager = connection.app.state.database
return database
database_pool_manager = DatabasePoolManager(
user=DB_USER,
password=DB_PASS,
db=DB_NAME,
host=DB_HOST,
port=DB_PORT,
min_size=DB_POOL_MIN_SIZE,
max_size=DB_POOL_MAX_SIZE,
connect_timeout=DB_CONNECT_TIMEOUT_SEC,
command_timeout=DB_COMMAND_TIMEOUT_SEC,
)
@@ -1,47 +1,89 @@
from fastapi import Depends
from infrastructure.dependencies.storage import get_storage
from config import SESSION_CACHE_TTL_SECONDS, SESSION_TTL_SECONDS
from infrastructure.dependencies.cache import CacheManager, get_cache
from infrastructure.dependencies.database import DatabasePoolManager, get_database
from infrastructure.repositories import (
InMemoryChatRepository,
InMemoryMessageRepository,
InMemoryUserRepository,
PostgresChatRepository,
PostgresMessageRepository,
PostgresSessionRepository,
PostgresUserRepository,
ValkeySessionCache,
)
from infrastructure.security import PasswordHasher, get_password_hasher
from infrastructure.services import (
AuthService,
ChatService,
MessageService,
UserService,
)
from interfaces import (
ChatRepository,
MessageRepository,
SessionCache,
SessionRepository,
UserRepository,
)
from infrastructure.services import ChatService, MessageService, UserService
from infrastructure.storage import InMemoryStorage
from interfaces import ChatRepository, MessageRepository, UserRepository
class ServiceCreator:
@staticmethod
def _get_user_repository(
storage: InMemoryStorage = Depends(get_storage),
database: DatabasePoolManager = Depends(get_database),
) -> UserRepository:
return InMemoryUserRepository(storage)
return PostgresUserRepository(database)
@staticmethod
def _get_chat_repository(
storage: InMemoryStorage = Depends(get_storage),
database: DatabasePoolManager = Depends(get_database),
) -> ChatRepository:
return InMemoryChatRepository(storage)
return PostgresChatRepository(database)
@staticmethod
def _get_message_repository(
storage: InMemoryStorage = Depends(get_storage),
database: DatabasePoolManager = Depends(get_database),
) -> MessageRepository:
return InMemoryMessageRepository(storage)
return PostgresMessageRepository(database)
@staticmethod
def _get_session_repository(
database: DatabasePoolManager = Depends(get_database),
) -> SessionRepository:
return PostgresSessionRepository(database)
@staticmethod
def _get_session_cache(
cache: CacheManager = Depends(get_cache),
) -> SessionCache:
return ValkeySessionCache(cache, SESSION_CACHE_TTL_SECONDS)
@staticmethod
def get_user_service(
repository: UserRepository = Depends(_get_user_repository),
hasher: PasswordHasher = Depends(get_password_hasher),
) -> UserService:
return UserService(repository)
return UserService(repository, hasher)
@staticmethod
def get_auth_service(
user_repository: UserRepository = Depends(_get_user_repository),
session_repository: SessionRepository = Depends(_get_session_repository),
session_cache: SessionCache = Depends(_get_session_cache),
hasher: PasswordHasher = Depends(get_password_hasher),
) -> AuthService:
return AuthService(
user_repository,
session_repository,
session_cache,
hasher,
SESSION_TTL_SECONDS,
)
@staticmethod
def get_chat_service(
chat_repository: ChatRepository = Depends(_get_chat_repository),
user_repository: UserRepository = Depends(_get_user_repository),
) -> ChatService:
return ChatService(chat_repository, user_repository)
return ChatService(chat_repository)
@staticmethod
def get_message_service(
@@ -1,9 +0,0 @@
from starlette.requests import HTTPConnection
from infrastructure.storage import InMemoryStorage
def get_storage(connection: HTTPConnection) -> InMemoryStorage:
"""Получение in-memory хранилища, созданного в lifespan."""
storage: InMemoryStorage = connection.app.state.storage
return storage
+10 -6
View File
@@ -1,9 +1,13 @@
from .chat_repository import InMemoryChatRepository
from .message_repository import InMemoryMessageRepository
from .user_repository import InMemoryUserRepository
from .chat_repository import PostgresChatRepository
from .message_repository import PostgresMessageRepository
from .session_cache import ValkeySessionCache
from .session_repository import PostgresSessionRepository
from .user_repository import PostgresUserRepository
__all__ = [
"InMemoryUserRepository",
"InMemoryChatRepository",
"InMemoryMessageRepository",
"PostgresUserRepository",
"PostgresChatRepository",
"PostgresMessageRepository",
"PostgresSessionRepository",
"ValkeySessionCache",
]
@@ -1,3 +1,3 @@
from .in_memory import InMemoryChatRepository
from .postgres import PostgresChatRepository
__all__ = ["InMemoryChatRepository"]
__all__ = ["PostgresChatRepository"]
@@ -1,36 +0,0 @@
from uuid import UUID, uuid4
from domain import ChatSchema, PageKey
from infrastructure.storage import InMemoryStorage
from infrastructure.utils import slice_after
from interfaces import ChatRepository
class InMemoryChatRepository(ChatRepository):
def __init__(self, storage: InMemoryStorage) -> None:
self._storage = storage
async def create(self, title: str, member_ids: list[UUID]) -> ChatSchema:
async with self._storage.chats_lock:
chat = ChatSchema(
id=uuid4(),
title=title,
member_ids=member_ids,
created_at=self._storage.chats_clock.now(),
)
self._storage.chats[chat.id] = chat
for member_id in chat.member_ids:
self._storage.chats_by_member.setdefault(member_id, []).append(chat)
return chat
async def get_for_member(self, chat_id: UUID, member_id: UUID) -> ChatSchema | None:
chat = self._storage.chats.get(chat_id)
if chat is None or member_id not in chat.member_ids:
return None
return chat
async def list_for_member(
self, member_id: UUID, after: PageKey | None, limit: int
) -> list[ChatSchema]:
chats = self._storage.chats_by_member.get(member_id, [])
return slice_after(chats, after, limit)
@@ -0,0 +1,150 @@
from uuid import UUID
import asyncpg
from domain import ChatSchema, PageKey
from domain.errors import InvalidRequestError
from infrastructure.utils import Pool, repository_logs, transaction
from interfaces import ChatRepository
class PostgresChatRepository(ChatRepository):
def __init__(self, pool: Pool) -> None:
self._pool = pool
@repository_logs
async def create(
self, title: str, created_by: UUID, member_ids: list[UUID]
) -> ChatSchema:
"""
Чат и участники — одна транзакция. Неизвестный участник нарушает FK
на users, транзакция откатывается целиком, строка chats не остаётся.
Участники вставляются одним запросом; position — порядок в member_ids.
"""
chat_query = """
INSERT INTO chats
(
title,
created_by
)
VALUES
(
$1,
$2
)
RETURNING id, title, created_at;
"""
members_query = """
INSERT INTO chat_members
(
chat_id,
user_id,
position
)
SELECT
$1,
member.user_id,
member.ordinality - 1
FROM unnest($2::uuid[]) WITH ORDINALITY AS member(user_id, ordinality);
"""
try:
async with transaction(self._pool) as conn:
row = await conn.fetchrow(chat_query, title, created_by)
assert row is not None
await conn.execute(members_query, row["id"], member_ids)
except asyncpg.ForeignKeyViolationError:
raise InvalidRequestError(
"member_ids содержит неизвестных пользователей"
) from None
return ChatSchema(
id=row["id"],
title=row["title"],
member_ids=member_ids,
created_at=row["created_at"],
)
@repository_logs
async def get_for_member(self, chat_id: UUID, member_id: UUID) -> ChatSchema | None:
query = """
SELECT
chat.id,
chat.title,
chat.created_at,
ARRAY(
SELECT member.user_id
FROM chat_members member
WHERE member.chat_id = chat.id
ORDER BY member.position
) AS member_ids
FROM chats chat
WHERE
chat.id = $1
AND EXISTS
(
SELECT 1
FROM chat_members caller
WHERE caller.chat_id = chat.id AND caller.user_id = $2
);
"""
async with self._pool.acquire() as conn:
row = await conn.fetchrow(query, chat_id, member_id)
return self._row_to_chat(row) if row is not None else None
@repository_logs
async def list_for_member(
self, member_id: UUID, after: PageKey | None, limit: int
) -> list[ChatSchema]:
"""Чаты пользователя по (created_at, id); со второй страницы — после ключа"""
first_page_query = """
SELECT
chat.id,
chat.title,
chat.created_at,
ARRAY(
SELECT member.user_id
FROM chat_members member
WHERE member.chat_id = chat.id
ORDER BY member.position
) AS member_ids
FROM chat_members caller
JOIN chats chat ON chat.id = caller.chat_id
WHERE caller.user_id = $1
ORDER BY chat.created_at, chat.id
LIMIT $2;
"""
next_page_query = """
SELECT
chat.id,
chat.title,
chat.created_at,
ARRAY(
SELECT member.user_id
FROM chat_members member
WHERE member.chat_id = chat.id
ORDER BY member.position
) AS member_ids
FROM chat_members caller
JOIN chats chat ON chat.id = caller.chat_id
WHERE
caller.user_id = $1
AND (chat.created_at, chat.id) > ($2, $3)
ORDER BY chat.created_at, chat.id
LIMIT $4;
"""
async with self._pool.acquire() as conn:
if after is None:
rows = await conn.fetch(first_page_query, member_id, limit)
else:
rows = await conn.fetch(
next_page_query, member_id, after.created_at, after.id, limit
)
return [self._row_to_chat(row) for row in rows]
@staticmethod
def _row_to_chat(row: asyncpg.Record) -> ChatSchema:
return ChatSchema(
id=row["id"],
title=row["title"],
member_ids=row["member_ids"],
created_at=row["created_at"],
)
@@ -1,3 +1,3 @@
from .in_memory import InMemoryMessageRepository
from .postgres import PostgresMessageRepository
__all__ = ["InMemoryMessageRepository"]
__all__ = ["PostgresMessageRepository"]
@@ -1,29 +0,0 @@
from uuid import UUID, uuid4
from domain import MessageSchema, PageKey
from infrastructure.storage import InMemoryStorage
from infrastructure.utils import slice_after
from interfaces import MessageRepository
class InMemoryMessageRepository(MessageRepository):
def __init__(self, storage: InMemoryStorage) -> None:
self._storage = storage
async def create(self, chat_id: UUID, sender_id: UUID, text: str) -> MessageSchema:
async with self._storage.messages_lock:
message = MessageSchema(
id=uuid4(),
chat_id=chat_id,
sender_id=sender_id,
text=text,
created_at=self._storage.messages_clock.now(),
)
self._storage.messages_by_chat.setdefault(chat_id, []).append(message)
return message
async def list_for_chat(
self, chat_id: UUID, after: PageKey | None, limit: int
) -> list[MessageSchema]:
history = self._storage.messages_by_chat.get(chat_id, [])
return slice_after(history, after, limit)
@@ -0,0 +1,106 @@
from uuid import UUID
import asyncpg
from domain import MessageSchema, PageKey
from infrastructure.utils import Pool, repository_logs, transaction
from interfaces import MessageRepository
# Пространство ключей advisory lock: (namespace, hashtext(chat_id))
CHAT_LOCK_NAMESPACE = 2
class PostgresMessageRepository(MessageRepository):
def __init__(self, pool: Pool) -> None:
self._pool = pool
@repository_logs
async def create(self, chat_id: UUID, sender_id: UUID, text: str) -> MessageSchema:
"""
Блокировка чата и вставка — одна транзакция; lock снимается на COMMIT.
Запись в один чат сериализуется, записи в разные чаты не мешают друг другу.
created_at строго больше последнего в чате, даже если часы ушли назад:
порядок коммитов совпадает с порядком (created_at, id), и читатель
с cursor не пропустит сообщение. MAX берётся из индекса
(chat_id, created_at, id) — Index Only Scan Backward, а не проход по истории.
"""
lock_query = """
SELECT pg_advisory_xact_lock($1, hashtext($2::uuid::text));
"""
insert_query = """
INSERT INTO messages
(
chat_id,
sender_id,
text,
created_at
)
SELECT
$1,
$2,
$3,
GREATEST(clock_timestamp(), MAX(created_at) + interval '1 microsecond')
FROM messages
WHERE chat_id = $1
RETURNING id, chat_id, sender_id, text, created_at;
"""
async with transaction(self._pool) as conn:
await conn.execute(lock_query, CHAT_LOCK_NAMESPACE, chat_id)
row = await conn.fetchrow(insert_query, chat_id, sender_id, text)
assert row is not None
return self._row_to_message(row)
@repository_logs
async def list_for_chat(
self, chat_id: UUID, after: PageKey | None, limit: int
) -> list[MessageSchema]:
"""
История по (created_at, id). Со второй страницы Index Cond по
(chat_id, created_at, id) начинает чтение сразу после cursor
и останавливается после LIMIT строк.
"""
first_page_query = """
SELECT
id,
chat_id,
sender_id,
text,
created_at
FROM messages
WHERE chat_id = $1
ORDER BY created_at, id
LIMIT $2;
"""
next_page_query = """
SELECT
id,
chat_id,
sender_id,
text,
created_at
FROM messages
WHERE
chat_id = $1
AND (created_at, id) > ($2, $3)
ORDER BY created_at, id
LIMIT $4;
"""
async with self._pool.acquire() as conn:
if after is None:
rows = await conn.fetch(first_page_query, chat_id, limit)
else:
rows = await conn.fetch(
next_page_query, chat_id, after.created_at, after.id, limit
)
return [self._row_to_message(row) for row in rows]
@staticmethod
def _row_to_message(row: asyncpg.Record) -> MessageSchema:
return MessageSchema(
id=row["id"],
chat_id=row["chat_id"],
sender_id=row["sender_id"],
text=row["text"],
created_at=row["created_at"],
)
@@ -0,0 +1,3 @@
from .valkey import ValkeySessionCache
__all__ = ["ValkeySessionCache"]
@@ -0,0 +1,87 @@
import math
from datetime import UTC, datetime
from typing import TYPE_CHECKING
from pydantic import ValidationError
from redis.exceptions import RedisError
from config import LOGGER
from domain import ActiveSessionSchema
from interfaces import SessionCache
if TYPE_CHECKING:
from infrastructure.dependencies.cache import CacheManager
KEY_PREFIX = "session:"
CACHE_UNAVAILABLE_ERRORS: tuple[type[Exception], ...] = (
RedisError,
OSError,
TimeoutError,
)
class ValkeySessionCache(SessionCache):
"""
Read-through кэш сессий в Valkey.
Ключ session:<sha256 токена hex>, значение — JSON ActiveSessionSchema.
TTL = min(остаток жизни сессии, max_ttl): запись исчезает не позже сессии,
а max_ttl ограничивает окно устаревания, если инвалидация не дошла.
"""
def __init__(self, cache: "CacheManager", max_ttl_seconds: int) -> None:
self._cache = cache
self._max_ttl_ms = max_ttl_seconds * 1000
async def get(self, token_hash: bytes) -> ActiveSessionSchema | None:
if not self._cache.is_available or self._cache.client is None:
return None
try:
raw = await self._cache.client.get(self._key(token_hash))
except CACHE_UNAVAILABLE_ERRORS as error:
self._cache.mark_failed(error)
return None
if raw is None:
return None
try:
return ActiveSessionSchema.model_validate_json(raw)
except ValidationError:
LOGGER.warning("Повреждённая запись кэша сессии проигнорирована")
return None
async def set(self, token_hash: bytes, session: ActiveSessionSchema) -> None:
if not self._cache.is_available or self._cache.client is None:
return
remaining = session.expires_at - datetime.now(UTC)
ttl_ms = min(self._max_ttl_ms, math.floor(remaining.total_seconds() * 1000))
if ttl_ms <= 0:
return
try:
await self._cache.client.set(
self._key(token_hash), session.model_dump_json(), px=ttl_ms
)
except CACHE_UNAVAILABLE_ERRORS as error:
self._cache.mark_failed(error)
async def delete(self, token_hash: bytes) -> bool:
if self._cache.client is None:
return False
try:
await self._cache.client.delete(self._key(token_hash))
except CACHE_UNAVAILABLE_ERRORS as error:
self._cache.mark_failed(error)
return False
return True
async def ping(self) -> bool:
if self._cache.client is None:
return False
try:
return bool(await self._cache.client.ping())
except CACHE_UNAVAILABLE_ERRORS:
return False
@staticmethod
def _key(token_hash: bytes) -> str:
return KEY_PREFIX + token_hash.hex()
@@ -0,0 +1,3 @@
from .postgres import PostgresSessionRepository
__all__ = ["PostgresSessionRepository"]
@@ -0,0 +1,85 @@
from datetime import datetime
from uuid import UUID
from domain import ActiveSessionSchema, UserSchema
from infrastructure.utils import Pool, repository_logs
from interfaces import SessionRepository
class PostgresSessionRepository(SessionRepository):
def __init__(self, pool: Pool) -> None:
self._pool = pool
@repository_logs
async def create(
self, token_hash: bytes, user_id: UUID, ttl_seconds: int
) -> datetime:
query = """
INSERT INTO sessions
(
token_hash,
user_id,
expires_at
)
VALUES
(
$1,
$2,
clock_timestamp() + make_interval(secs => $3::integer)
)
RETURNING expires_at;
"""
async with self._pool.acquire() as conn:
expires_at: datetime = await conn.fetchval(
query, token_hash, user_id, ttl_seconds
)
return expires_at
@repository_logs
async def get_active(self, token_hash: bytes) -> ActiveSessionSchema | None:
"""Поиск по PK; истёкшая или отозванная сессия не возвращается"""
query = """
SELECT
usr.id,
usr.username,
usr.display_name,
usr.created_at,
session.expires_at
FROM sessions session
JOIN users usr ON usr.id = session.user_id
WHERE
session.token_hash = $1
AND session.revoked_at IS NULL
AND session.expires_at > clock_timestamp();
"""
async with self._pool.acquire() as conn:
row = await conn.fetchrow(query, token_hash)
if row is None:
return None
return ActiveSessionSchema(
user=UserSchema(
id=row["id"],
username=row["username"],
display_name=row["display_name"],
created_at=row["created_at"],
),
expires_at=row["expires_at"],
)
@repository_logs
async def revoke(self, token_hash: bytes) -> bool:
query = """
UPDATE sessions
SET revoked_at = clock_timestamp()
WHERE
token_hash = $1
AND revoked_at IS NULL
AND expires_at > clock_timestamp();
"""
async with self._pool.acquire() as conn:
status = await conn.execute(query, token_hash)
return self._parse_affected(status) > 0
@staticmethod
def _parse_affected(status: str) -> int:
return int(status.split()[-1])
@@ -1,3 +1,3 @@
from .in_memory import InMemoryUserRepository
from .postgres import PostgresUserRepository
__all__ = ["InMemoryUserRepository"]
__all__ = ["PostgresUserRepository"]
@@ -1,32 +0,0 @@
from datetime import UTC, datetime
from uuid import UUID, uuid4
from domain import UserSchema
from domain.errors import ConflictError
from infrastructure.storage import InMemoryStorage
from interfaces import UserRepository
class InMemoryUserRepository(UserRepository):
def __init__(self, storage: InMemoryStorage) -> None:
self._storage = storage
async def create(self, username: str, display_name: str) -> UserSchema:
async with self._storage.users_lock:
if username in self._storage.user_ids_by_username:
raise ConflictError("Имя пользователя уже занято")
user = UserSchema(
id=uuid4(),
username=username,
display_name=display_name,
created_at=datetime.now(UTC),
)
self._storage.users[user.id] = user
self._storage.user_ids_by_username[user.username] = user.id
return user
async def get_by_id(self, user_id: UUID) -> UserSchema | None:
return self._storage.users.get(user_id)
async def get_missing_ids(self, user_ids: list[UUID]) -> set[UUID]:
return {user_id for user_id in user_ids if user_id not in self._storage.users}
@@ -0,0 +1,67 @@
import asyncpg
from domain import UserCredentialsSchema, UserSchema
from domain.errors import ConflictError
from infrastructure.utils import Pool, repository_logs
from interfaces import UserRepository
class PostgresUserRepository(UserRepository):
def __init__(self, pool: Pool) -> None:
self._pool = pool
@repository_logs
async def create(
self, username: str, display_name: str, password_hash: str
) -> UserSchema:
query = """
INSERT INTO users
(
username,
display_name,
password_hash
)
VALUES
(
$1,
$2,
$3
)
RETURNING id, username, display_name, created_at;
"""
async with self._pool.acquire() as conn:
try:
row = await conn.fetchrow(query, username, display_name, password_hash)
except asyncpg.UniqueViolationError:
raise ConflictError("Имя пользователя уже занято") from None
assert row is not None
return self._row_to_user(row)
@repository_logs
async def get_credentials(self, username: str) -> UserCredentialsSchema | None:
query = """
SELECT
id,
username,
display_name,
created_at,
password_hash
FROM users
WHERE username = $1;
"""
async with self._pool.acquire() as conn:
row = await conn.fetchrow(query, username)
if row is None:
return None
return UserCredentialsSchema(
user=self._row_to_user(row), password_hash=row["password_hash"]
)
@staticmethod
def _row_to_user(row: asyncpg.Record) -> UserSchema:
return UserSchema(
id=row["id"],
username=row["username"],
display_name=row["display_name"],
created_at=row["created_at"],
)
+4
View File
@@ -0,0 +1,4 @@
from .password_hasher import PasswordHasher, get_password_hasher
from .tokens import generate_token, hash_token
__all__ = ["PasswordHasher", "get_password_hasher", "generate_token", "hash_token"]
@@ -0,0 +1,50 @@
import asyncio
import secrets
from concurrent.futures import ThreadPoolExecutor
from argon2 import PasswordHasher as Argon2Hasher
from argon2.exceptions import InvalidHashError, VerificationError
from argon2.profiles import RFC_9106_LOW_MEMORY
from starlette.requests import HTTPConnection
class PasswordHasher:
"""
Хеширование паролей с использованием Argon2id.
"""
def __init__(self, workers: int) -> None:
self._hasher = Argon2Hasher.from_parameters(RFC_9106_LOW_MEMORY)
self._executor = ThreadPoolExecutor(
max_workers=workers, thread_name_prefix="argon2"
)
self._dummy_hash = self._hasher.hash(secrets.token_urlsafe())
async def hash(self, password: str) -> str:
loop = asyncio.get_running_loop()
return await loop.run_in_executor(self._executor, self._hasher.hash, password)
async def verify(self, password_hash: str, password: str) -> bool:
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
self._executor, self._verify, password_hash, password
)
async def verify_dummy(self, password: str) -> None:
"""Та же работа, что у verify, для выравнивания времени ответа"""
await self.verify(self._dummy_hash, password)
def close(self) -> None:
self._executor.shutdown(wait=False, cancel_futures=True)
def _verify(self, password_hash: str, password: str) -> bool:
try:
return self._hasher.verify(password_hash, password)
except (VerificationError, InvalidHashError):
return False
def get_password_hasher(connection: HTTPConnection) -> PasswordHasher:
"""Получение hasher, созданного в lifespan."""
hasher: PasswordHasher = connection.app.state.password_hasher
return hasher
+17
View File
@@ -0,0 +1,17 @@
import hashlib
import secrets
def generate_token() -> str:
"""Непрозрачный токен сессии: 256 бит из CSPRNG, base64url"""
return secrets.token_urlsafe(32)
def hash_token(token: str) -> bytes:
"""
SHA-256 токена для хранения и поиска.
Токен уже имеет 256 бит энтропии, перебор невозможен, поэтому быстрый hash
достаточен; медленный KDF нужен паролям, у которых энтропия низкая.
"""
return hashlib.sha256(token.encode()).digest()
+2 -1
View File
@@ -1,5 +1,6 @@
from .auth_service import AuthService
from .chat_service import ChatService
from .message_service import MessageService
from .user_service import UserService
__all__ = ["UserService", "ChatService", "MessageService"]
__all__ = ["UserService", "AuthService", "ChatService", "MessageService"]
@@ -0,0 +1,3 @@
from .auth_service import AuthService
__all__ = ["AuthService"]
@@ -0,0 +1,92 @@
from datetime import UTC, datetime
from config import LOGGER
from domain import BasicCredentialsSchema, SessionSchema, UserSchema
from domain.errors import InvalidCredentialsError, UnauthorizedError
from infrastructure.security import PasswordHasher, generate_token, hash_token
from interfaces import SessionCache, SessionRepository, UserRepository
TOKEN_MAX_LENGTH = 256
class AuthService:
"""
Basic → opaque Bearer-сессия.
Источник истины — SessionRepository (PostgreSQL), SessionCache (Valkey) —
read-through кэш: при промахе или недоступности кэша сессия читается из БД.
"""
def __init__(
self,
user_repository: UserRepository,
session_repository: SessionRepository,
session_cache: SessionCache,
hasher: PasswordHasher,
session_ttl_seconds: int,
) -> None:
self._users = user_repository
self._sessions = session_repository
self._cache = session_cache
self._hasher = hasher
self._session_ttl = session_ttl_seconds
async def login(self, credentials: BasicCredentialsSchema) -> SessionSchema:
"""
Создание сессии по username и паролю.
Raises:
InvalidCredentialsError: неизвестный username или неверный пароль —
одинаковый ответ и сопоставимое время
"""
found = await self._users.get_credentials(credentials.username)
if found is None:
await self._hasher.verify_dummy(credentials.password)
raise InvalidCredentialsError()
if not await self._hasher.verify(found.password_hash, credentials.password):
raise InvalidCredentialsError()
token = generate_token()
expires_at = await self._sessions.create(
hash_token(token), found.user.id, self._session_ttl
)
LOGGER.info(f"Создана сессия пользователя {found.user.id}")
return SessionSchema(token=token, expires_at=expires_at, user=found.user)
async def authenticate(self, token: str | None) -> UserSchema:
"""
Владелец действующей сессии.
Raises:
UnauthorizedError: токена нет, он неизвестен, истёк или отозван
UnavailableError: кэш промахнулся, а PostgreSQL недоступен
"""
if not token or len(token) > TOKEN_MAX_LENGTH:
raise UnauthorizedError()
token_hash = hash_token(token)
session = await self._cache.get(token_hash)
if session is not None and session.expires_at > datetime.now(UTC):
return session.user
session = await self._sessions.get_active(token_hash)
if session is None:
raise UnauthorizedError()
await self._cache.set(token_hash, session)
return session.user
async def logout(self, token: str | None) -> None:
"""
Отзыв в источнике истины, затем инвалидация кэша.
Raises:
UnauthorizedError: действующей сессии с таким токеном нет
"""
if not token or len(token) > TOKEN_MAX_LENGTH:
raise UnauthorizedError()
token_hash = hash_token(token)
if not await self._sessions.revoke(token_hash):
raise UnauthorizedError()
if not await self._cache.delete(token_hash):
LOGGER.warning(
"Сессия отозвана в PostgreSQL, но запись кэша не удалена: "
"она истечёт по TTL кэша"
)
LOGGER.info("Сессия отозвана")
@@ -4,27 +4,26 @@ from config import LOGGER
from domain import ChatPageSchema, ChatSchema, CreateChatSchema, UserSchema
from domain.errors import InvalidRequestError, NotFoundError
from infrastructure.utils import build_page, decode_cursor
from interfaces import ChatRepository, UserRepository
from interfaces import ChatRepository
class ChatService:
def __init__(
self, chat_repository: ChatRepository, user_repository: UserRepository
) -> None:
def __init__(self, chat_repository: ChatRepository) -> None:
self._chats = chat_repository
self._users = user_repository
async def create_chat(
self, current_user: UserSchema, data: CreateChatSchema
) -> ChatSchema:
"""Чат создаётся из явного списка существующих участников, включая создателя"""
"""
Чат создаётся из явного списка существующих участников, включая создателя.
Существование участников проверяет FK в транзакции создания: отдельная
предварительная проверка была бы гонкой и не нужна для отката.
"""
if current_user.id not in data.member_ids:
raise InvalidRequestError(
"member_ids должен содержать текущего пользователя"
)
if await self._users.get_missing_ids(data.member_ids):
raise InvalidRequestError("member_ids содержит неизвестных пользователей")
chat = await self._chats.create(data.title, data.member_ids)
chat = await self._chats.create(data.title, current_user.id, data.member_ids)
LOGGER.info(
f"Создан чат {chat.id} пользователем {current_user.id}, "
f"участников: {len(chat.member_ids)}"
@@ -1,34 +1,17 @@
from uuid import UUID
from config import LOGGER
from domain import CreateUserSchema, UserSchema
from domain.errors import UnauthorizedError
from infrastructure.security import PasswordHasher
from interfaces import UserRepository
class UserService:
def __init__(self, repository: UserRepository) -> None:
def __init__(self, repository: UserRepository, hasher: PasswordHasher) -> None:
self._repo = repository
self._hasher = hasher
async def register(self, data: CreateUserSchema) -> UserSchema:
user = await self._repo.create(data.username, data.display_name)
"""Пароль сохраняется только как hash Argon2id"""
password_hash = await self._hasher.hash(data.password)
user = await self._repo.create(data.username, data.display_name, password_hash)
LOGGER.info(f"Зарегистрирован пользователь {user.id}")
return user
async def authenticate(self, raw_user_id: str | None) -> UserSchema:
"""
Учебная идентификация lab1: X-User-Id с UUID существующего пользователя.
Raises:
UnauthorizedError: заголовка нет, он не UUID или пользователь неизвестен
"""
if not raw_user_id:
raise UnauthorizedError()
try:
user_id = UUID(raw_user_id)
except ValueError:
raise UnauthorizedError() from None
user = await self._repo.get_by_id(user_id)
if user is None:
raise UnauthorizedError()
return user
-3
View File
@@ -1,3 +0,0 @@
from .in_memory import InMemoryStorage
__all__ = ["InMemoryStorage"]
-23
View File
@@ -1,23 +0,0 @@
import asyncio
from uuid import UUID
from domain import ChatSchema, MessageSchema, UserSchema
from infrastructure.utils import MonotonicClock
class InMemoryStorage:
"""Всё состояние мессенджера в памяти одного процесса."""
def __init__(self) -> None:
self.users: dict[UUID, UserSchema] = {}
self.user_ids_by_username: dict[str, UUID] = {}
self.users_lock = asyncio.Lock()
self.chats: dict[UUID, ChatSchema] = {}
self.chats_by_member: dict[UUID, list[ChatSchema]] = {}
self.chats_lock = asyncio.Lock()
self.chats_clock = MonotonicClock()
self.messages_by_chat: dict[UUID, list[MessageSchema]] = {}
self.messages_lock = asyncio.Lock()
self.messages_clock = MonotonicClock()
+8 -10
View File
@@ -1,17 +1,15 @@
from .clock import MonotonicClock
from .pagination import (
build_page,
decode_cursor,
encode_cursor,
page_key,
slice_after,
)
from .pagination import build_page, decode_cursor, encode_cursor, page_key
from .repository_utils import DATABASE_UNAVAILABLE_ERRORS, repository_logs
from .transaction import ConnectionPool, Pool, transaction
__all__ = [
"MonotonicClock",
"page_key",
"slice_after",
"encode_cursor",
"decode_cursor",
"build_page",
"repository_logs",
"DATABASE_UNAVAILABLE_ERRORS",
"ConnectionPool",
"Pool",
"transaction",
]
-22
View File
@@ -1,22 +0,0 @@
from datetime import UTC, datetime, timedelta
CLOCK_STEP = timedelta(microseconds=1)
class MonotonicClock:
"""
Строго возрастающее время UTC.
Две записи не получат одинаковый created_at, а перевод системных часов назад
не поставит новую запись перед уже прочитанной. Вызывать под локом коллекции.
"""
def __init__(self) -> None:
self._last: datetime | None = None
def now(self) -> datetime:
current = datetime.now(UTC)
if self._last is not None and current <= self._last:
current = self._last + CLOCK_STEP
self._last = current
return current
-9
View File
@@ -1,6 +1,5 @@
import base64
import binascii
from bisect import bisect_right
from pydantic import ValidationError
@@ -14,14 +13,6 @@ def page_key(item: PageItem) -> PageKey:
return PageKey(item.created_at, item.id)
def slice_after(
items: list[PageItem], after: PageKey | None, limit: int
) -> list[PageItem]:
"""Элементы строго после ключа; items отсортированы по page_key"""
start = 0 if after is None else bisect_right(items, after, key=page_key)
return items[start : start + limit]
def encode_cursor(scope: str, key: PageKey) -> str:
"""Непрозрачный cursor: base64url от JSON с ресурсом и ключом последнего элемента"""
payload = PageCursorSchema(scope=scope, created_at=key.created_at, id=key.id)
@@ -0,0 +1,39 @@
from collections.abc import Callable
from functools import wraps
from typing import Any
import asyncpg
from config import LOGGER
from domain.errors import UnavailableError
DATABASE_UNAVAILABLE_ERRORS: tuple[type[Exception], ...] = (
OSError,
TimeoutError,
asyncpg.PostgresConnectionError,
asyncpg.InterfaceError,
asyncpg.exceptions.OperatorInterventionError,
asyncpg.exceptions.InsufficientResourcesError,
)
def repository_logs(func: Callable) -> Callable:
"""
Decorator for logging database requests.
"""
@wraps(func)
async def wrapper(*args: Any, **kwargs: Any) -> Any:
log_text = (
f"Request to DATABASE || Object: {args[0].__class__.__name__} "
f"|| Function: {func.__name__} || "
)
try:
result = await func(*args, **kwargs)
except DATABASE_UNAVAILABLE_ERRORS as error:
LOGGER.warning(log_text + f"failed || Error: {type(error).__name__}")
raise UnavailableError() from None
LOGGER.debug(log_text + "completed")
return result
return wrapper
+29
View File
@@ -0,0 +1,29 @@
from collections.abc import AsyncIterator
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from typing import Protocol
import asyncpg
class Pool(Protocol):
"""Источник соединений: DatabasePoolManager или одно соединение транзакции"""
def acquire(self) -> AbstractAsyncContextManager[asyncpg.Connection]: ...
class ConnectionPool:
"""Pool-подобная обёртка над одним соединением."""
def __init__(self, conn: asyncpg.Connection) -> None:
self.connection = conn
@asynccontextmanager
async def acquire(self) -> AsyncIterator[asyncpg.Connection]:
yield self.connection
@asynccontextmanager
async def transaction(pool: Pool) -> AsyncIterator[asyncpg.Connection]:
async with pool.acquire() as conn:
async with conn.transaction():
yield conn
+9 -1
View File
@@ -1,5 +1,13 @@
from .chat_repository import ChatRepository
from .message_repository import MessageRepository
from .session_cache import SessionCache
from .session_repository import SessionRepository
from .user_repository import UserRepository
__all__ = ["UserRepository", "ChatRepository", "MessageRepository"]
__all__ = [
"UserRepository",
"ChatRepository",
"MessageRepository",
"SessionRepository",
"SessionCache",
]
+13 -4
View File
@@ -8,18 +8,27 @@ class ChatRepository(ABC):
"""Слой абстракции хранилища чатов"""
@abstractmethod
async def create(self, title: str, member_ids: list[UUID]) -> ChatSchema:
"""сохраняет чат и индексирует его по участникам."""
async def create(
self, title: str, created_by: UUID, member_ids: list[UUID]
) -> ChatSchema:
"""
создание чата вместе с участниками: при любой ошибке
не остаётся ни чата, ни части участников.
"""
pass
@abstractmethod
async def get_for_member(self, chat_id: UUID, member_id: UUID) -> ChatSchema | None:
"""Получение чата, только если пользователь является его участником."""
"""
Получение чата, только если пользователь является его участником.
"""
pass
@abstractmethod
async def list_for_member(
self, member_id: UUID, after: PageKey | None, limit: int
) -> list[ChatSchema]:
"""Чаты пользователя по (created_at, id) по возрастанию."""
"""
Чаты пользователя по (created_at, id) по возрастанию.
"""
pass
+8 -2
View File
@@ -9,12 +9,18 @@ class MessageRepository(ABC):
@abstractmethod
async def create(self, chat_id: UUID, sender_id: UUID, text: str) -> MessageSchema:
"""Атомарно назначает id, created_at и добавляет сообщение в конец истории чата."""
"""
Добавление сообщения в конец истории чата. id и created_at назначает
хранилище; created_at строго возрастает внутри чата, поэтому сообщение
не может появиться перед уже выданным cursor.
"""
pass
@abstractmethod
async def list_for_chat(
self, chat_id: UUID, after: PageKey | None, limit: int
) -> list[MessageSchema]:
"""История чата по (created_at, id) по возрастанию."""
"""
История чата по (created_at, id) по возрастанию.
"""
pass
+35
View File
@@ -0,0 +1,35 @@
from abc import ABC, abstractmethod
from domain import ActiveSessionSchema
class SessionCache(ABC):
"""
Слой абстракции кэша сессий. Кэш не источник истины: любой метод при
недоступности кэша не бросает исключение, а сообщает промах/пропуск,
и вызывающий идёт в SessionRepository.
"""
@abstractmethod
async def get(self, token_hash: bytes) -> ActiveSessionSchema | None:
"""
Сессия из кэша.
"""
pass
@abstractmethod
async def set(self, token_hash: bytes, session: ActiveSessionSchema) -> None:
"""Запись сессии с TTL не дольше её оставшейся жизни"""
pass
@abstractmethod
async def delete(self, token_hash: bytes) -> bool:
"""
Инвалидация записи после отзыва сессии.
"""
pass
@abstractmethod
async def ping(self) -> bool:
"""Доступность кэша для readiness и диагностики"""
pass
+36
View File
@@ -0,0 +1,36 @@
from abc import ABC, abstractmethod
from datetime import datetime
from uuid import UUID
from domain import ActiveSessionSchema
class SessionRepository(ABC):
"""
Слой абстракции хранилища сессий — источника истины.
Хранится только hash токена, сам токен знает лишь клиент.
"""
@abstractmethod
async def create(
self, token_hash: bytes, user_id: UUID, ttl_seconds: int
) -> datetime:
"""
Сохранение новой сессии. Срок считается по часам хранилища — тем же,
по которым потом проверяется истечение.
"""
pass
@abstractmethod
async def get_active(self, token_hash: bytes) -> ActiveSessionSchema | None:
"""
Действующая сессия: не истекла и не отозвана.
"""
pass
@abstractmethod
async def revoke(self, token_hash: bytes) -> bool:
"""
Отзыв действующей сессии (logout).
"""
pass
+12 -11
View File
@@ -1,23 +1,24 @@
from abc import ABC, abstractmethod
from uuid import UUID
from domain import UserSchema
from domain import UserCredentialsSchema, UserSchema
class UserRepository(ABC):
"""Слой абстракции хранилища пользователей"""
@abstractmethod
async def create(self, username: str, display_name: str) -> UserSchema:
"""проверяет уникальность username и сохраняет пользователя."""
async def create(
self, username: str, display_name: str, password_hash: str
) -> UserSchema:
"""
Сохранение пользователя. Уникальность username гарантирует хранилище,
поэтому одновременные регистрации одного имени не создают дубликат.
"""
pass
@abstractmethod
async def get_by_id(self, user_id: UUID) -> UserSchema | None:
"""Получение пользователя по ID."""
pass
@abstractmethod
async def get_missing_ids(self, user_ids: list[UUID]) -> set[UUID]:
"""Возвращает ID из списка, для которых пользователей не существует."""
async def get_credentials(self, username: str) -> UserCredentialsSchema | None:
"""
Пользователь и hash его пароля для проверки входа.
"""
pass
+21 -8
View File
@@ -5,7 +5,7 @@ from pathlib import Path
import httpx
import pytest
from helpers import auth, unique_username
from helpers import auth, basic, unique_password, unique_username
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_BASE_URL = json.loads((ROOT / "lab.json").read_text())["default_base_url"]
@@ -24,16 +24,29 @@ def api(base_url: str) -> Iterator[httpx.Client]:
yield client
def register_and_login(
client: httpx.Client, label: str, display_name: str | None = None
) -> dict:
"""Регистрация и вход; в словаре User плюс token и password для тестов"""
username = unique_username(label)
password = unique_password()
body = {
"username": username,
"display_name": display_name or f"Студент {label}",
"password": password,
}
response = client.post("/api/v1/users", json=body)
assert response.status_code == 201, response.text
user = response.json()
session = client.post("/api/v1/auth/sessions", headers=basic(username, password))
assert session.status_code == 201, session.text
return {**user, "token": session.json()["token"], "password": password}
@pytest.fixture
def make_user(api: httpx.Client) -> Callable[..., dict]:
def create(label: str = "user", display_name: str | None = None) -> dict:
body = {
"username": unique_username(label),
"display_name": display_name or f"Студент {label}",
}
response = api.post("/api/v1/users", json=body)
assert response.status_code == 201, response.text
return response.json()
return register_and_login(api, label, display_name)
return create
+56 -1
View File
@@ -1,16 +1,38 @@
"""Общие проверки для собственных black-box тестов"""
import base64
import subprocess
import uuid
from pathlib import Path
import httpx
ROOT = Path(__file__).resolve().parents[1]
USER_FIELDS = ("id", "username", "display_name", "created_at")
def unique_username(label: str) -> str:
return f"st_{label}_{uuid.uuid4().hex[:12]}"
def unique_password() -> str:
return f"Pw-{uuid.uuid4().hex}"
def basic(username: str, password: str) -> dict[str, str]:
"""Authorization: Basic; пароль кодируется в UTF-8"""
raw = f"{username}:{password}".encode()
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
def auth(user: dict) -> dict[str, str]:
return {"X-User-Id": user["id"]}
return {"Authorization": f"Bearer {user['token']}"}
def public_user(user: dict) -> dict:
"""User из ответа API без тестовых полей token/password"""
return {field: user[field] for field in USER_FIELDS}
def assert_error(response: httpx.Response, status: int, code: str) -> None:
@@ -23,6 +45,12 @@ def assert_error(response: httpx.Response, status: int, code: str) -> None:
assert error["request_id"] == response.headers["X-Request-Id"]
def assert_unauthorized(response: httpx.Response, scheme: str = "Bearer") -> None:
"""401 с challenge нужной схемы"""
assert_error(response, 401, "unauthorized")
assert response.headers["WWW-Authenticate"].startswith(scheme)
def read_all_messages(
api: httpx.Client, user: dict, chat_id: str, limit: int
) -> tuple[list[dict], int]:
@@ -41,3 +69,30 @@ def read_all_messages(
if page["next_cursor"] is None:
return items, pages
params = {"limit": limit, "cursor": page["next_cursor"]}
def compose(*args: str, stdin: str | None = None) -> str:
"""docker compose из корня репозитория; вывод не печатается (может быть секретен)"""
result = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
input=stdin,
capture_output=True,
text=True,
timeout=120,
check=True,
)
return result.stdout
def psql(sql: str) -> str:
"""Запрос в PostgreSQL стенда изнутри контейнера; порт БД наружу не открыт"""
return compose(
"exec",
"-T",
"postgres",
"sh",
"-c",
'psql -X -q -tA -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
stdin=sql,
).strip()
+131
View File
@@ -0,0 +1,131 @@
"""Вход по Basic, opaque Bearer-сессия, неверный пароль и logout"""
import base64
from datetime import UTC, datetime
import httpx
import pytest
from helpers import (
assert_unauthorized,
auth,
basic,
psql,
public_user,
unique_username,
)
SESSIONS_PATH = "/api/v1/auth/sessions"
CURRENT_SESSION_PATH = "/api/v1/auth/sessions/current"
def test_login_returns_opaque_bearer_session(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
response = api.post(
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
)
assert response.status_code == 201, response.text
session = response.json()
assert set(session) == {"token", "token_type", "expires_at", "user"}
assert session["token_type"] == "Bearer"
assert session["user"] == public_user(alice)
assert len(session["token"]) >= 43 # 32 байта в base64url
assert alice["id"] not in session["token"]
assert alice["username"] not in session["token"]
assert session["token"] != alice["token"]
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
assert expires_at > datetime.now(UTC)
def test_wrong_password_and_unknown_user_are_indistinguishable(
api: httpx.Client, make_user
) -> None:
alice = make_user("alice")
wrong = api.post(SESSIONS_PATH, headers=basic(alice["username"], "Wrong-pass-123"))
unknown = api.post(
SESSIONS_PATH, headers=basic(unique_username("ghost"), "Wrong-pass-123")
)
for response in (wrong, unknown):
assert_unauthorized(response, scheme="Basic")
assert 'realm="messenger"' in response.headers["WWW-Authenticate"]
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
@pytest.mark.parametrize(
"authorization",
[
None,
"",
"Basic",
"Basic !!!not-base64!!!",
"Basic " + base64.b64encode(b"no-colon-here").decode(),
"Basic " + base64.b64encode(b"\xff\xfe:password").decode(),
"Bearer some-token",
],
)
def test_malformed_basic_is_unauthorized(
api: httpx.Client, authorization: str | None
) -> None:
headers = {} if authorization is None else {"Authorization": authorization}
assert_unauthorized(api.post(SESSIONS_PATH, headers=headers), scheme="Basic")
def test_utf8_password_with_colon(api: httpx.Client) -> None:
username = unique_username("utf")
password = "пароль:с:двоеточием 🔐"
body = {"username": username, "display_name": "x", "password": password}
assert api.post("/api/v1/users", json=body).status_code == 201
assert api.post(SESSIONS_PATH, headers=basic(username, password)).status_code == 201
assert_unauthorized(
api.post(SESSIONS_PATH, headers=basic(username, "пароль:с:двоеточием")),
scheme="Basic",
)
def test_basic_is_rejected_on_business_endpoints(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
headers = basic(alice["username"], alice["password"])
assert_unauthorized(api.get("/api/v1/users/me", headers=headers))
assert_unauthorized(api.get("/api/v1/chats", headers=headers))
def test_logout_revokes_only_current_session(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
second = api.post(
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
)
other_session = {**alice, "token": second.json()["token"]}
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
response = api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
assert response.status_code == 204
assert response.content == b""
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
assert_unauthorized(api.delete(CURRENT_SESSION_PATH, headers=auth(alice)))
assert api.get("/api/v1/users/me", headers=auth(other_session)).status_code == 200
def test_logout_without_token(api: httpx.Client) -> None:
assert_unauthorized(api.delete(CURRENT_SESSION_PATH))
assert_unauthorized(
api.delete(CURRENT_SESSION_PATH, headers={"Authorization": "Bearer unknown"})
)
def test_relogin_after_logout(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
again = api.post(SESSIONS_PATH, headers=basic(alice["username"], alice["password"]))
assert again.status_code == 201
renewed = {**alice, "token": again.json()["token"]}
assert api.get("/api/v1/users/me", headers=auth(renewed)).status_code == 200
def test_password_is_not_stored_in_plaintext(make_user) -> None:
"""Проверка в БД стенда: в users лежит PHC-строка Argon2id, а не пароль"""
alice = make_user("alice")
stored = psql(
f"SELECT password_hash FROM users WHERE username = '{alice['username']}';"
)
assert stored.startswith("$argon2id$")
assert alice["password"] not in stored
+2 -2
View File
@@ -5,7 +5,7 @@ import json
import time
import httpx
from helpers import read_all_messages
from helpers import auth, read_all_messages
CLIENTS = 10
MESSAGES_PER_CLIENT = 10
@@ -21,7 +21,7 @@ async def _send_concurrently(
async def client_worker(user: dict) -> list[int]:
async with httpx.AsyncClient(
base_url=base_url, headers={"X-User-Id": user["id"]}, timeout=30
base_url=base_url, headers=auth(user), timeout=30
) as client:
await start.wait()
responses = await asyncio.gather(
+129
View File
@@ -0,0 +1,129 @@
"""
Отказы зависимостей: Valkey и PostgreSQL останавливаются через docker compose.
Тесты меняют состояние стенда (stop/start контейнеров, volumes сохраняются),
поэтому запускаются только явно: make test-failures (RUN_FAILURE_TESTS=1).
"""
import os
import time
from collections.abc import Iterator
import httpx
import pytest
from helpers import assert_error, assert_unauthorized, auth, basic, compose
pytestmark = pytest.mark.skipif(
os.environ.get("RUN_FAILURE_TESTS") != "1",
reason="останавливает контейнеры стенда: запускайте через make test-failures",
)
READY_TIMEOUT_SEC = 60
# Ответ при упавшей зависимости должен быть быстрым, а не висеть до таймаута клиента
BOUNDED_RESPONSE_SEC = 3
def wait_ready(api: httpx.Client) -> None:
deadline = time.monotonic() + READY_TIMEOUT_SEC
while time.monotonic() < deadline:
try:
if api.get("/health/ready").status_code == 200:
return
except httpx.TransportError:
pass
time.sleep(0.5)
raise AssertionError("API не стал готов после восстановления зависимости")
@pytest.fixture
def valkey_stopped(api: httpx.Client) -> Iterator[None]:
compose("stop", "valkey")
try:
yield
finally:
compose("start", "valkey")
compose("up", "-d", "--wait", "valkey")
wait_ready(api)
@pytest.fixture
def postgres_stopped(api: httpx.Client) -> Iterator[None]:
compose("stop", "postgres")
try:
yield
finally:
compose("start", "postgres")
compose("up", "-d", "--wait", "postgres")
wait_ready(api)
def test_valkey_down_cache_is_bypassed(
api: httpx.Client, make_user, make_chat, send_message, valkey_stopped
) -> None:
"""Без Valkey всё работает через PostgreSQL: вход, Bearer, запись, logout"""
alice = make_user("alice")
started = time.monotonic()
me = api.get("/api/v1/users/me", headers=auth(alice))
assert me.status_code == 200, me.text
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
chat = make_chat(alice, [alice])
send_message(alice, chat, "без кэша")
assert api.get("/health/ready").status_code == 200
assert (
api.delete("/api/v1/auth/sessions/current", headers=auth(alice)).status_code
== 204
)
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
assert_unauthorized(api.get("/api/v1/users/me"))
def test_logout_during_valkey_outage_is_not_resurrected(
api: httpx.Client, make_user
) -> None:
"""
Сессия попала в кэш, затем Valkey упал и пользователь вышел. После подъёма
Valkey (без persistence — пустой) отозванный токен не принимается.
"""
alice = make_user("alice")
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
compose("stop", "valkey")
try:
response = api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
assert response.status_code == 204
finally:
compose("start", "valkey")
compose("up", "-d", "--wait", "valkey")
wait_ready(api)
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
def test_postgres_down_returns_bounded_503_and_no_anonymous_access(
api: httpx.Client, make_user, postgres_stopped
) -> None:
alice_token_unused = {"token": "x" * 43}
started = time.monotonic()
ready = api.get("/health/ready")
assert_error(ready, 503, "unavailable")
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
# Анонимный запрос остаётся 401, неизвестный токен не принимается как доверенный
assert_unauthorized(api.get("/api/v1/users/me"))
unknown = api.get("/api/v1/users/me", headers=auth(alice_token_unused))
assert_error(unknown, 503, "unavailable")
assert "asyncpg" not in unknown.text and "postgres" not in unknown.text.lower()
body = {"username": "st_pg_down", "display_name": "x", "password": "P" * 12}
assert_error(api.post("/api/v1/users", json=body), 503, "unavailable")
login = api.post("/api/v1/auth/sessions", headers=basic("st_pg_down", "P" * 12))
assert_error(login, 503, "unavailable")
def test_session_survives_postgres_restart(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
compose("restart", "postgres")
wait_ready(api)
chats = api.get("/api/v1/chats", headers=auth(alice))
assert chats.status_code == 200, chats.text
+55
View File
@@ -0,0 +1,55 @@
"""
Истечение сессии при коротком SESSION_TTL_SECONDS.
Нужен отдельный API с SESSION_TTL_SECONDS=2: make test-expiry поднимает
api-short-ttl на :8081 поверх тех же PostgreSQL и Valkey.
"""
import os
import time
from datetime import UTC, datetime
import httpx
import pytest
from conftest import register_and_login
from helpers import assert_unauthorized, auth, basic
EXPIRY_BASE_URL = os.environ.get("EXPIRY_BASE_URL")
SHORT_TTL_SEC = 2
pytestmark = pytest.mark.skipif(
not EXPIRY_BASE_URL, reason="EXPIRY_BASE_URL не задан: запустите make test-expiry"
)
@pytest.fixture
def short_api() -> httpx.Client:
assert EXPIRY_BASE_URL is not None
with httpx.Client(base_url=EXPIRY_BASE_URL, timeout=10) as client:
yield client
def test_session_expires_after_short_ttl(short_api: httpx.Client) -> None:
alice = register_and_login(short_api, "ttl")
me = short_api.get("/api/v1/users/me", headers=auth(alice))
assert me.status_code == 200, me.text
time.sleep(SHORT_TTL_SEC + 1)
# Сессия уже лежала в кэше после первого запроса: истечь должна и там
assert_unauthorized(short_api.get("/api/v1/users/me", headers=auth(alice)))
assert_unauthorized(short_api.get("/api/v1/chats", headers=auth(alice)))
assert_unauthorized(
short_api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
)
def test_expires_at_matches_short_ttl(short_api: httpx.Client) -> None:
before = datetime.now(UTC)
alice = register_and_login(short_api, "ttl")
session = short_api.post(
"/api/v1/auth/sessions", headers=basic(alice["username"], alice["password"])
).json()
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
lifetime = (expires_at - before).total_seconds()
assert 0 < lifetime <= SHORT_TTL_SEC + 1
+16 -8
View File
@@ -4,6 +4,8 @@ import httpx
import pytest
from helpers import assert_error, auth
PASSWORD = "Valid-password-123"
MALFORMED_BODIES = [
b'{"username": "abc",',
b"not json at all",
@@ -42,14 +44,20 @@ def test_malformed_json_on_create_chat_and_message(
[
[],
"alice",
{"username": "valid_name"},
{"username": 123, "display_name": "x"},
{"username": "valid_name", "display_name": None},
{"username": "valid_name", "display_name": "x", "is_admin": True},
{"username": "Upper_Case", "display_name": "x"},
{"username": "ab", "display_name": "x"},
{"username": "valid_name", "display_name": " "},
{"username": "valid_name", "display_name": "я" * 101},
{"username": "valid_name", "password": PASSWORD},
{"username": 123, "display_name": "x", "password": PASSWORD},
{"username": "valid_name", "display_name": None, "password": PASSWORD},
{
"username": "valid_name",
"display_name": "x",
"password": PASSWORD,
"is_admin": True,
},
{"username": "Upper_Case", "display_name": "x", "password": PASSWORD},
{"username": "ab", "display_name": "x", "password": PASSWORD},
{"username": "valid_name", "display_name": " ", "password": PASSWORD},
{"username": "valid_name", "display_name": "я" * 101, "password": PASSWORD},
{"username": "valid_name", "display_name": "a\u0000b", "password": PASSWORD},
],
)
def test_invalid_user_payload(api: httpx.Client, body: object) -> None:
+20 -2
View File
@@ -42,14 +42,32 @@ def test_unicode_is_preserved(
assert alice["display_name"] == name
chat = make_chat(alice, [alice], title="Чат 🚀 中文")
assert chat["title"] == "Чат 🚀 中文"
text = "Привет, мир 👋 — «кавычки» \u0000 и 𝔘𝔫𝔦𝔠𝔬𝔡𝔢"
text = "Привет, мир 👋 — «кавычки» \t\n и 𝔘𝔫𝔦𝔠𝔬𝔡𝔢"
message = send_message(alice, chat, text)
assert message["text"] == text
page = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(alice)).json()
assert page["items"][0]["text"] == text
def test_sender_is_taken_from_x_user_id(make_user, make_chat, send_message) -> None:
def test_nul_character_is_rejected(api: httpx.Client, make_user, make_chat) -> None:
"""PostgreSQL text не хранит U+0000: отказ 400 до записи, а не 500"""
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = api.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "до\u0000после"},
headers=auth(alice),
)
assert_error(response, 400, "invalid_request")
response = api.post(
"/api/v1/chats",
json={"title": "a\u0000b", "member_ids": [alice["id"]]},
headers=auth(alice),
)
assert_error(response, 400, "invalid_request")
def test_sender_is_taken_from_session(make_user, make_chat, send_message) -> None:
alice = make_user("alice")
bob = make_user("bob")
chat = make_chat(alice, [alice, bob])
+95
View File
@@ -0,0 +1,95 @@
"""Гонка регистрации одинакового username и rollback создания чата"""
import asyncio
import json
import uuid
import httpx
from helpers import assert_error, auth, psql, unique_password, unique_username
PARALLEL_REGISTRATIONS = 20
async def _register_concurrently(base_url: str, username: str) -> list[int]:
"""Все запросы стартуют по одному сигналу, у каждого свой пароль"""
start = asyncio.Event()
async def register(client: httpx.AsyncClient) -> int:
await start.wait()
body = {
"username": username,
"display_name": "Гонка",
"password": unique_password(),
}
response = await client.post("/api/v1/users", json=body)
return response.status_code
limits = httpx.Limits(max_connections=PARALLEL_REGISTRATIONS)
async with httpx.AsyncClient(
base_url=base_url, timeout=30, limits=limits
) as client:
tasks = [
asyncio.create_task(register(client)) for _ in range(PARALLEL_REGISTRATIONS)
]
await asyncio.sleep(0)
start.set()
return list(await asyncio.gather(*tasks))
def test_same_username_race_creates_exactly_one_user(base_url: str) -> None:
username = unique_username("race")
statuses = asyncio.run(_register_concurrently(base_url, username))
stored = psql(f"SELECT count(*) FROM users WHERE username = '{username}';")
print(
"\nREGISTRATION RACE:",
json.dumps(
{
"requests": len(statuses),
"status_201": statuses.count(201),
"status_409": statuses.count(409),
"rows_in_db": int(stored),
}
),
)
assert statuses.count(201) == 1
assert statuses.count(409) == PARALLEL_REGISTRATIONS - 1
assert stored == "1"
def test_failed_chat_creation_is_rolled_back(api: httpx.Client, make_user) -> None:
"""
Строка chats вставляется первой, затем участники нарушают FK (неизвестный
пользователь в конце списка). После 400 в БД не должно остаться ни чата
с этим title, ни его участников: откатилась вся транзакция.
"""
alice = make_user("alice")
bob = make_user("bob")
title = f"rollback-{uuid.uuid4().hex}"
body = {"title": title, "member_ids": [alice["id"], bob["id"], str(uuid.uuid4())]}
response = api.post("/api/v1/chats", json=body, headers=auth(alice))
assert_error(response, 400, "invalid_request")
assert psql(f"SELECT count(*) FROM chats WHERE title = '{title}';") == "0"
orphan_members = psql(
"SELECT count(*) FROM chat_members m "
"LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL;"
)
assert orphan_members == "0"
listed = api.get("/api/v1/chats", params={"limit": 100}, headers=auth(alice))
assert all(chat["title"] != title for chat in listed.json()["items"])
def test_successful_chat_creation_commits_all_members(
api: httpx.Client, make_user
) -> None:
alice = make_user("alice")
bob = make_user("bob")
title = f"commit-{uuid.uuid4().hex}"
body = {"title": title, "member_ids": [bob["id"], alice["id"]]}
chat = api.post("/api/v1/chats", json=body, headers=auth(alice)).json()
assert chat["member_ids"] == [bob["id"], alice["id"]]
members = psql(f"SELECT count(*) FROM chat_members WHERE chat_id = '{chat['id']}';")
assert members == "2"
again = api.get(f"/api/v1/chats/{chat['id']}", headers=auth(bob)).json()
assert again == chat
+73 -18
View File
@@ -1,40 +1,95 @@
"""Дубликат username и идентификация через X-User-Id"""
"""Регистрация, дубликат username и идентификация только через Bearer"""
import uuid
import httpx
import pytest
from helpers import assert_error, unique_username
from helpers import (
assert_error,
assert_unauthorized,
auth,
public_user,
unique_password,
unique_username,
)
def test_duplicate_username_is_conflict(api: httpx.Client) -> None:
username = unique_username("dup")
first = api.post("/api/v1/users", json={"username": username, "display_name": "A"})
assert first.status_code == 201
second = api.post("/api/v1/users", json={"username": username, "display_name": "B"})
assert_error(second, 409, "conflict")
me = api.get("/api/v1/users/me", headers={"X-User-Id": first.json()["id"]})
assert me.json()["display_name"] == "A"
def test_duplicate_username_is_conflict(api: httpx.Client, make_user) -> None:
alice = make_user("dup")
body = {
"username": alice["username"],
"display_name": "B",
"password": unique_password(),
}
assert_error(api.post("/api/v1/users", json=body), 409, "conflict")
me = api.get("/api/v1/users/me", headers=auth(alice))
assert me.json()["display_name"] == alice["display_name"]
def test_registration_never_returns_password(api: httpx.Client) -> None:
password = unique_password()
body = {
"username": unique_username("pw"),
"display_name": "x",
"password": password,
}
response = api.post("/api/v1/users", json=body)
assert response.status_code == 201
assert set(response.json()) == {"id", "username", "display_name", "created_at"}
assert password not in response.text
@pytest.mark.parametrize(
"password",
[None, "", "короткий", "x" * 11, "x" * 129, 123456789012],
)
def test_invalid_password_is_rejected(api: httpx.Client, password: object) -> None:
body: dict[str, object] = {"username": unique_username("pw"), "display_name": "x"}
if password is not None:
body["password"] = password
assert_error(api.post("/api/v1/users", json=body), 400, "invalid_request")
def test_password_length_is_counted_in_code_points(api: httpx.Client) -> None:
for password in ("😀" * 12, "😀" * 128):
body = {
"username": unique_username("pw"),
"display_name": "x",
"password": password,
}
assert api.post("/api/v1/users", json=body).status_code == 201
@pytest.mark.parametrize(
"headers",
[
{},
{"X-User-Id": ""},
{"X-User-Id": "not-a-uuid"},
{"X-User-Id": str(uuid.uuid4())},
{"Authorization": ""},
{"Authorization": "Bearer"},
{"Authorization": "Bearer not-a-real-token"},
{"Authorization": "Bearer " + "x" * 5000},
{"Authorization": "Token abc"},
],
)
def test_missing_or_unknown_user_is_unauthorized(
def test_missing_or_unknown_token_is_unauthorized(
api: httpx.Client, headers: dict
) -> None:
assert_error(api.get("/api/v1/users/me", headers=headers), 401, "unauthorized")
assert_error(api.get("/api/v1/chats", headers=headers), 401, "unauthorized")
assert_unauthorized(api.get("/api/v1/users/me", headers=headers))
assert_unauthorized(api.get("/api/v1/chats", headers=headers))
def test_x_user_id_gives_no_access(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
eve = make_user("eve")
assert_unauthorized(api.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}))
me = api.get("/api/v1/users/me", headers={**auth(alice), "X-User-Id": eve["id"]})
assert me.json()["id"] == alice["id"]
unknown = {"X-User-Id": str(uuid.uuid4())}
assert_unauthorized(api.get("/api/v1/chats", headers=unknown))
def test_current_user(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
me = api.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]})
me = api.get("/api/v1/users/me", headers=auth(alice))
assert me.status_code == 200
assert me.json() == alice
assert me.json() == public_user(alice)