ЛР 2 — БВТ2301 — Ляхонов — на 5. #31
+29
-15
@@ -1,20 +1,34 @@
|
||||
.git
|
||||
.github
|
||||
.gitignore
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
secrets
|
||||
certs
|
||||
volumes
|
||||
data
|
||||
backups
|
||||
*.key
|
||||
*.pem
|
||||
*.p12
|
||||
*.pfx
|
||||
*.jks
|
||||
.env.example
|
||||
.venv
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
.Python
|
||||
*.so
|
||||
*.egg
|
||||
*.egg-info
|
||||
dist
|
||||
build
|
||||
.pytest_cache
|
||||
.mypy_cache
|
||||
.coverage
|
||||
htmlcov
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
vendor
|
||||
output
|
||||
*.md
|
||||
!README.md
|
||||
!REPORT.md
|
||||
!COURSE.md
|
||||
!CONTRIBUTING.md
|
||||
contracts/
|
||||
evidence/
|
||||
examples/
|
||||
scripts/
|
||||
tests/
|
||||
student-tests/
|
||||
.github/
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
*.sh text eol=lf
|
||||
*.py text eol=lf
|
||||
*.sql text eol=lf
|
||||
Dockerfile text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
FROM python:3.11.10-slim-bookworm
|
||||
WORKDIR /app
|
||||
# Приложение работает без прав root.
|
||||
RUN groupadd -r appuser && useradd -r -g appuser appuser
|
||||
COPY requirements.lock.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.lock.txt
|
||||
COPY src/ src/
|
||||
COPY migrations/ migrations/
|
||||
USER appuser
|
||||
HEALTHCHECK --interval=5s --timeout=5s --start-period=15s --retries=5 CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready')"
|
||||
EXPOSE 8080
|
||||
CMD ["sh", "-c", "python -m src.migrate && exec python -m uvicorn src.app:app --host 0.0.0.0 --port 8080 --timeout-graceful-shutdown 8"]
|
||||
@@ -24,3 +24,21 @@ load:
|
||||
test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
.PHONY: student-test bootstrap
|
||||
bootstrap:
|
||||
$(PYTHON) scripts/bootstrap.py
|
||||
|
||||
student-test:
|
||||
$(PYTHON) student-tests/test_lab2.py --base-url "$(BASE_URL)"
|
||||
|
||||
.PHONY: level4-test explain
|
||||
level4-test:
|
||||
$(PYTHON) student-tests/test_level4.py
|
||||
|
||||
explain:
|
||||
$(PYTHON) student-tests/explain_level4.py
|
||||
|
||||
.PHONY: research
|
||||
research:
|
||||
$(PYTHON) scripts/research.py
|
||||
|
||||
@@ -1,37 +1,275 @@
|
||||
# Отчёт — лабораторная 2
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор: Ляхонов Сергей, группа БВТ2301.
|
||||
- Целевая оценка: **5**, трек 2 — «План запроса и восстановление».
|
||||
- Ветка: `solution/BVT2301-lyakhonov`.
|
||||
- Репозиторий: https://gitea.privcloud.tech/lyakhonov/mtusi2026lab2
|
||||
- Перенос основы: `6e19f1d`; уровень 3: `6fba941`; уровень 4: `64f2a5b`; уровень 5: `358ef4a`; итоговое уточнение аутентификации: `509161e`.
|
||||
- Использование ИИ: Codex помог написать и проверить приложение, инфраструктуру, собственные тесты и исследовательские сценарии, разобрать измерения и оформить этот отчёт. Исходной основой была моя принятая лабораторная 1. Публичные проверки и обязательный контракт преподавателя не изменялись.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
### Окружение
|
||||
|
||||
Проверено на Windows, Docker Desktop 4.49.0 с Linux containers, Docker Engine 28.5.1, Compose v2.40.3-desktop.1, Python 3.13.7 на машине запуска. Компьютер: Intel Core i5-1340P, 12 ядер / 16 логических процессоров, 16 778 182 656 байт оперативной памяти (около 15,63 GiB). Все зависимости PostgreSQL и Redis запускаются из репозитория; установленные на хосте БД не нужны.
|
||||
|
||||
Runtime приложения: Python 3.11.10, образ `python:3.11.10-slim-bookworm`; PostgreSQL `postgres:16.6-alpine`; Redis `redis:7.4.1-alpine`. Основные библиотеки: FastAPI 0.115.0, Uvicorn 0.32.0, Pydantic 2.9.2, psycopg 3.2.3, psycopg-pool 3.2.4, argon2-cffi 23.1.0, redis-py 5.2.0. Все фактические зависимости образа закреплены в `requirements.lock.txt`; Dockerfile устанавливает именно этот файл. `requirements.txt` перечисляет прямые зависимости. Linux lock содержит uvloop: для Windows основной путь запуска — Docker, не установка Linux lock в системный Python.
|
||||
|
||||
| Сервис | CPU | RAM | Том | Порты и готовность |
|
||||
| ------- | ------- | ------- | ------------------- | ---------------------------------------------------- |
|
||||
| `api` | 1 CPU | 512 MiB | нет данных на диске | localhost:8080; `/health/ready` проверяет PostgreSQL |
|
||||
| `db` | 1 CPU | 512 MiB | `postgres_data` | только сеть Compose; `pg_isready` |
|
||||
| `redis` | 0,5 CPU | 128 MiB | `redis_data` | только сеть Compose; `redis-cli ping` |
|
||||
|
||||
У Redis отдельно установлен `maxmemory=64mb`, политика `allkeys-lru`. Его том не является источником сохранности: RDB/AOF отключены, потому что в нём только восстанавливаемый кэш профилей. Все сессии сохраняются в PostgreSQL.
|
||||
|
||||
### Команды запуска
|
||||
|
||||
Из корня клона, в Git Bash, PowerShell или Linux shell:
|
||||
|
||||
```sh
|
||||
python scripts/bootstrap.py
|
||||
docker compose config --quiet
|
||||
docker compose up -d --build --wait --wait-timeout 90
|
||||
python scripts/wait_ready.py
|
||||
python scripts/check_contract.py
|
||||
python tests/smoke.py
|
||||
python student-tests/test_lab2.py
|
||||
```
|
||||
|
||||
`bootstrap.py` создаёт случайный локальный пароль и URL БД в `secrets/`, не печатает значения и не перезаписывает существующие файлы. Compose передаёт их через `/run/secrets/db_password` и `/run/secrets/database_url`. Каталог исключён из Git. Повтор bootstrap безопасен. Если удалить секреты при сохранённом томе БД и сгенерировать другой пароль, нужно отдельно согласовать новый пароль с БД: автоматической смены пароля существующего PostgreSQL нет.
|
||||
|
||||
При каждом запуске API сначала выполняется `python -m src.migrate`, затем Uvicorn становится основным процессом контейнера через `exec`. Миграции применяются к пустой БД; повторный запуск не создаёт данные заново. Отдельная проверка повторного запуска:
|
||||
|
||||
```sh
|
||||
docker compose exec -T api python -m src.migrate
|
||||
```
|
||||
|
||||
Локальный `.env` необязателен. Для короткого TTL основного стенда можно создать исключённый из Git `.env` с `SESSION_TTL_SECONDS=2` и пересоздать API; перед публичным smoke и persistence вернуть не менее 300 секунд (по умолчанию 3600). Автотест expiry запускает отдельный временный API на 8082 и не меняет TTL основного стенда.
|
||||
|
||||
### Соответствие конфигурации
|
||||
|
||||
| Настройка | Реальное использование |
|
||||
| ------------------------------ | -------------------------------------------------------------------------------------------------------- |
|
||||
| `SESSION_TTL_SECONDS` | Compose передаёт в API, по умолчанию 3600; абсолютное expiry рассчитывается PostgreSQL |
|
||||
| `DATABASE_URL_FILE` | Чтение секрета URL через `src/config.py` |
|
||||
| `DATABASE_URL` | Альтернативное прямое значение для самостоятельного запуска; секрет предпочтительнее |
|
||||
| `CACHE_URL` / `CACHE_URL_FILE` | В Compose задан внутренний `redis://redis:6379/0`; конфигурация также поддерживает файл |
|
||||
| `PROFILE_CACHE_TTL_SECONDS` | TTL профиля, в Compose 60 секунд |
|
||||
| `SESSION_STORE` из примера | Выбор альтернативного backend не реализован: источник сессий всегда PostgreSQL |
|
||||
| `APP_HOST`, `APP_PORT` | Поддерживаются самостоятельной точкой входа `src/main.py`; Docker запускает Uvicorn явно на 0.0.0.0:8080 |
|
||||
| `APP_ENV` | Информационная подсказка заготовки, на поведение реализации не влияет |
|
||||
|
||||
### Проверки и остановка
|
||||
|
||||
На Windows (включая Git Bash с Windows Python):
|
||||
|
||||
```sh
|
||||
python tests/resilience.py --mode persistence --action-script scripts/restart.cmd
|
||||
```
|
||||
|
||||
На Linux:
|
||||
|
||||
```sh
|
||||
chmod +x scripts/restart.sh
|
||||
python tests/resilience.py --mode persistence --action-script scripts/restart.sh
|
||||
```
|
||||
|
||||
Windows Python не исполняет Unix shebang как Linux, поэтому добавлен эквивалентный `.cmd`. Оба hook перезапускают **db, redis и api**, не удаляют volumes, не перезаполняют БД и не меняют тестовые данные.
|
||||
|
||||
Если установлен Make, эквивалентные цели:
|
||||
|
||||
```sh
|
||||
make check PYTHON=python
|
||||
make test PYTHON=python
|
||||
make student-test PYTHON=python
|
||||
make test-persistence PYTHON=python ACTION_SCRIPT=scripts/restart.cmd
|
||||
# Linux: ACTION_SCRIPT=scripts/restart.sh
|
||||
make level4-test PYTHON=python
|
||||
make explain PYTHON=python
|
||||
make research PYTHON=python
|
||||
```
|
||||
|
||||
В сохранённых результатах выполнялись непосредственно Python-команды, которые вызываются этими целями; это явно отмечено, а не заявлено как запуск отсутствующего на Windows Make.
|
||||
|
||||
```sh
|
||||
# Дополнительные проверки уровня 4 — явно останавливают зависимости учебного стенда:
|
||||
python student-tests/test_level4.py
|
||||
python student-tests/explain_level4.py
|
||||
|
||||
# Исследование и восстановление:
|
||||
python scripts/research.py
|
||||
|
||||
# Безопасная остановка без удаления данных:
|
||||
docker compose down
|
||||
|
||||
# Повторный запуск:
|
||||
docker compose up -d --wait --wait-timeout 90
|
||||
|
||||
# Только для намеренного удаления данных именно этого учебного Compose-проекта:
|
||||
docker compose down --volumes
|
||||
```
|
||||
|
||||
Последняя команда приведена для оператора и в проверках не выполнялась. Исследовательские БД и отдельные тома восстановления создаются с уникальными именами и не удаляются автоматически; их имена записаны в evidence. Повтор исследования расходует дополнительное место. Архивы находятся в `backups/` вне Git. Перед запуском уровня 4 порт 8082 должен быть свободен.
|
||||
|
||||
Для полной валидации OpenAPI:
|
||||
|
||||
```sh
|
||||
python -m pip install -r requirements-dev.txt
|
||||
python scripts/validate_openapi.py
|
||||
```
|
||||
|
||||
На стенде валидатор запускался в отдельном одноразовом контейнере, не меняющем рабочий образ приложения.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```text
|
||||
Клиент → FastAPI/Uvicorn → PostgreSQL (пользователи, чаты, участники, сообщения, сессии)
|
||||
→ Redis (необязательный кэш публичных профилей)
|
||||
```
|
||||
|
||||
Из lab1 перенесены маршруты и модели REST API, обработка ошибок с X-Request-Id, проверки членства, формат курсора, ограничение одновременных запросов и основа контейнера. Словари заменены PostgreSQL, собственные тесты адаптированы. Старые тесты с X-User-Id и сборщик token bucket удалены после переноса полезных сценариев в test_lab2.py. Эксперимент деградации lab1 не заявляется доказательством lab2.
|
||||
|
||||
### Схема, ограничения и транзакции
|
||||
|
||||
`migrations/001_initial.sql` содержит users, chats, chat_members, messages, sessions. У каждого объекта UUID PK; username уникален. Участники имеют PK `(chat_id,user_id)`. Сообщение связано FK с чатом и пользователем, а составной FK `(chat_id,sender_id)` гарантирует членство отправителя. Ограничения длины и непустоты дополняют HTTP-валидацию.
|
||||
|
||||
Создание чата и всех участников выполняется одной транзакцией. Неизвестный участник нарушает FK, вся транзакция откатывается, клиент получает 400. Гонка регистрации разрешается уникальным ограничением PostgreSQL: один 201, остальные 409. Параметры передаются отдельно от SQL; пользовательский текст не подставляется в строку запроса.
|
||||
|
||||
Пул: от 1 до 10 соединений, не более 32 ожидающих; timeout получения 3 секунды, connect_timeout 3 секунды, statement_timeout 3 секунды, lock_timeout 2 секунды. Ошибка критичного хранилища возвращает 503 без SQL/stack trace. Синхронные маршруты исполняются в пуле потоков; KDF входа вынесен из цикла событий.
|
||||
|
||||
`schema_migrations` хранит применённые версии. Миграции выполняются в транзакции под advisory lock, поэтому повторный и параллельный запуск не применяет их дважды. Предварительное описание схемы и границ — `infra/schema.md`.
|
||||
|
||||
### Аутентификация и сохранность
|
||||
|
||||
Регистрация требует password длиной 12–128 Unicode code points. Пароль хешируется Argon2id (time_cost=2, memory_cost=19 456 KiB, parallelism=1), соль создаёт библиотека. Хеш не входит в публичный User. Basic используется только для POST `/api/v1/auth/sessions`; пароль разбирается по первому двоеточию, поэтому двоеточия в пароле сохраняются. Неверные учётные данные дают одинаковый 401 с WWW-Authenticate Basic. Для неизвестного пользователя также выполняется проверка KDF на служебном хеше.
|
||||
|
||||
Токен создаётся `secrets.token_urlsafe(32)`: 32 случайных байта, 256 бит энтропии. В БД хранится только SHA-256 токена, UUID пользователя и абсолютное expires_at. SHA-256 используется для случайного токена, **не для пароля**. Каждая Bearer-сессия проверяется в PostgreSQL с текущим временем БД. Logout удаляет строку, повторный запрос даёт 401 с WWW-Authenticate Bearer. Basic на бизнес-маршруте не принимается. X-User-Id игнорируется и не меняет владельца Bearer-сессии.
|
||||
|
||||
После успешного контекста psycopg выполняется COMMIT, и только после его завершения возвращается созданный объект. На проверенном PostgreSQL `fsync=on`, `synchronous_commit=on`, `full_page_writes=on`. Это даёт обычные гарантии PostgreSQL в рамках доступного устойчивого тома, но не резервирует диск и host. Перезапуск API не продлевает expires_at. Сессии, ещё действующие после рестарта, читают прежние данные.
|
||||
|
||||
### Кэш профиля
|
||||
|
||||
Redis работает по cache-aside. Ключ `profile:v1:<user_id>`, TTL 60 секунд, значение — только публичный User. Промах читает PostgreSQL и заполняет Redis; ошибка Redis обходит кэш. Профиль в обязательном API нельзя редактировать или удалить, поэтому кэшируемые данные неизменяемы. Если такие операции появятся, потребуется явная инвалидация. Очистка/рестарт Redis не теряет сессии: они в PostgreSQL. История сообщений и решения об авторизации не кэшируются, поэтому кэш не нарушает read-after-write и немедленный logout.
|
||||
|
||||
Readiness зависит от PostgreSQL и не зависит от Redis. Liveness проверяет только процесс. Дополнительная диагностика GET `/stats` описана в `infra/extensions.md`; обязательный contracts/ не изменялся.
|
||||
|
||||
### Курсор и индекс
|
||||
|
||||
Курсор — URL-safe Base64 JSON с `scope`, `resource_id`, `created_at`, `id`. Он проверяется на структуру, UUID, время, правильный ресурс и существование маркера. Для списка чатов ресурс — пользователь, для истории — чат. Курсор не подписан и не заменяет авторизацию.
|
||||
|
||||
Время PostgreSQL возвращается в UTC с микросекундами. SQL выбирает записи после пары `(created_at,id)` и запрашивает `limit+1`, чтобы узнать, есть ли следующая страница:
|
||||
|
||||
```sql
|
||||
SELECT * FROM messages
|
||||
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4;
|
||||
```
|
||||
|
||||
Индекс: `(chat_id,created_at,id)`. В приложении нет OFFSET и сортировки всей истории в Python. Для одной страницы достаточно индексного диапазона. Между несколькими запросами нет snapshot: конкурентная вставка с ключом до курсора не попадёт в уже продолжаемый обход. UUID разрешает одинаковое время, но не задаёт очерёдность отправки при равном timestamp.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Критерий | Команда/проверка | Наблюдение | Доказательство |
|
||||
| ---------------------------------------------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
|
||||
| Структура и обязательный контракт | `python scripts/check_contract.py` | PASS; публичные tests/ и contracts/ не менялись | `evidence/final_checks.json` |
|
||||
| Полная OpenAPI 3.1 / JSON Schema | `python scripts/validate_openapi.py` | PASS в одноразовом контейнере | `evidence/openapi_validation.txt` |
|
||||
| Публичный сценарий lab2 | `python tests/smoke.py` | PASS: регистрация, Basic/Bearer, чат, сообщения, курсор, доступ, logout | `evidence/level3.json`, `evidence/final_checks.json` |
|
||||
| PostgreSQL, FK, уникальность и атомарный чат | миграция + test_level4.py | 1×201, 7×409; неизвестный участник не оставляет чат | `migrations/001_initial.sql`, `evidence/level4.json` |
|
||||
| Полный рестарт, прежний токен и данные | `python tests/resilience.py --mode persistence --action-script scripts/restart.cmd` | PASS; изменились StartedAt db/redis/api, том PostgreSQL прежний | `evidence/final_checks.json` |
|
||||
| Повтор миграций | `docker compose exec -T api python -m src.migrate` | одна версия 001_initial.sql, повтор без изменений | `evidence/level3.json` |
|
||||
| Воспроизводимая сборка | чистый локальный clone, новые секреты и тома, отдельный порт 8083 | сборка + smoke + собственные тесты PASS | `evidence/clean_clone.json` |
|
||||
| Конкурентная запись и отрицательные сценарии | `python student-tests/test_lab2.py` | 100 уникальных сообщений от 10 клиентов, полный обход, чужой/битый cursor → 400 | `evidence/final_checks.json` |
|
||||
| Непривилегированный процесс и SIGTERM | docker stop --timeout 10, проверка exit code и закрытого порта | appuser; exit 0; остановка за 0.729 с | `evidence/lifecycle.json` |
|
||||
| Реальный Redis, TTL и обход при отказе | `python student-tests/test_level4.py` | профиль присутствует, TTL 59 с; при остановке Redis авторизованный запрос проходит | `evidence/level4.json` |
|
||||
| Пул, параметры, timeout и отказ БД | тот же тест | live=200; ready и защищённый запрос=503; после запуска БД прежняя сессия работает | `src/storage.py`, `evidence/level4.json` |
|
||||
| Expiry, logout, неверный пароль | отдельный API TTL=2 + публичный smoke | после 2,2 с — 401; logout — 401; неверный пароль — 401 | `evidence/level4.json`, `evidence/final_checks.json` |
|
||||
| Индекс истории на ≥10 000 | `python student-tests/explain_level4.py` | messages_history_idx; Execution Time 0,080 мс | `evidence/explain_10000.json` |
|
||||
| Трек 2: ≥100 000, ≥2 индекса, стоимость записи | `python scripts/research.py` | 100 000 сообщений, 13 чатов, 3 индекса, SQL-планы и latency | `evidence/research.json` |
|
||||
| Трек 2: backup → новое хранилище → сверка | та же команда | 100 000 сообщений совпали по количеству и общей контрольной сумме; 39 выборочных строк равны | `evidence/recovery.json` |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Имена контейнеров, UUID и названия томов в evidence относятся к конкретному запуску; они не нужны для запуска нового клона. Токены, пароли и бинарные дампы в Git не включены. Чистый clone проверялся на коммите 509161e; последующее заполнение отчёта не изменяет runtime.
|
||||
|
||||
## Эксперименты и отказы
|
||||
## Исследование уровня 5, трек 2
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
### Гипотеза и методика
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
Гипотеза: индекс только по chat_id вынужден читать и сортировать много строк большого чата; составной B-tree `(chat_id,created_at,id)` позволяет сразу найти диапазон после курсора. Покрывающий индекс с INCLUDE может уменьшить heap fetches, но увеличит память и стоимость записи; его выигрыш нужно измерить.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
Исследование выполняется в отдельной БД с уникальным именем в том же PostgreSQL, не в таблицах API. Создано **ровно 100 000 сообщений**: чаты на 70 000, 20 000, 9 000 сообщений и десять чатов по 100. Текст — 128 символов x и порядковый номер. Время задаётся детерминированно с шагом 1 микросекунда; UUID случайные. Все три варианта проверяются на одном наборе данных и с теми же лимитами контейнера.
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Сравниваются:
|
||||
|
||||
1. `chat_only`: B-tree `(chat_id)`.
|
||||
2. `composite`: B-tree `(chat_id,created_at,id)`.
|
||||
3. `covering`: B-tree `(chat_id,created_at,id) INCLUDE(sender_id,text)`.
|
||||
|
||||
Для размеров 70 000, 20 000, 9 000 и 100 проверяются границы на 10%, 50% и 90% истории. В каждом случае три прогревочных запроса и 100 измеряемых запросов, всего **3 600 успешных чтений**, ошибок 0. Конкуренция 1, closed-loop без заданного arrival rate. Один SQL-запрос возвращает до 51 строки. Latency измеряется клиентом psycopg в контейнере API, включает выполнение SQL и передачу результата; отдельный EXPLAIN фиксирует серверное время и buffers. Это **SQL-throughput, не HTTP RPS и не предел производительности сервера**.
|
||||
|
||||
Для каждого индекса дополнительно три транзакции вставки по 1 000 сообщений с COMMIT. После каждого измерения строки write_probe удаляются вне измеряемого интервала. Составной FK и PK одинаковы во всех вариантах. Записаны время построения и размер индекса. Перед измерениями выполняется VACUUM ANALYZE. OFFSET используется только для подготовки позиции эксперимента, не в измеряемом запросе и не в API.
|
||||
|
||||
### Результаты
|
||||
|
||||
Большой чат (70 000 сообщений), граница на 90% истории; latency в мс, throughput — успешные SQL-запросы/с. Стоимость записи — медиана трёх транзакций по 1 000 строк с COMMIT:
|
||||
|
||||
| Индекс | p50, мс | p95, мс | p99, мс | SQL-запросов/с | Размер, MiB | Запись, строк/с |
|
||||
| --------- | ------- | ------- | ------- | -------------- | ----------- | --------------- |
|
||||
| chat_only | 6.727 | 8.431 | 9.563 | 144 | 0.70 | 19896 |
|
||||
| composite | 0.377 | 0.587 | 0.657 | 2453 | 5.95 | 19496 |
|
||||
| covering | 0.552 | 1.057 | 1.521 | 1060 | 23.44 | 18088 |
|
||||
|
||||
При chat_only планировщик выбрал Seq Scan + top-N Sort: 93 001 строка отфильтрована, 2 811 shared hit blocks. Составной индекс дал Index Scan без Sort: 51 строка и 6 shared hit blocks. Покрывающий дал Index Only Scan, Heap Fetches=0 и 5 shared hit blocks. Уменьшение heap-доступов само по себе не гарантировало меньшую клиентскую задержку.
|
||||
|
||||
Для составного индекса p95 снизился примерно в 14,4 раза относительно chat_only. Покрывающий индекс занял около 23,44 MiB против 5,95 MiB составного (примерно в 3,94 раза больше); стоимость записи оказалась выше, а latency в выбранном случае хуже. Поэтому в приложении оставлен обычный составной индекс. Это локальный вывод для данного профиля, не универсальный запрет INCLUDE.
|
||||
|
||||
Полный исследовательский запуск вместе с созданием набора и сбором метрик занял 14.29 с. По пяти выборкам Docker stats PostgreSQL наблюдалось до 98,84% CPU (при лимите 1 CPU) и до 88,77 MiB памяти из 512 MiB. Это метрика памяти контейнера Docker, не точный RSS отдельного backend. Выборки примерно раз в 3 секунды: короткие пики могли быть пропущены. Для каждого из 36 сочетаний в JSON сохранены duration, успешные запросы/с, ошибки, p50/p95/p99 и полный EXPLAIN (ANALYZE, BUFFERS).
|
||||
|
||||
### Backup и восстановление
|
||||
|
||||
После исследования создан логический архив `pg_dump -Fc` всей исследовательской БД. Затем запущен **новый контейнер PostgreSQL с новым пустым именованным томом**, теми же CPU/RAM и версией образа. Архив скопирован и восстановлен через `pg_restore --exit-on-error --no-owner`. Это не повторное чтение исходной БД и не восстановление в старый том.
|
||||
|
||||
- Размер архива: 2991247 байт.
|
||||
- Создание дампа и копирование на хост: 1.304 с.
|
||||
- Сам `pg_restore`: 0.814 с.
|
||||
- Запуск нового хранилища, ожидание готовности, копирование архива и restore: 3.166 с.
|
||||
- Количества: 1 пользователь, 13 чатов, 13 членств, 100 000 сообщений, 0 сессий в отдельной исследовательской БД.
|
||||
- Совпали количества всех таблиц, MD5-отпечаток упорядоченного содержимого **всех сообщений** и 39 выбранных строк (начало, середина, конец каждого чата).
|
||||
- Потеря сообщений относительно снимка дампа: 0.
|
||||
|
||||
MD5 здесь — техническая сверка синтетических данных, не защита от намеренной подмены. Сохранность действующих сессий отдельно проверена публичным persistence на основной БД, в которой сессии реально есть.
|
||||
|
||||
После сверки восстановленный контейнер остановлен, новый том оставлен для демонстрации. Его имя и имя исходной исследовательской БД записаны в `evidence/recovery.json` и `evidence/research.json`. Архив находится в `backups/`, исключённом из Git. Для повтора не нужен мой архив: `scripts/research.py` создаёт новый набор, архив и новый том.
|
||||
|
||||
## Отказы и границы решения
|
||||
|
||||
| Воздействие | Ожидание | Наблюдение | Восстановление / потеря |
|
||||
| ---------------------------------- | ------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------- |
|
||||
| Рестарт API, PostgreSQL, Redis | прежний токен и подтверждённые данные сохраняются | публичный persistence PASS, StartedAt всех трёх изменился | данные не потеряны, expiry не продлён |
|
||||
| Остановка Redis | чтение профиля через PostgreSQL | запрос с Bearer прошёл, анонимный получил 401 | кэш заполняется заново; данные и сессии сохранены |
|
||||
| Остановка PostgreSQL | ограниченный 503; live остаётся 200 | два ошибочных запроса заняли суммарно 6,05 с | после старта БД прежняя сессия работает |
|
||||
| Expiry при TTL=2 | токен становится недействительным | после 2,2 с получен 401 | нужен новый вход |
|
||||
| Logout | немедленный отзыв | прежний токен получает 401 | нужен новый вход |
|
||||
| Ошибка участника при создании чата | полный rollback | количество чатов не увеличилось | неполный чат не создан |
|
||||
| SIGTERM | завершение ≤10 с, новые запросы не принимаются | exit 0, 0.729 с, порт перестал отвечать | данные в PostgreSQL сохранены |
|
||||
| Восстановление логического дампа | совпадение снимка в новом хранилище | полная сверка PASS | 0 потерь относительно снимка, restore 0.814 с |
|
||||
|
||||
Время 8,617 с в level4.json включает команду остановки Redis и запрос, поэтому это не задержка одного fallback-запроса. Для отказа БД зафиксировано суммарное время двух запросов, а не production SLA восстановления. Публичный тест ждёт готовности в своём бюджете; более строгий RTO после полной аварии host не исследован.
|
||||
|
||||
Один Docker-host и один PostgreSQL не обеспечивают HA. Именованный том выдерживает проверенный restart контейнера, но не утрату диска. `pg_dump` даёт согласованный снимок: новые записи после этого снимка в архив не входят. Без архивирования WAL и PITR возможная потеря при аварии равна изменениям после последнего успешного backup; нулевая потеря в эксперименте относится только к замороженному исследовательскому набору. Архив на том же физическом компьютере не защищает от потери этого компьютера.
|
||||
|
||||
Ограничения измерений: один компьютер, тёплый кэш, один клиентский поток, три индекса запускались последовательно без рандомизации; 100 повторов каждого чтения, три повтора записи. Набор сообщений синтетический, нет длительного смешанного read/write и сетевой задержки удалённого стенда. Результаты не являются оценкой максимальных HTTP RPS. Для повторного исследования следует менять порядок вариантов и увеличивать длительность/число независимых прогонов.
|
||||
|
||||
Учебные упрощения: HTTP только на localhost, нет TLS и ограничения попыток входа; роль PostgreSQL, созданная стандартным образом, имеет административные права для миграций и исследовательских БД. Для production нужны отдельные роли приложения/миграций/backup, мониторинг, управление секретами, ротация и внешнее резервное хранилище. Истёкшие строки сессий не очищаются фоновым процессом, но никогда не принимаются как действующие. Список чатов делает дополнительные запросы участников по числу чатов страницы; индекс истории решает именно чтение сообщений.
|
||||
|
||||
В Gitea эта работа проверена локально. Workflow заготовки в `.github/` сохранён, автоматический запуск Gitea Actions не заявляется. Оценка подтверждается воспроизводимыми сценариями и защитой, а не наличием зелёного CI.
|
||||
|
||||
## Источники
|
||||
|
||||
- [Документация PostgreSQL 16: составные индексы](https://www.postgresql.org/docs/16/indexes-multicolumn.html).
|
||||
- [Документация PostgreSQL 16: EXPLAIN](https://www.postgresql.org/docs/16/using-explain.html).
|
||||
- [pg_dump](https://www.postgresql.org/docs/16/app-pgdump.html), [pg_restore](https://www.postgresql.org/docs/16/app-pgrestore.html).
|
||||
- [psycopg: connection pools и границы транзакций](https://www.psycopg.org/psycopg3/docs/advanced/pool.html).
|
||||
- [Redis: cache-aside](https://redis.io/docs/latest/develop/use-cases/cache-aside/).
|
||||
- [argon2-cffi](https://argon2-cffi.readthedocs.io/en/stable/howto.html).
|
||||
- [RFC 7617: Basic Authentication](https://www.rfc-editor.org/rfc/rfc7617).
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
name: lyakhonov-lab2
|
||||
services:
|
||||
db:
|
||||
image: postgres:16.6-alpine
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
|
||||
secrets: [db_password]
|
||||
volumes: [postgres_data:/var/lib/postgresql/data]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, "pg_isready -U messenger -d messenger"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
cpus: 1
|
||||
mem_limit: 512m
|
||||
redis:
|
||||
image: redis:7.4.1-alpine
|
||||
command: [redis-server, --maxmemory, 64mb, --maxmemory-policy, allkeys-lru, --save, "", --appendonly, "no"]
|
||||
volumes: [redis_data:/data]
|
||||
healthcheck:
|
||||
test: [CMD, redis-cli, ping]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
cpus: 0.5
|
||||
mem_limit: 128m
|
||||
api:
|
||||
build: .
|
||||
image: lyakhonov-messenger:lab2
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL: redis://redis:6379/0
|
||||
PROFILE_CACHE_TTL_SECONDS: 60
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
secrets: [database_url]
|
||||
ports: ["127.0.0.1:8080:8080"]
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
cpus: 1
|
||||
mem_limit: 512m
|
||||
stop_grace_period: 10s
|
||||
secrets:
|
||||
db_password:
|
||||
file: ./secrets/db_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
volumes:
|
||||
redis_data:
|
||||
postgres_data:
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"source_commit": "509161edcabe7f99a67d9a3fbd3c35ae077d9cd4",
|
||||
"clone": "C:\\Users\\User\\AppData\\Local\\Temp\\lyakhonov-lab2-clean-p6og92bu",
|
||||
"project": "lyakhonov-lab2-clean",
|
||||
"fresh_secrets": true,
|
||||
"fresh_volumes": true,
|
||||
"port": 8083,
|
||||
"build_and_checks_seconds": 30.772888699983014,
|
||||
"checks": [
|
||||
{
|
||||
"command": "python scripts/check_contract.py",
|
||||
"output": "PASS: offline skeleton structure, local refs and Python syntax; application NOT tested."
|
||||
},
|
||||
{
|
||||
"command": "python tests/smoke.py --base-url http://localhost:8083",
|
||||
"output": "PASS: lab2 public API scenario; infrastructure and grading evidence remain separate."
|
||||
},
|
||||
{
|
||||
"command": "python student-tests/test_lab2.py --base-url http://localhost:8083",
|
||||
"output": "PASS: strict validation, access, cursor binding, 100 messages / 10 clients, complete pagination"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"date": "2026-10-09",
|
||||
"author": "Ляхонов Сергей",
|
||||
"group": "БВТ2301",
|
||||
"grade": 5,
|
||||
"track": 2,
|
||||
"tested_runtime_commit": "509161edcabe7f99a67d9a3fbd3c35ae077d9cd4",
|
||||
"research_worker_sha256": "a87d5a83a9046521a101ad6b46911502ecb5bf5b16fef72adfa4eccaec16b09d",
|
||||
"cpu": "Intel Core i5-1340P",
|
||||
"cores": 12,
|
||||
"logical_processors": 16,
|
||||
"host_ram_bytes": 16778182656,
|
||||
"docker": "28.5.1",
|
||||
"docker_desktop": "4.49.0",
|
||||
"compose": "2.40.3-desktop.1",
|
||||
"postgres_durability": {
|
||||
"fsync": "on",
|
||||
"synchronous_commit": "on",
|
||||
"full_page_writes": "on"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"rows": 10000,
|
||||
"query": "SELECT * FROM messages WHERE chat_id=%s AND (created_at,id)>(%s,%s) ORDER BY created_at,id LIMIT 51",
|
||||
"plan": {
|
||||
"Plan": {
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 12.94,
|
||||
"Plan Rows": 51,
|
||||
"Plan Width": 87,
|
||||
"Actual Startup Time": 0.017,
|
||||
"Actual Total Time": 0.025,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Shared Hit Blocks": 5,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Plans": [
|
||||
{
|
||||
"Node Type": "Index Scan",
|
||||
"Parent Relationship": "Outer",
|
||||
"Parallel Aware": false,
|
||||
"Async Capable": false,
|
||||
"Scan Direction": "Forward",
|
||||
"Index Name": "messages_history_idx",
|
||||
"Relation Name": "messages",
|
||||
"Alias": "messages",
|
||||
"Startup Cost": 0.29,
|
||||
"Total Cost": 536.25,
|
||||
"Plan Rows": 2160,
|
||||
"Plan Width": 87,
|
||||
"Actual Startup Time": 0.016,
|
||||
"Actual Total Time": 0.021,
|
||||
"Actual Rows": 51,
|
||||
"Actual Loops": 1,
|
||||
"Index Cond": "((chat_id = '44cfe328-842b-43a5-900b-ff083cb13f7f'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.008001+00'::timestamp with time zone, '10e68164-4b26-406f-a3a4-f0395ca68f52'::uuid)))",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Shared Hit Blocks": 5,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"Planning": {
|
||||
"Shared Hit Blocks": 108,
|
||||
"Shared Read Blocks": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Written Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Written Blocks": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
},
|
||||
"Planning Time": 0.516,
|
||||
"Triggers": [],
|
||||
"Execution Time": 0.08
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"before": [
|
||||
{
|
||||
"name": "/lyakhonov-lab2-api-1",
|
||||
"started_at": "2026-10-09T11:23:47.014525416Z",
|
||||
"user": "appuser",
|
||||
"image_id": "sha256:282821b02aeddc63acf7f264fe014cf4add9c798cbb687370d7ee21262567ff3",
|
||||
"mounts": []
|
||||
},
|
||||
{
|
||||
"name": "/lyakhonov-lab2-db-1",
|
||||
"started_at": "2026-10-09T11:19:19.752878335Z",
|
||||
"user": "",
|
||||
"image_id": "sha256:1d04b9ba1d4996401f2552b51beda8187f175c0645c091e4781134fc9c9a3eef",
|
||||
"mounts": [
|
||||
{
|
||||
"name": "lyakhonov-lab2_postgres_data",
|
||||
"destination": "/var/lib/postgresql/data"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "/lyakhonov-lab2-redis-1",
|
||||
"started_at": "2026-10-09T11:19:19.807227368Z",
|
||||
"user": "",
|
||||
"image_id": "sha256:c1e88455c85225310bbea54816e9c3f4b5295815e6dbf80c34d40afc6df28275",
|
||||
"mounts": [
|
||||
{
|
||||
"name": "lyakhonov-lab2_redis_data",
|
||||
"destination": "/data"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"commands": [
|
||||
{
|
||||
"command": "python scripts/check_contract.py",
|
||||
"output": "PASS: offline skeleton structure, local refs and Python syntax; application NOT tested."
|
||||
},
|
||||
{
|
||||
"command": "python tests/smoke.py",
|
||||
"output": "PASS: lab2 public API scenario; infrastructure and grading evidence remain separate."
|
||||
},
|
||||
{
|
||||
"command": "python student-tests/test_lab2.py",
|
||||
"output": "PASS: strict validation, access, cursor binding, 100 messages / 10 clients, complete pagination"
|
||||
},
|
||||
{
|
||||
"command": "python tests/resilience.py --mode persistence --action-script scripts/restart.cmd",
|
||||
"output": "Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.\nPASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence."
|
||||
}
|
||||
],
|
||||
"after": [
|
||||
{
|
||||
"name": "/lyakhonov-lab2-api-1",
|
||||
"started_at": "2026-10-09T11:25:00.737823332Z",
|
||||
"user": "appuser",
|
||||
"image_id": "sha256:282821b02aeddc63acf7f264fe014cf4add9c798cbb687370d7ee21262567ff3",
|
||||
"mounts": []
|
||||
},
|
||||
{
|
||||
"name": "/lyakhonov-lab2-db-1",
|
||||
"started_at": "2026-10-09T11:25:00.409548723Z",
|
||||
"user": "",
|
||||
"image_id": "sha256:1d04b9ba1d4996401f2552b51beda8187f175c0645c091e4781134fc9c9a3eef",
|
||||
"mounts": [
|
||||
{
|
||||
"name": "lyakhonov-lab2_postgres_data",
|
||||
"destination": "/var/lib/postgresql/data"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "/lyakhonov-lab2-redis-1",
|
||||
"started_at": "2026-10-09T11:25:00.307001994Z",
|
||||
"user": "",
|
||||
"image_id": "sha256:c1e88455c85225310bbea54816e9c3f4b5295815e6dbf80c34d40afc6df28275",
|
||||
"mounts": [
|
||||
{
|
||||
"name": "lyakhonov-lab2_redis_data",
|
||||
"destination": "/data"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"commands": [
|
||||
{
|
||||
"command": "python scripts/check_contract.py",
|
||||
"output": "PASS: offline skeleton structure, local refs and Python syntax; application NOT tested."
|
||||
},
|
||||
{
|
||||
"command": "python tests/smoke.py",
|
||||
"output": "PASS: lab2 public API scenario; infrastructure and grading evidence remain separate."
|
||||
},
|
||||
{
|
||||
"command": "python student-tests/test_lab2.py",
|
||||
"output": "PASS: strict validation, access, cursor binding, 100 messages / 10 clients, complete pagination"
|
||||
},
|
||||
{
|
||||
"command": "python tests/resilience.py --mode persistence --action-script scripts/restart.cmd",
|
||||
"output": "Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.\nPASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence."
|
||||
}
|
||||
],
|
||||
"before": [
|
||||
{
|
||||
"Name": "/lyakhonov-lab2-api-1",
|
||||
"RestartCount": 0,
|
||||
"started_at": "2026-10-09T11:15:56.676676381Z",
|
||||
"image": "lyakhonov-messenger:lab2"
|
||||
},
|
||||
{
|
||||
"Name": "/lyakhonov-lab2-db-1",
|
||||
"RestartCount": 0,
|
||||
"started_at": "2026-10-09T11:15:56.130807797Z",
|
||||
"image": "postgres:16.6-alpine"
|
||||
}
|
||||
],
|
||||
"after": [
|
||||
{
|
||||
"Name": "/lyakhonov-lab2-api-1",
|
||||
"RestartCount": 0,
|
||||
"started_at": "2026-10-09T11:16:33.449311224Z",
|
||||
"image": "lyakhonov-messenger:lab2"
|
||||
},
|
||||
{
|
||||
"Name": "/lyakhonov-lab2-db-1",
|
||||
"RestartCount": 0,
|
||||
"started_at": "2026-10-09T11:16:33.058063917Z",
|
||||
"image": "postgres:16.6-alpine"
|
||||
}
|
||||
],
|
||||
"migration_repeat": "PASS: repeated migration completed without applying migration twice",
|
||||
"migration_versions": "001_initial.sql"
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"registration_codes": [
|
||||
201,
|
||||
409,
|
||||
409,
|
||||
409,
|
||||
409,
|
||||
409,
|
||||
409,
|
||||
409
|
||||
],
|
||||
"rollback": "PASS",
|
||||
"profile_cache_ttl_seconds": 59,
|
||||
"redis_fallback": "PASS",
|
||||
"redis_stop_and_request_seconds": 8.617,
|
||||
"db_failure": "503, live=200, recovery with same session",
|
||||
"two_db_error_requests_seconds": 6.05,
|
||||
"expiry_seconds": 2,
|
||||
"expiry": "401",
|
||||
"logout": "401",
|
||||
"passed": true
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
python tests/smoke.py
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"stop_seconds": 0.7288908000045922,
|
||||
"exit_code": 0,
|
||||
"new_requests_refused": true,
|
||||
"container_user": "uid=999(appuser) gid=999(appuser) groups=999(appuser)",
|
||||
"graceful_timeout_seconds": 8
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
Команда во временном контейнере: python scripts/validate_openapi.py
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
@@ -0,0 +1,387 @@
|
||||
{
|
||||
"source_database": "lab2_research_eaaceacf5e",
|
||||
"restore_container": "lyakhonov-lab2-restore-e73b5fd47f",
|
||||
"new_volume": "lyakhonov_lab2_restore_e73b5fd47f",
|
||||
"archive_file": "backups/research_fb31d8e86c.dump",
|
||||
"archive_bytes": 2991247,
|
||||
"backup_seconds": 1.3044416999910027,
|
||||
"restore_seconds": 0.8138425000070129,
|
||||
"provision_and_restore_seconds": 3.1661540000059176,
|
||||
"checks": {
|
||||
"counts": {
|
||||
"equal": true,
|
||||
"value": {
|
||||
"users": 1,
|
||||
"chats": 13,
|
||||
"members": 13,
|
||||
"messages": 100000,
|
||||
"sessions": 0
|
||||
}
|
||||
},
|
||||
"all_message_fingerprint": {
|
||||
"equal": true,
|
||||
"value": {
|
||||
"count": 100000,
|
||||
"digest": "1e61a199fa8e8c94d2041f6f64394fd9"
|
||||
}
|
||||
},
|
||||
"selected_messages": {
|
||||
"equal": true,
|
||||
"value": [
|
||||
{
|
||||
"id": "11a3b161-4e2b-4aaf-a4cd-12e9d57edf52",
|
||||
"chat_id": "0895b1b6-473e-41be-8ea1-bf81a723fadc",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "99be4627-2bc0-45ac-b505-402cd8a12693",
|
||||
"chat_id": "0895b1b6-473e-41be-8ea1-bf81a723fadc",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx100",
|
||||
"created_at": "2026-01-01T00:00:00.0001+00:00",
|
||||
"n": 100,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "9d3e23a8-69f2-42c8-bb78-ae97911aa7d5",
|
||||
"chat_id": "0895b1b6-473e-41be-8ea1-bf81a723fadc",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx50",
|
||||
"created_at": "2026-01-01T00:00:00.00005+00:00",
|
||||
"n": 50,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "04348821-e05f-46fe-b5b1-e2e11bd7645e",
|
||||
"chat_id": "11981599-4a94-4007-bd54-201527ddad8a",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "6e87c8e2-6b8e-46f1-9718-9f4c8e1c40c8",
|
||||
"chat_id": "11981599-4a94-4007-bd54-201527ddad8a",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx100",
|
||||
"created_at": "2026-01-01T00:00:00.0001+00:00",
|
||||
"n": 100,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "e2b6195d-91e1-44bd-b213-91c5db1032b2",
|
||||
"chat_id": "11981599-4a94-4007-bd54-201527ddad8a",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx50",
|
||||
"created_at": "2026-01-01T00:00:00.00005+00:00",
|
||||
"n": 50,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "4d2ca458-a710-4764-bf18-149495dca55e",
|
||||
"chat_id": "1605ec06-2fcb-4281-84ff-a3da632735a3",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx50",
|
||||
"created_at": "2026-01-01T00:00:00.00005+00:00",
|
||||
"n": 50,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "7474c834-f59e-4fed-923a-33f0dc1d4cda",
|
||||
"chat_id": "1605ec06-2fcb-4281-84ff-a3da632735a3",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx100",
|
||||
"created_at": "2026-01-01T00:00:00.0001+00:00",
|
||||
"n": 100,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "96a0e5d8-1361-4377-9c20-ebb719a78905",
|
||||
"chat_id": "1605ec06-2fcb-4281-84ff-a3da632735a3",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "12ebdc82-c91d-48f9-92c2-88b1a0bd1c58",
|
||||
"chat_id": "3c405a3b-6a05-44db-b95b-bf169588af8e",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "98dc824d-2eab-439c-bb32-2dab06e1a0a9",
|
||||
"chat_id": "3c405a3b-6a05-44db-b95b-bf169588af8e",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx50",
|
||||
"created_at": "2026-01-01T00:00:00.00005+00:00",
|
||||
"n": 50,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "d46c72a5-ad44-43e7-82e2-4a4bbd7f516e",
|
||||
"chat_id": "3c405a3b-6a05-44db-b95b-bf169588af8e",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx100",
|
||||
"created_at": "2026-01-01T00:00:00.0001+00:00",
|
||||
"n": 100,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "537239af-3ae3-4c63-8ca7-15ad966e462d",
|
||||
"chat_id": "435b684f-92c0-4429-b392-f610a4eb2c1d",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx100",
|
||||
"created_at": "2026-01-01T00:00:00.0001+00:00",
|
||||
"n": 100,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "755c5e7d-a3c7-4232-b96b-4cb19954385a",
|
||||
"chat_id": "435b684f-92c0-4429-b392-f610a4eb2c1d",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "efa11b0f-c8b1-4201-8b70-ae4f05e850ea",
|
||||
"chat_id": "435b684f-92c0-4429-b392-f610a4eb2c1d",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx50",
|
||||
"created_at": "2026-01-01T00:00:00.00005+00:00",
|
||||
"n": 50,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "0318ba50-7912-4975-9960-17a2710d753c",
|
||||
"chat_id": "43c99015-4e1d-46c4-8a29-369516c20985",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx20000",
|
||||
"created_at": "2026-01-01T00:00:00.02+00:00",
|
||||
"n": 20000,
|
||||
"total": 20000
|
||||
},
|
||||
{
|
||||
"id": "4f3a53b1-59c5-49db-808f-d7237d18ffbc",
|
||||
"chat_id": "43c99015-4e1d-46c4-8a29-369516c20985",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx10000",
|
||||
"created_at": "2026-01-01T00:00:00.01+00:00",
|
||||
"n": 10000,
|
||||
"total": 20000
|
||||
},
|
||||
{
|
||||
"id": "575e59bf-fef2-49c4-8274-67d4c26de49a",
|
||||
"chat_id": "43c99015-4e1d-46c4-8a29-369516c20985",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 20000
|
||||
},
|
||||
{
|
||||
"id": "2417d232-3b20-492e-bcb9-28570446ac1f",
|
||||
"chat_id": "44747c11-d90a-436f-9ec0-a01325912444",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "9ecb8a28-faa5-4210-bfdf-8f2ed309a519",
|
||||
"chat_id": "44747c11-d90a-436f-9ec0-a01325912444",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx100",
|
||||
"created_at": "2026-01-01T00:00:00.0001+00:00",
|
||||
"n": 100,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "dcada8e5-4af5-454c-953b-0556c7c73267",
|
||||
"chat_id": "44747c11-d90a-436f-9ec0-a01325912444",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx50",
|
||||
"created_at": "2026-01-01T00:00:00.00005+00:00",
|
||||
"n": 50,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "1a6103ab-bb23-4cba-b0dd-bd7c133c63b8",
|
||||
"chat_id": "474412a5-c1a5-48f3-a2cf-044f2cfe4f12",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx50",
|
||||
"created_at": "2026-01-01T00:00:00.00005+00:00",
|
||||
"n": 50,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "9e226f91-9251-4948-8969-c3d7a829d619",
|
||||
"chat_id": "474412a5-c1a5-48f3-a2cf-044f2cfe4f12",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx100",
|
||||
"created_at": "2026-01-01T00:00:00.0001+00:00",
|
||||
"n": 100,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "c298525a-c3df-46a6-9069-4f74f069618c",
|
||||
"chat_id": "474412a5-c1a5-48f3-a2cf-044f2cfe4f12",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "088bcd80-4186-464a-9cbd-524e5ccf9704",
|
||||
"chat_id": "91ff03f5-fc06-4689-99ea-5ac69a0c7bd6",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx50",
|
||||
"created_at": "2026-01-01T00:00:00.00005+00:00",
|
||||
"n": 50,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "69508dfb-9024-4064-8fbc-223f5acf1b11",
|
||||
"chat_id": "91ff03f5-fc06-4689-99ea-5ac69a0c7bd6",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "a5ad8ac2-9687-45b6-9ee0-5bcb80e44a74",
|
||||
"chat_id": "91ff03f5-fc06-4689-99ea-5ac69a0c7bd6",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx100",
|
||||
"created_at": "2026-01-01T00:00:00.0001+00:00",
|
||||
"n": 100,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "122852f1-d8c3-46fe-ac29-14e6cfc3272e",
|
||||
"chat_id": "bdd3477c-67e1-4dc1-ad42-3e2551db823b",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx50",
|
||||
"created_at": "2026-01-01T00:00:00.00005+00:00",
|
||||
"n": 50,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "4447d2e4-6e92-43a3-9b08-573f879f1e99",
|
||||
"chat_id": "bdd3477c-67e1-4dc1-ad42-3e2551db823b",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "47e6b656-df1d-4930-a049-4879c02614ed",
|
||||
"chat_id": "bdd3477c-67e1-4dc1-ad42-3e2551db823b",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx100",
|
||||
"created_at": "2026-01-01T00:00:00.0001+00:00",
|
||||
"n": 100,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "642c52a5-b8a1-4ba0-afb9-4fcea0dd65e8",
|
||||
"chat_id": "c9f802fd-c998-4180-9ca3-f02977eb8301",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx70000",
|
||||
"created_at": "2026-01-01T00:00:00.07+00:00",
|
||||
"n": 70000,
|
||||
"total": 70000
|
||||
},
|
||||
{
|
||||
"id": "c92030c9-7b9d-496b-8bea-e57930fc84bb",
|
||||
"chat_id": "c9f802fd-c998-4180-9ca3-f02977eb8301",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 70000
|
||||
},
|
||||
{
|
||||
"id": "dcb218a5-0bc6-4467-9927-e214a027e99f",
|
||||
"chat_id": "c9f802fd-c998-4180-9ca3-f02977eb8301",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx35000",
|
||||
"created_at": "2026-01-01T00:00:00.035+00:00",
|
||||
"n": 35000,
|
||||
"total": 70000
|
||||
},
|
||||
{
|
||||
"id": "2f174ebf-4835-402f-a957-8630ad4d73cc",
|
||||
"chat_id": "ee38cff2-be26-4a0d-97b7-9d4102096aba",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 9000
|
||||
},
|
||||
{
|
||||
"id": "3ae8e884-e4e0-491a-8566-4ba3736ba420",
|
||||
"chat_id": "ee38cff2-be26-4a0d-97b7-9d4102096aba",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9000",
|
||||
"created_at": "2026-01-01T00:00:00.009+00:00",
|
||||
"n": 9000,
|
||||
"total": 9000
|
||||
},
|
||||
{
|
||||
"id": "c48eb0d5-ef04-4689-a289-280bc6fb6ada",
|
||||
"chat_id": "ee38cff2-be26-4a0d-97b7-9d4102096aba",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx4500",
|
||||
"created_at": "2026-01-01T00:00:00.0045+00:00",
|
||||
"n": 4500,
|
||||
"total": 9000
|
||||
},
|
||||
{
|
||||
"id": "af1bef3d-5153-42dd-b1cf-8396160e0e7e",
|
||||
"chat_id": "fcdaf99f-f7b3-4168-944e-a215d7c03e17",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx50",
|
||||
"created_at": "2026-01-01T00:00:00.00005+00:00",
|
||||
"n": 50,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "b237f587-49fc-4b04-883c-e246450992e4",
|
||||
"chat_id": "fcdaf99f-f7b3-4168-944e-a215d7c03e17",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1",
|
||||
"created_at": "2026-01-01T00:00:00.000001+00:00",
|
||||
"n": 1,
|
||||
"total": 100
|
||||
},
|
||||
{
|
||||
"id": "f2dc8d6b-e8dd-455e-90d2-b144d10bd6c8",
|
||||
"chat_id": "fcdaf99f-f7b3-4168-944e-a215d7c03e17",
|
||||
"sender_id": "dd797d22-94f6-4dd0-b9e2-64ceb3d6d5d1",
|
||||
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx100",
|
||||
"created_at": "2026-01-01T00:00:00.0001+00:00",
|
||||
"n": 100,
|
||||
"total": 100
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"snapshot_message_loss": 0,
|
||||
"passed": true
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
# Дополнительная диагностика
|
||||
|
||||
`GET /stats` — необязательное расширение API: числа users/chats/messages и счётчики profile_cache.hits/misses/errors/ttl_seconds. Счётчики кэша живут в процессе и сбрасываются при его перезапуске. Ответ не раскрывает профили, тексты, хеши паролей или токены. Публичный обязательный контракт не изменён. Ограничитель количества запросов сохранён из lab1: не более 100 одновременно обслуживаемых запросов в одном процессе; переполнение — 503 unavailable. Это не распределённый rate limiter.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Схема PostgreSQL
|
||||
|
||||
Пользователь имеет уникальное имя и хеш Argon2id. Чат и строки участников создаются в одной транзакции; ошибка любого FK откатывает весь чат. Сообщение связано с чатом, отправителем и членством составным FK. Удаление данных через API отсутствует.
|
||||
|
||||
Сессия хранит SHA-256 случайного 256-битного токена и абсолютное время окончания; SHA-256 применяется к токену, а пароль обрабатывается Argon2id. Logout удаляет строку. Внешний API не возвращает хеши.
|
||||
|
||||
Индекс messages_history_idx (chat_id, created_at, id) обслуживает WHERE chat_id = ? AND (created_at,id) > (?,?) ORDER BY created_at,id LIMIT ?. Запрашиваются limit+1 строка, чтобы определить наличие следующей страницы. PostgreSQL timestamptz сохраняет микросекунды; UUID разрешает совпадения времени. Между страницами нет общего snapshot.
|
||||
|
||||
Миграции выполняются под advisory lock в транзакции; schema_migrations предотвращает повторное применение. Пул ограничен десятью подключениями и 32 ожидающими; получение подключения — 3 секунды, statement_timeout — 3 секунды, lock_timeout — 2 секунды.
|
||||
|
||||
## Кэш уровня 4
|
||||
Redis хранит только публичные неизменяемые профили пользователей, без хешей паролей и токенов. Ключ profile:v1:UUID, TTL 60 секунд, maxmemory 64 MiB, allkeys-lru. Пользовательские изменения и удаление не входят в API: инвалидация при обновлении не требуется; при будущем расширении она обязательна. Cache-aside: промах или ошибка возвращают чтение PostgreSQL; кэш заполняется после чтения подтверждённой строки. После рестарта кэш пуст и восстанавливается по запросам. Persistence кэша отключён намеренно; сессии находятся в PostgreSQL. Redis не критичен для readiness, PostgreSQL критичен. Кэш не участвует в проверке Bearer: каждая сессия проверяется в PostgreSQL, поэтому logout немедленно действует даже при недоступном Redis.
|
||||
@@ -0,0 +1,33 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name varchar(100) NOT NULL CHECK (length(btrim(display_name)) > 0),
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title varchar(100) NOT NULL CHECK (length(btrim(title)) > 0),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
sender_id uuid NOT NULL REFERENCES users(id),
|
||||
text varchar(4000) NOT NULL CHECK (length(btrim(text)) > 0),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
|
||||
CREATE TABLE sessions (
|
||||
token_hash char(64) PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
|
||||
@@ -0,0 +1,25 @@
|
||||
annotated-types==0.8.0
|
||||
anyio==4.15.1
|
||||
argon2-cffi==23.1.0
|
||||
argon2-cffi-bindings==26.1.0
|
||||
cffi==2.1.1
|
||||
click==8.5.0
|
||||
fastapi==0.115.0
|
||||
h11==0.16.0
|
||||
httptools==0.8.0
|
||||
idna==3.20
|
||||
psycopg==3.2.3
|
||||
psycopg-binary==3.2.3
|
||||
psycopg-pool==3.2.4
|
||||
pycparser==3.1
|
||||
pydantic==2.9.2
|
||||
pydantic_core==2.23.4
|
||||
python-dotenv==1.2.4
|
||||
PyYAML==6.0.3
|
||||
starlette==0.38.6
|
||||
typing_extensions==4.16.0
|
||||
uvicorn==0.32.0
|
||||
uvloop==0.23.0
|
||||
watchfiles==1.3.0
|
||||
websockets==17.2
|
||||
redis==5.2.0
|
||||
@@ -0,0 +1,7 @@
|
||||
fastapi==0.115.0
|
||||
uvicorn[standard]==0.32.0
|
||||
pydantic==2.9.2
|
||||
psycopg[binary]==3.2.3
|
||||
psycopg-pool==3.2.4
|
||||
argon2-cffi==23.1.0
|
||||
redis==5.2.0
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Создать локальные секреты, не перезаписывая существующие."""
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
folder = root / 'secrets'
|
||||
folder.mkdir(exist_ok=True)
|
||||
password_file = folder / 'db_password'
|
||||
if not password_file.exists():
|
||||
password_file.write_text(secrets.token_hex(24), encoding='utf-8')
|
||||
url_file = folder / 'database_url'
|
||||
if not url_file.exists():
|
||||
password = password_file.read_text(encoding='utf-8').strip()
|
||||
url_file.write_text(f'postgresql://messenger:{password}@db:5432/messenger', encoding='utf-8')
|
||||
print('Локальные секреты готовы; значения не выводятся.')
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Повторяемое исследование SQL, сбор CPU/RAM, backup и восстановление в новый том."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
os.chdir(ROOT)
|
||||
|
||||
|
||||
def command(args):
|
||||
result=subprocess.run(args,capture_output=True,text=True,encoding='utf-8',errors='replace',check=True)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return command(['docker','compose',*args])
|
||||
|
||||
|
||||
def database_query(service,database,query):
|
||||
output=compose('exec','-T',service,'psql','-U','messenger','-d',database,'-Atc',query)
|
||||
return json.loads(output)
|
||||
|
||||
|
||||
def main():
|
||||
evidence=ROOT/'evidence'
|
||||
evidence.mkdir(exist_ok=True)
|
||||
stats=[]
|
||||
stop=threading.Event()
|
||||
def collect():
|
||||
while not stop.is_set():
|
||||
raw=command(['docker','stats','--no-stream','--format','{{json .}}',compose('ps','-q','db')])
|
||||
stats.append({'elapsed_seconds':round(time.monotonic()-started,3),'docker':json.loads(raw)})
|
||||
stop.wait(1)
|
||||
started=time.monotonic()
|
||||
collector=threading.Thread(target=collect)
|
||||
collector.start()
|
||||
try:
|
||||
source=(ROOT/'student-tests/research_worker.py').read_text(encoding='utf-8')
|
||||
proc=subprocess.run(['docker','compose','exec','-T','api','python','-'],input=source,capture_output=True,text=True,encoding='utf-8',check=True)
|
||||
result=json.loads(proc.stdout)
|
||||
finally:
|
||||
stop.set()
|
||||
collector.join()
|
||||
result['total_research_seconds']=time.monotonic()-started
|
||||
result['resources']=stats
|
||||
result['postgres_version']=compose('exec','-T','db','postgres','--version')
|
||||
(evidence/'research.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
||||
print('SQL-исследование завершено: 100 000 сообщений, три индекса.')
|
||||
# Дамп содержит синтетические данные; бинарный архив остаётся вне Git.
|
||||
folder=ROOT/'backups'
|
||||
folder.mkdir(exist_ok=True)
|
||||
archive='research_'+uuid.uuid4().hex[:10]+'.dump'
|
||||
before=time.perf_counter()
|
||||
compose('exec','-T','db','pg_dump','-U','messenger','-d',result['database'],'-Fc','-f','/tmp/'+archive)
|
||||
db_id=compose('ps','-q','db')
|
||||
command(['docker','cp',db_id+':/tmp/'+archive,str(folder/archive)])
|
||||
backup_seconds=time.perf_counter()-before
|
||||
# Каждый запуск получает новый отдельный том; существующие тома не удаляются.
|
||||
restore_volume='lyakhonov_lab2_restore_'+uuid.uuid4().hex[:10]
|
||||
restore_name=restore_volume.replace('_','-')
|
||||
command(['docker','volume','create',restore_volume])
|
||||
before=time.perf_counter()
|
||||
password_file=str(ROOT/'secrets/db_password')
|
||||
command(['docker','run','-d','--name',restore_name,'--network','lyakhonov-lab2_default',
|
||||
'--cpus','1','--memory','512m','-e','POSTGRES_USER=messenger','-e','POSTGRES_DB=messenger',
|
||||
'-e','POSTGRES_PASSWORD_FILE=/run/secrets/db_password','--mount','type=bind,src='+password_file+',dst=/run/secrets/db_password,readonly',
|
||||
'-v',restore_volume+':/var/lib/postgresql/data','postgres:16.6-alpine'])
|
||||
deadline=time.monotonic()+60
|
||||
while True:
|
||||
ready=subprocess.run(['docker','exec',restore_name,'pg_isready','-h','127.0.0.1','-U','messenger','-d','messenger'],capture_output=True)
|
||||
if ready.returncode==0:
|
||||
break
|
||||
if time.monotonic()>deadline:
|
||||
raise RuntimeError('новое хранилище не готово')
|
||||
time.sleep(0.5)
|
||||
command(['docker','cp',str(folder/archive),restore_name+':/tmp/'+archive])
|
||||
restore_start=time.perf_counter()
|
||||
command(['docker','exec',restore_name,'pg_restore','-U','messenger','-d','messenger','--exit-on-error','--no-owner','/tmp/'+archive])
|
||||
restore_seconds=time.perf_counter()-restore_start
|
||||
provision_restore_seconds=time.perf_counter()-before
|
||||
counts="SELECT json_build_object('users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),'members',(SELECT count(*) FROM chat_members),'messages',(SELECT count(*) FROM messages),'sessions',(SELECT count(*) FROM sessions))"
|
||||
fingerprint="SELECT json_build_object('count',count(*),'digest',md5(string_agg(md5(id::text || chat_id::text || sender_id::text || text || created_at::text),'' ORDER BY id))) FROM messages"
|
||||
samples="SELECT json_agg(t ORDER BY chat_id,id) FROM (SELECT * FROM (SELECT id,chat_id,sender_id,text,created_at,row_number() OVER(PARTITION BY chat_id ORDER BY created_at,id) AS n,count(*) OVER(PARTITION BY chat_id) AS total FROM messages) s WHERE n=1 OR n=total OR n=total/2) t"
|
||||
def restored(query):
|
||||
return json.loads(command(['docker','exec',restore_name,'psql','-U','messenger','-d','messenger','-Atc',query]))
|
||||
checks={}
|
||||
for label,query in [('counts',counts),('all_message_fingerprint',fingerprint),('selected_messages',samples)]:
|
||||
original=database_query('db',result['database'],query)
|
||||
recovered=restored(query)
|
||||
assert original==recovered, 'расхождение после восстановления: '+label
|
||||
checks[label]={'equal':True,'value':original}
|
||||
recovery={'source_database':result['database'],'restore_container':restore_name,'new_volume':restore_volume,
|
||||
'archive_file':'backups/'+archive,'archive_bytes':(folder/archive).stat().st_size,
|
||||
'backup_seconds':backup_seconds,'restore_seconds':restore_seconds,'provision_and_restore_seconds':provision_restore_seconds,
|
||||
'checks':checks,'snapshot_message_loss':0,'passed':True}
|
||||
(evidence/'recovery.json').write_text(json.dumps(recovery,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
||||
print('PASS: backup восстановлен в новый том; количество, все сообщения и выборка совпали.')
|
||||
# Контейнер исследования останавливается; том сохраняется для защиты.
|
||||
command(['docker','stop',restore_name])
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose restart db redis api
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
# Перезапускаем все процессы, не удаляя тома и не изменяя данные.
|
||||
docker compose restart db redis api
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Дождаться HTTP readiness перед запуском проверок."""
|
||||
import argparse
|
||||
import time
|
||||
import urllib.request
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url',default='http://localhost:8080')
|
||||
args=parser.parse_args()
|
||||
for _ in range(120):
|
||||
try:
|
||||
with urllib.request.urlopen(args.base_url+'/health/ready',timeout=2) as response:
|
||||
if response.status==200:
|
||||
print('PASS: API ready')
|
||||
break
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise SystemExit('API readiness timeout')
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
import psycopg
|
||||
from psycopg_pool import PoolTimeout
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import ValidationError as PydanticValidationError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from src.models import ErrorResponse
|
||||
from src.routes import chats, health, messages, users
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
"""Создать и настроить приложение FastAPI."""
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
await run_in_threadpool(storage.pool.open, wait=True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await run_in_threadpool(storage.pool.close)
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger Lab2", version="1.2.0", lifespan=lifespan)
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
@app.exception_handler(psycopg.errors.QueryCanceled)
|
||||
@app.exception_handler(PoolTimeout)
|
||||
async def dependency_error(request, exc):
|
||||
return JSONResponse(status_code=503, content=ErrorResponse(error={
|
||||
"code": "unavailable", "message": "хранилище временно недоступно",
|
||||
"request_id": request.state.request_id}).model_dump(),
|
||||
headers={"X-Request-Id": request.state.request_id})
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next):
|
||||
"""Middleware: добавляет X-Request-Id и реализует ограничение очереди запросов (трек 2)."""
|
||||
request_id = request.headers.get("X-Request-Id", "") or str(uuid.uuid4())
|
||||
request.state.request_id = request_id
|
||||
|
||||
# Трек 2: ограничение очереди запросов — возвращаем 503 при переполнении
|
||||
if not storage.acquire_request_slot():
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "unavailable",
|
||||
"message": "сервер перегружен, попробуйте позже",
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
try:
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
finally:
|
||||
storage.release_request_slot()
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
"""Обработчик HTTPException: возвращает ошибку в формате контракта {"error": ...}."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
if isinstance(exc.detail, dict) and "error" in exc.detail:
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=exc.detail,
|
||||
headers={"X-Request-Id": request_id, **(exc.headers or {})},
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "internal_error",
|
||||
"message": str(exc.detail),
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def request_validation_handler(request: Request, exc: RequestValidationError):
|
||||
"""Перехватываем ошибки валидации запроса (422 -> 400 по контракту)."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
errors = exc.errors()
|
||||
messages = []
|
||||
for err in errors:
|
||||
loc = ".".join(str(x) for x in err.get("loc", []))
|
||||
messages.append(f"{loc}: {err.get('msg', 'invalid')}")
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "invalid_request",
|
||||
"message": "; ".join(messages),
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
@app.exception_handler(PydanticValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: PydanticValidationError):
|
||||
"""Перехватываем ошибки Pydantic (422 -> 400 по контракту)."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
errors = exc.errors()
|
||||
messages = []
|
||||
for err in errors:
|
||||
loc = ".".join(str(x) for x in err.get("loc", []))
|
||||
messages.append(f"{loc}: {err.get('msg', 'invalid')}")
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "invalid_request",
|
||||
"message": "; ".join(messages),
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def generic_exception_handler(request: Request, exc: Exception):
|
||||
"""Обработчик непредвиденных исключений: скрываем детали, возвращаем 500."""
|
||||
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content=ErrorResponse(
|
||||
error={
|
||||
"code": "internal_error",
|
||||
"message": "внутренняя ошибка сервера",
|
||||
"request_id": request_id,
|
||||
}
|
||||
).model_dump(),
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
# Подключаем роуты
|
||||
app.include_router(health.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
|
||||
return app
|
||||
|
||||
|
||||
# Экземпляр приложения для uvicorn
|
||||
app = create_app()
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Необязательный кэш неизменяемого публичного профиля; ошибки обходятся через БД."""
|
||||
import logging
|
||||
import os
|
||||
from redis import Redis, RedisError
|
||||
from pydantic import ValidationError
|
||||
from src.config import setting
|
||||
from src.models import User
|
||||
|
||||
|
||||
class ProfileCache:
|
||||
def __init__(self):
|
||||
url = setting('CACHE_URL')
|
||||
self.client = Redis.from_url(url, decode_responses=True, socket_connect_timeout=0.2,
|
||||
socket_timeout=0.2, max_connections=16) if url else None
|
||||
self.ttl = int(os.getenv('PROFILE_CACHE_TTL_SECONDS','60'))
|
||||
self.hits = self.misses = self.errors = 0
|
||||
|
||||
def get(self, user_id):
|
||||
if not self.client:
|
||||
return None
|
||||
try:
|
||||
value = self.client.get('profile:v1:'+user_id)
|
||||
if value:
|
||||
user=User.model_validate_json(value)
|
||||
if user.id != user_id:
|
||||
raise ValueError('неверный ключ кэша')
|
||||
self.hits += 1
|
||||
return user
|
||||
self.misses += 1
|
||||
except (RedisError, ValidationError, ValueError):
|
||||
self.errors += 1
|
||||
logging.getLogger(__name__).warning('Кэш профиля недоступен; чтение из PostgreSQL')
|
||||
return None
|
||||
|
||||
def put(self, user):
|
||||
if self.client:
|
||||
try:
|
||||
self.client.set('profile:v1:'+user.id,user.model_dump_json(),ex=self.ttl)
|
||||
except RedisError:
|
||||
self.errors += 1
|
||||
|
||||
|
||||
profile_cache = ProfileCache()
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Настройки окружения и чтение секретов из файлов."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def setting(name, default=None):
|
||||
path = os.getenv(name + '_FILE')
|
||||
if path:
|
||||
return Path(path).read_text(encoding='utf-8').strip()
|
||||
return os.getenv(name, default)
|
||||
@@ -0,0 +1,9 @@
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
|
||||
if __name__ == "__main__":
|
||||
"""Точка входа: запуск Uvicorn с параметрами из переменных окружения."""
|
||||
host = os.getenv("APP_HOST", "0.0.0.0")
|
||||
port = int(os.getenv("APP_PORT", "8080"))
|
||||
uvicorn.run("src.app:app", host=host, port=port, log_level="info")
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Версионируемые миграции: одна транзакция, блокировка от параллельного запуска."""
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
from src.config import setting
|
||||
|
||||
|
||||
def main():
|
||||
with psycopg.connect(setting('DATABASE_URL'), connect_timeout=5) as conn:
|
||||
conn.execute('SELECT pg_advisory_xact_lock(2301002)')
|
||||
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)')
|
||||
for path in sorted(Path('/app/migrations' if Path('/app/migrations').exists() else 'migrations').glob('*.sql')):
|
||||
if not conn.execute('SELECT 1 FROM schema_migrations WHERE version=%s', (path.name,)).fetchone():
|
||||
conn.execute(path.read_text(encoding='utf-8'))
|
||||
conn.execute('INSERT INTO schema_migrations VALUES (%s)', (path.name,))
|
||||
print('Применена миграция:', path.name)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
import uuid
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
"""Возвращает текущее время в формате RFC 3339 UTC с суффиксом Z."""
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
class ErrorDetail(BaseModel):
|
||||
"""Детали ошибки API."""
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
"""Стандартный ответ об ошибке."""
|
||||
error: ErrorDetail
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
"""Ответ проверки работоспособности."""
|
||||
status: str = "ok"
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
"""Модель пользователя."""
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
"""Данные для создания пользователя."""
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
password: str = Field(..., min_length=12, max_length=128)
|
||||
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(..., min_length=1, max_length=100)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def display_name_not_whitespace_only(cls, v: str) -> str:
|
||||
"""Запрещаем display_name, состоящий только из пробельных символов."""
|
||||
if v.strip() == "":
|
||||
raise ValueError("display_name не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
"""Модель чата."""
|
||||
id: str
|
||||
title: str
|
||||
member_ids: list[str]
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
"""Данные для создания чата."""
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(..., min_length=1, max_length=100)
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def valid_members(cls, values):
|
||||
"""Проверить UUID и привести их к единому представлению."""
|
||||
return [str(uuid.UUID(value)) for value in values]
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def title_not_whitespace_only(cls, v: str) -> str:
|
||||
"""Запрещаем title, состоящий только из пробельных символов."""
|
||||
if v.strip() == "":
|
||||
raise ValueError("title не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
"""Модель сообщения."""
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
"""Данные для отправки сообщения."""
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
text: str = Field(..., min_length=1, max_length=4000)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def text_not_whitespace_only(cls, v: str) -> str:
|
||||
"""Запрещаем текст, состоящий только из пробельных символов."""
|
||||
if v.strip() == "":
|
||||
raise ValueError("текст не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
"""Страница списка чатов с курсорной пагинацией."""
|
||||
items: list[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
"""Страница истории сообщений с курсорной пагинацией."""
|
||||
items: list[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
@@ -0,0 +1,79 @@
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from src.models import Chat, ChatPage, CreateChat
|
||||
from src.routes.common import get_request_id, make_error, require_user
|
||||
from src.storage import LimitExceeded, ValidationError, storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/chats", response_model=Chat, status_code=201)
|
||||
def create_chat(
|
||||
request: Request,
|
||||
body: CreateChat,
|
||||
x_user_id: str = Depends(require_user),
|
||||
):
|
||||
"""Создать чат. Создатель обязательно должен входить в member_ids."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
try:
|
||||
chat = storage.create_chat(body.title, body.member_ids, x_user_id)
|
||||
return chat
|
||||
except ValidationError as e:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", str(e), request_id).model_dump(),
|
||||
)
|
||||
except LimitExceeded as e:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=make_error("rate_limited", str(e), request_id).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(
|
||||
request: Request,
|
||||
x_user_id: str = Depends(require_user),
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
):
|
||||
"""Список чатов текущего пользователя с курсорной пагинацией."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", "limit должен быть от 1 до 100", request_id).model_dump(),
|
||||
)
|
||||
|
||||
try:
|
||||
items, next_cursor = storage.list_chats_for_user(x_user_id, cursor, limit)
|
||||
return ChatPage(items=items, next_cursor=next_cursor)
|
||||
except ValidationError as e:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", str(e), request_id).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
def get_chat(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
x_user_id: str = Depends(require_user),
|
||||
):
|
||||
"""Получить чат по id. Доступен только участникам чата (чужой — 404)."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
if not chat or x_user_id not in chat.member_ids:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
)
|
||||
|
||||
return chat
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Общие ошибки и проверка Bearer-сессии; X-User-Id не используется."""
|
||||
from fastapi import HTTPException, Request
|
||||
from src.models import ErrorResponse
|
||||
from src.storage import storage
|
||||
|
||||
|
||||
def make_error(code, message, request_id):
|
||||
return ErrorResponse(error={'code': code, 'message': message, 'request_id': request_id})
|
||||
|
||||
|
||||
def get_request_id(request):
|
||||
return request.state.request_id
|
||||
|
||||
|
||||
def unauthorized(request, basic=False):
|
||||
challenge = 'Basic realm="messenger", charset="UTF-8"' if basic else 'Bearer realm="messenger"'
|
||||
raise HTTPException(401, detail=make_error('unauthorized', 'неверные учётные данные', get_request_id(request)).model_dump(), headers={'WWW-Authenticate': challenge})
|
||||
|
||||
|
||||
def require_user(request: Request):
|
||||
authorization = request.headers.get('Authorization', '')
|
||||
parts = authorization.split()
|
||||
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
||||
unauthorized(request)
|
||||
user_id = storage.session_user(parts[1])
|
||||
if not user_id:
|
||||
unauthorized(request)
|
||||
request.state.token = parts[1]
|
||||
return user_id
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Жизнь процесса и готовность критичного хранилища проверяются отдельно."""
|
||||
from fastapi import APIRouter
|
||||
from src.models import Health
|
||||
from src.storage import storage
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get('/health/live')
|
||||
def liveness():
|
||||
return Health()
|
||||
|
||||
|
||||
@router.get('/health/ready')
|
||||
def readiness():
|
||||
storage.ready()
|
||||
return Health()
|
||||
|
||||
|
||||
@router.get('/stats')
|
||||
def stats():
|
||||
return storage.get_stats()
|
||||
@@ -0,0 +1,72 @@
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from src.models import CreateMessage, Message, MessagePage
|
||||
from src.routes.common import get_request_id, make_error, require_user
|
||||
from src.storage import LimitExceeded, ValidationError, storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
def create_message(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
body: CreateMessage,
|
||||
x_user_id: str = Depends(require_user),
|
||||
):
|
||||
"""Отправить сообщение в чат. Отправитель определяется по X-User-Id."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
if not chat or x_user_id not in chat.member_ids:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
)
|
||||
|
||||
try:
|
||||
msg = storage.create_message(chat_id_str, x_user_id, body.text)
|
||||
return msg
|
||||
except LimitExceeded as e:
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail=make_error("rate_limited", str(e), request_id).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
x_user_id: str = Depends(require_user),
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
):
|
||||
"""История сообщений чата с курсорной пагинацией. Доступно только участникам."""
|
||||
request_id = get_request_id(request)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = storage.get_chat(chat_id_str)
|
||||
if not chat or x_user_id not in chat.member_ids:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=make_error("not_found", "чат не найден", request_id).model_dump(),
|
||||
)
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", "limit должен быть от 1 до 100", request_id).model_dump(),
|
||||
)
|
||||
|
||||
try:
|
||||
items, next_cursor = storage.list_messages(chat_id_str, cursor, limit)
|
||||
return MessagePage(items=items, next_cursor=next_cursor)
|
||||
except ValidationError as e:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=make_error("invalid_request", str(e), request_id).model_dump(),
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Регистрация, вход, текущий пользователь и отзыв сессии."""
|
||||
import base64
|
||||
import binascii
|
||||
from fastapi import APIRouter, Request, Response, HTTPException
|
||||
from src.models import CreateUser, User
|
||||
from src.routes.common import get_request_id, make_error, require_user, unauthorized
|
||||
from src.storage import ConflictError, storage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post('/api/v1/users', response_model=User, status_code=201)
|
||||
def register_user(request: Request, body: CreateUser):
|
||||
try:
|
||||
return storage.create_user(body.username,body.display_name,body.password)
|
||||
except ConflictError as exc:
|
||||
raise HTTPException(409,detail=make_error('conflict',str(exc),get_request_id(request)).model_dump())
|
||||
|
||||
|
||||
@router.post('/api/v1/auth/sessions', status_code=201)
|
||||
async def login(request: Request):
|
||||
if await request.body():
|
||||
raise HTTPException(400, detail=make_error('invalid_request','тело запроса не допускается',get_request_id(request)).model_dump())
|
||||
parts = request.headers.get('Authorization','').split()
|
||||
try:
|
||||
if len(parts) != 2 or parts[0].lower() != 'basic':
|
||||
unauthorized(request, basic=True)
|
||||
username,password = base64.b64decode(parts[1],validate=True).decode('utf-8').split(':',1)
|
||||
username.encode('ascii')
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
unauthorized(request,basic=True)
|
||||
# Вычисление KDF и синхронные запросы выполняются вне цикла событий.
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
result = await run_in_threadpool(storage.login,username,password)
|
||||
if not result:
|
||||
unauthorized(request,basic=True)
|
||||
return result
|
||||
|
||||
|
||||
@router.get('/api/v1/users/me',response_model=User)
|
||||
def current_user(request: Request):
|
||||
return storage.get_user(require_user(request))
|
||||
|
||||
|
||||
@router.delete('/api/v1/auth/sessions/current',status_code=204)
|
||||
def logout(request: Request):
|
||||
require_user(request)
|
||||
storage.logout(request.state.token)
|
||||
return Response(status_code=204)
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
"""PostgreSQL — источник истины; каждый контекст подключения завершает транзакцию."""
|
||||
import base64
|
||||
import binascii
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
|
||||
from psycopg.errors import UniqueViolation, ForeignKeyViolation
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
from src.config import setting
|
||||
from src.cache import profile_cache
|
||||
from src.models import User, Chat, Message
|
||||
|
||||
_CURSOR_FIELDS = {"scope", "resource_id", "created_at", "id"}
|
||||
PASSWORDS = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
DUMMY_HASH = PASSWORDS.hash('synthetic-dummy-password')
|
||||
|
||||
|
||||
class ValidationError(Exception):
|
||||
"""Неверный запрос."""
|
||||
|
||||
|
||||
class ConflictError(Exception):
|
||||
"""Имя уже занято."""
|
||||
|
||||
|
||||
class LimitExceeded(Exception):
|
||||
"""Перегрузка сервера."""
|
||||
|
||||
|
||||
class NotFoundError(Exception):
|
||||
"""Объект отсутствует или недоступен."""
|
||||
|
||||
|
||||
def timestamp(value):
|
||||
return value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def public_row(row):
|
||||
return {k: timestamp(v) if isinstance(v, datetime) else str(v) if isinstance(v, uuid.UUID) else v
|
||||
for k, v in row.items() if k != 'password_hash'}
|
||||
|
||||
|
||||
class PostgresStorage:
|
||||
def __init__(self):
|
||||
self.pool = ConnectionPool(setting('DATABASE_URL', ''), min_size=1, max_size=10,
|
||||
timeout=3, max_waiting=32, open=False, check=ConnectionPool.check_connection,
|
||||
kwargs={'row_factory': dict_row, 'connect_timeout': 3,
|
||||
'options': '-c statement_timeout=3000 -c lock_timeout=2000'})
|
||||
self._lock = threading.Lock()
|
||||
self._requests = 0
|
||||
|
||||
@staticmethod
|
||||
def _encode_cursor(scope: str, resource_id: str, created_at: str, item_id: str) -> str:
|
||||
"""Собрать непрозрачный курсор, привязанный к конкретному ресурсу."""
|
||||
payload = {
|
||||
"scope": scope,
|
||||
"resource_id": resource_id,
|
||||
"created_at": created_at,
|
||||
"id": item_id,
|
||||
}
|
||||
raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
|
||||
@staticmethod
|
||||
def _decode_cursor(cursor: str, expected_scope: str, expected_resource_id: str) -> tuple[str, str]:
|
||||
"""Разобрать и проверить курсор.
|
||||
|
||||
Клиент видит курсор как непрозрачную строку, поэтому любые пустые,
|
||||
повреждённые или относящиеся к другому ресурсу значения отклоняем.
|
||||
"""
|
||||
if cursor == "":
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="
|
||||
if any(char not in allowed_chars for char in cursor) or "=" in cursor.rstrip("="):
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
try:
|
||||
raw = base64.b64decode(cursor.encode("ascii"), altchars=b"-_", validate=True)
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
except (UnicodeEncodeError, UnicodeDecodeError, binascii.Error, json.JSONDecodeError):
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
if not isinstance(payload, dict) or set(payload) != _CURSOR_FIELDS:
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
if not all(isinstance(payload[field], str) for field in _CURSOR_FIELDS):
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
if payload["scope"] != expected_scope or payload["resource_id"] != expected_resource_id:
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
try:
|
||||
uuid.UUID(payload["resource_id"])
|
||||
uuid.UUID(payload["id"])
|
||||
datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
raise ValidationError("некорректный cursor")
|
||||
|
||||
return payload["created_at"], payload["id"]
|
||||
|
||||
|
||||
def create_user(self, username, display_name, password):
|
||||
password_hash = PASSWORDS.hash(password)
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('INSERT INTO users (id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at',
|
||||
(uuid.uuid4(), username, display_name, password_hash)).fetchone()
|
||||
return User(**public_row(row))
|
||||
except UniqueViolation:
|
||||
raise ConflictError('имя пользователя уже занято') from None
|
||||
|
||||
def get_user(self, user_id):
|
||||
cached = profile_cache.get(user_id)
|
||||
if cached:
|
||||
return cached
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT id,username,display_name,created_at FROM users WHERE id=%s', (user_id,)).fetchone()
|
||||
user = User(**public_row(row)) if row else None
|
||||
if user:
|
||||
profile_cache.put(user)
|
||||
return user
|
||||
|
||||
def login(self, username, password):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT * FROM users WHERE username=%s', (username,)).fetchone()
|
||||
try:
|
||||
PASSWORDS.verify(row['password_hash'] if row else DUMMY_HASH, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return None
|
||||
if not row:
|
||||
return None
|
||||
token = secrets.token_urlsafe(32)
|
||||
with self.pool.connection() as conn:
|
||||
session = conn.execute("INSERT INTO sessions VALUES (%s,%s,clock_timestamp() + %s * interval '1 second') RETURNING expires_at",
|
||||
(self.token_hash(token), row['id'], int(os.getenv('SESSION_TTL_SECONDS', '3600')))).fetchone()
|
||||
return {'token': token, 'token_type': 'Bearer', 'expires_at': timestamp(session['expires_at']), 'user': User(**public_row(row)).model_dump()}
|
||||
|
||||
@staticmethod
|
||||
def token_hash(token):
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
def session_user(self, token):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at > clock_timestamp()', (self.token_hash(token),)).fetchone()
|
||||
return str(row['user_id']) if row else None
|
||||
|
||||
def logout(self, token):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute('DELETE FROM sessions WHERE token_hash=%s', (self.token_hash(token),))
|
||||
|
||||
def create_chat(self, title, member_ids, creator_id):
|
||||
if len(set(member_ids)) != len(member_ids) or creator_id not in member_ids:
|
||||
raise ValidationError('неверный список участников')
|
||||
chat_id = uuid.uuid4()
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('INSERT INTO chats (id,title) VALUES (%s,%s) RETURNING *', (chat_id,title)).fetchone()
|
||||
for member in member_ids:
|
||||
conn.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat_id,member))
|
||||
return Chat(**public_row(row), member_ids=sorted(member_ids))
|
||||
except ForeignKeyViolation:
|
||||
raise ValidationError('участник не существует') from None
|
||||
|
||||
def get_chat(self, chat_id):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('SELECT * FROM chats WHERE id=%s', (chat_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
members = conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id', (chat_id,)).fetchall()
|
||||
return Chat(**public_row(row), member_ids=[str(x['user_id']) for x in members])
|
||||
|
||||
def list_chats_for_user(self, user_id, cursor, limit):
|
||||
with self.pool.connection() as conn:
|
||||
params = [user_id]
|
||||
boundary = ''
|
||||
if cursor is not None:
|
||||
when, item = self._decode_cursor(cursor, 'chats', user_id)
|
||||
marker = conn.execute('SELECT c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE c.id=%s AND m.user_id=%s', (item,user_id)).fetchone()
|
||||
if not marker or timestamp(marker['created_at']) != when:
|
||||
raise ValidationError('некорректный cursor')
|
||||
boundary = ' AND (c.created_at,c.id) > (%s,%s)'
|
||||
params += [when,item]
|
||||
rows = conn.execute('SELECT c.* FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s' + boundary + ' ORDER BY c.created_at,c.id LIMIT %s', params+[limit+1]).fetchall()
|
||||
page = [self.get_chat(str(row['id'])) for row in rows[:limit]]
|
||||
next_cursor = self._encode_cursor('chats',user_id,page[-1].created_at,page[-1].id) if len(rows)>limit else None
|
||||
return page,next_cursor
|
||||
|
||||
def create_message(self, chat_id, sender_id, text):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute('INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *', (uuid.uuid4(),chat_id,sender_id,text)).fetchone()
|
||||
return Message(**public_row(row))
|
||||
|
||||
def list_messages(self, chat_id, cursor, limit):
|
||||
with self.pool.connection() as conn:
|
||||
params = [chat_id]
|
||||
boundary = ''
|
||||
if cursor is not None:
|
||||
when,item = self._decode_cursor(cursor,'messages',chat_id)
|
||||
marker = conn.execute('SELECT created_at FROM messages WHERE id=%s AND chat_id=%s', (item,chat_id)).fetchone()
|
||||
if not marker or timestamp(marker['created_at']) != when:
|
||||
raise ValidationError('некорректный cursor')
|
||||
boundary = ' AND (created_at,id) > (%s,%s)'
|
||||
params += [when,item]
|
||||
rows = conn.execute('SELECT * FROM messages WHERE chat_id=%s' + boundary + ' ORDER BY created_at,id LIMIT %s', params+[limit+1]).fetchall()
|
||||
page = [Message(**public_row(row)) for row in rows[:limit]]
|
||||
next_cursor = self._encode_cursor('messages',chat_id,page[-1].created_at,page[-1].id) if len(rows)>limit else None
|
||||
return page,next_cursor
|
||||
|
||||
def ready(self):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute('SELECT 1 FROM schema_migrations LIMIT 1')
|
||||
|
||||
def acquire_request_slot(self):
|
||||
with self._lock:
|
||||
if self._requests >= 100:
|
||||
return False
|
||||
self._requests += 1
|
||||
return True
|
||||
|
||||
def release_request_slot(self):
|
||||
with self._lock:
|
||||
self._requests -= 1
|
||||
|
||||
def get_stats(self):
|
||||
with self.pool.connection() as conn:
|
||||
result = {table: conn.execute('SELECT count(*) AS n FROM '+table).fetchone()['n'] for table in ('users','chats','messages')}
|
||||
result['profile_cache'] = {'hits': profile_cache.hits, 'misses': profile_cache.misses, 'errors': profile_cache.errors, 'ttl_seconds': profile_cache.ttl}
|
||||
return result
|
||||
|
||||
|
||||
storage = PostgresStorage()
|
||||
@@ -0,0 +1,10 @@
|
||||
# Собственные проверки лабораторной 2
|
||||
|
||||
- `python student-tests/test_lab2.py` — валидация, доступ, курсоры, 100 сообщений от 10 клиентов.
|
||||
- `python student-tests/test_level4.py` — гонка регистрации, rollback, Redis, отказ БД, expiry и logout. Временно останавливает только сервисы этого учебного Compose-проекта; основной API должен быть на 8080, порт 8082 свободен.
|
||||
- `python student-tests/explain_level4.py` — добавляет 10 000 синтетических сообщений и сохраняет SQL-план.
|
||||
- `python scripts/research.py` — создаёт отдельную исследовательскую БД на 100 000 сообщений, сравнивает три индекса, сохраняет дамп вне Git и восстанавливает его в новый отдельный Docker-том. Исследовательский контейнер после сверки остановлен, том и БД сохранены для защиты. Каждый повтор создаёт новые ресурсы; список записан в evidence/research.json и evidence/recovery.json.
|
||||
|
||||
Все команды запускаются из корня репозитория. Требуются работающий Docker Desktop в режиме Linux containers и Python 3.9+ на машине запуска. Сами публичные проверки используют только стандартную библиотеку Python; зависимости приложения устанавливаются внутри образа.
|
||||
|
||||
Старые тесты lab1 с X-User-Id и эксперимент token bucket заменены актуальными проверками lab2. Публичные tests/ и обязательный contracts/ сохранены.
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Проверить индекс истории на 10 000 синтетических сообщений."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client, check
|
||||
from support import sql
|
||||
|
||||
c=Client('http://localhost:8080')
|
||||
a,b,_,chat=c.bootstrap()
|
||||
sql("INSERT INTO messages (id,chat_id,sender_id,text,created_at) SELECT gen_random_uuid(),%s,%s,'Синтетическое ' || n, timestamptz '2026-01-01' + n * interval '1 microsecond' FROM generate_series(1,10000) n",[chat['id'],a['id']])
|
||||
sql('ANALYZE messages')
|
||||
marker=sql('SELECT created_at,id FROM messages WHERE chat_id=%s ORDER BY created_at,id OFFSET 8000 LIMIT 1',[chat['id']])[0]
|
||||
query='SELECT * FROM messages WHERE chat_id=%s AND (created_at,id)>(%s,%s) ORDER BY created_at,id LIMIT 51'
|
||||
plan=sql('EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) '+query,[chat['id'],marker['created_at'],marker['id']])[0]['QUERY PLAN'][0]
|
||||
check('messages_history_idx' in json.dumps(plan),'индекс истории не используется')
|
||||
Path('evidence/explain_10000.json').write_text(json.dumps({'rows':10000,'query':query,'plan':plan},ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
||||
print('PASS: 10000 messages, indexed keyset pagination, execution ms:',plan['Execution Time'])
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Сравнение индексов в отдельной БД, не затрагивающее данные API."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import time
|
||||
import uuid
|
||||
import psycopg
|
||||
from psycopg import sql
|
||||
from psycopg.conninfo import make_conninfo
|
||||
from psycopg.rows import dict_row
|
||||
from src.config import setting
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
ordered=sorted(values)
|
||||
return ordered[min(len(ordered)-1, int((len(ordered)-1)*p))]
|
||||
|
||||
|
||||
def main():
|
||||
name='lab2_research_'+uuid.uuid4().hex[:10]
|
||||
url=setting('DATABASE_URL')
|
||||
with psycopg.connect(url,autocommit=True) as admin:
|
||||
admin.execute(sql.SQL('CREATE DATABASE {}').format(sql.Identifier(name)))
|
||||
conn=psycopg.connect(make_conninfo(url,dbname=name),row_factory=dict_row,autocommit=True)
|
||||
conn.execute("SET statement_timeout='30s'")
|
||||
for path in sorted(Path('/app/migrations').glob('*.sql')):
|
||||
conn.execute(path.read_text(encoding='utf-8'))
|
||||
user=str(uuid.uuid4())
|
||||
conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,'research','Синтетический пользователь','не используется для входа')",[user])
|
||||
sizes=[70000,20000,9000]+[100]*10
|
||||
chats=[]
|
||||
seed_started=time.perf_counter()
|
||||
with conn.transaction():
|
||||
for i,size in enumerate(sizes):
|
||||
chat=str(uuid.uuid4())
|
||||
chats.append(chat)
|
||||
conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)',[chat,'Исследование '+str(i)])
|
||||
conn.execute('INSERT INTO chat_members VALUES (%s,%s)',[chat,user])
|
||||
conn.execute("INSERT INTO messages(id,chat_id,sender_id,text,created_at) SELECT gen_random_uuid(),%s,%s,repeat('x',128) || n, timestamptz '2026-01-01' + n * interval '1 microsecond' FROM generate_series(1,%s) n",[chat,user,size])
|
||||
seed_seconds=time.perf_counter()-seed_started
|
||||
conn.execute('DROP INDEX messages_history_idx')
|
||||
conn.execute('VACUUM ANALYZE messages')
|
||||
variants=[('chat_only','CREATE INDEX research_idx ON messages(chat_id)'),
|
||||
('composite','CREATE INDEX research_idx ON messages(chat_id,created_at,id)'),
|
||||
('covering','CREATE INDEX research_idx ON messages(chat_id,created_at,id) INCLUDE(sender_id,text)')]
|
||||
result={'database':name,'rows':sum(sizes),'chat_sizes':sizes,'seed_seconds':seed_seconds,
|
||||
'concurrency':1,'warmup_queries_per_case':3,'queries_per_case':100,'repeats_write':3,'variants':[]}
|
||||
query='SELECT * FROM messages WHERE chat_id=%s AND (created_at,id)>(%s,%s) ORDER BY created_at,id LIMIT 51'
|
||||
result['query']=query
|
||||
for label,ddl in variants:
|
||||
started=time.perf_counter()
|
||||
conn.execute(ddl)
|
||||
build_seconds=time.perf_counter()-started
|
||||
conn.execute('VACUUM ANALYZE messages')
|
||||
cases=[]
|
||||
for chat,size in zip(chats[:4],sizes[:4]):
|
||||
for depth in [0.1,0.5,0.9]:
|
||||
# OFFSET нужен только для выбора фиксированной точки эксперимента.
|
||||
marker=conn.execute('SELECT created_at,id FROM messages WHERE chat_id=%s ORDER BY created_at,id OFFSET %s LIMIT 1',[chat,int(size*depth)]).fetchone()
|
||||
params=[chat,marker['created_at'],marker['id']]
|
||||
for _ in range(3):
|
||||
conn.execute(query,params).fetchall()
|
||||
timings=[]
|
||||
for _ in range(100):
|
||||
start=time.perf_counter()
|
||||
rows=conn.execute(query,params).fetchall()
|
||||
timings.append((time.perf_counter()-start)*1000)
|
||||
assert len(rows)==min(51,size-int(size*depth)-1)
|
||||
plan=conn.execute('EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON) '+query,params).fetchone()['QUERY PLAN'][0]
|
||||
cases.append({'chat_size':size,'depth':depth,'successful_queries':100,'errors':0,
|
||||
'duration_seconds':sum(timings)/1000,'successful_rps':100000/sum(timings),
|
||||
'p50_ms':percentile(timings,0.5),'p95_ms':percentile(timings,0.95),'p99_ms':percentile(timings,0.99),'plan':plan})
|
||||
writes=[]
|
||||
for trial in range(3):
|
||||
start=time.perf_counter()
|
||||
with conn.transaction():
|
||||
conn.execute("INSERT INTO messages(id,chat_id,sender_id,text) SELECT gen_random_uuid(),%s,%s,'write_probe' FROM generate_series(1,1000)",[chats[0],user])
|
||||
writes.append(time.perf_counter()-start)
|
||||
conn.execute("DELETE FROM messages WHERE text='write_probe'")
|
||||
index_bytes=conn.execute("SELECT pg_relation_size('research_idx') AS n").fetchone()['n']
|
||||
result['variants'].append({'name':label,'ddl':ddl,'build_seconds':build_seconds,'index_bytes':index_bytes,
|
||||
'write_1000_commit_seconds':writes,'write_median_rows_per_second':1000/statistics.median(writes),'cases':cases})
|
||||
conn.execute('DROP INDEX research_idx')
|
||||
conn.execute('CREATE INDEX messages_history_idx ON messages(chat_id,created_at,id)')
|
||||
conn.execute('VACUUM ANALYZE messages')
|
||||
result['final_count']=conn.execute('SELECT count(*) AS n FROM messages').fetchone()['n']
|
||||
assert result['final_count']==100000
|
||||
conn.close()
|
||||
print(json.dumps(result,ensure_ascii=False,default=str))
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Административные запросы только к изолированному учебному стенду Compose."""
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
|
||||
def compose(*args):
|
||||
result=subprocess.run(['docker','compose',*args],capture_output=True,text=True,encoding='utf-8',errors='replace',check=True)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def sql(query, params=None):
|
||||
source="""import json, psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from src.config import setting
|
||||
with psycopg.connect(setting('DATABASE_URL'),row_factory=dict_row) as conn:
|
||||
cursor=conn.execute(%r, %r)
|
||||
result=cursor.fetchall() if cursor.description else []
|
||||
print(json.dumps(result,default=str))
|
||||
""" % (query,params)
|
||||
result=subprocess.run(['docker','compose','exec','-T','api','python','-'],input=source,capture_output=True,text=True,encoding='utf-8',check=True)
|
||||
return json.loads(result.stdout)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Негативные сценарии, курсоры и конкурентная запись через реальный HTTP API."""
|
||||
import concurrent.futures
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args=arguments('Собственные проверки лабораторной 2')
|
||||
c=Client(args.base_url,args.ca_file)
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
path='/api/v1/chats/'+chat['id']+'/messages'
|
||||
c.call('POST','/api/v1/users',400,body={'username':'short','display_name':'Тест','password':'short'})
|
||||
c.call('POST',path,400,actor=alice,body={'text':'hello','sender_id':bob['id']})
|
||||
c.call('POST',path,400,actor=alice,body={'text':' '})
|
||||
c.call('GET','/api/v1/chats/not-a-uuid',400,actor=alice)
|
||||
# Сначала идентификация, затем валидация и доступ к ресурсу.
|
||||
c.call('GET','/api/v1/chats/not-a-uuid',401)
|
||||
c.call('POST',path,401,body={'text':''})
|
||||
c.call('POST',path,400,actor=alice,raw=b'{',headers={'Content-Type':'application/json'})
|
||||
c.call('POST',path,404,actor=eve,body={'text':'чужое'})
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
|
||||
sent=list(pool.map(lambda i: c.message(alice,chat,'Параллельное '+str(i))['json'],range(100)))
|
||||
expected={m['id'] for m in sent}
|
||||
received=[]
|
||||
cursor=None
|
||||
while True:
|
||||
url=path+'?limit=7'+('&cursor='+quote(cursor,safe='') if cursor else '')
|
||||
page=c.call('GET',url,actor=bob,schema='MessagePage')['json']
|
||||
received.extend(m['id'] for m in page['items'])
|
||||
cursor=page['next_cursor']
|
||||
if cursor is None:
|
||||
break
|
||||
check(len(received)==100 and set(received)==expected,'потеря или дубликат сообщения')
|
||||
page=c.call('GET',path+'?limit=1',actor=alice,schema='MessagePage')['json']
|
||||
other=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Другой','member_ids':[alice['id']]},schema='Chat')['json']
|
||||
c.call('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+quote(page['next_cursor'],safe=''),400,actor=alice)
|
||||
for bad in ['', 'not-base64', 'e30=']:
|
||||
c.call('GET',path+'?cursor='+quote(bad,safe=''),400,actor=alice)
|
||||
print('PASS: strict validation, access, cursor binding, 100 messages / 10 clients, complete pagination')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Гонки, транзакции, короткий TTL и реальные отказы зависимостей."""
|
||||
import concurrent.futures
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client, check
|
||||
from support import compose, sql
|
||||
|
||||
|
||||
def wait_ready(client):
|
||||
deadline=time.monotonic()+45
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
client.call('GET','/health/ready',schema='Health')
|
||||
return
|
||||
except Exception:
|
||||
time.sleep(0.3)
|
||||
raise AssertionError('сервер не восстановился')
|
||||
|
||||
|
||||
def main():
|
||||
c=Client('http://localhost:8080')
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
registration=dict(alice['registration'],username='race_'+uuid.uuid4().hex[:16])
|
||||
def register(i):
|
||||
# Оба результата допустимы для отдельного участника гонки.
|
||||
import urllib.request, urllib.error
|
||||
req=urllib.request.Request(c.base+'/api/v1/users',data=json.dumps(registration).encode(),headers={'Content-Type':'application/json'},method='POST')
|
||||
try:
|
||||
with urllib.request.urlopen(req,timeout=10) as response:
|
||||
return response.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
codes=list(pool.map(register,range(8)))
|
||||
check(codes.count(201)==1 and codes.count(409)==7,'гонка регистрации: '+str(codes))
|
||||
before=sql('SELECT count(*) AS n FROM chats')[0]['n']
|
||||
c.call('POST','/api/v1/chats',400,actor=alice,body={'title':'Rollback','member_ids':[alice['id'],str(uuid.uuid4())]})
|
||||
check(sql('SELECT count(*) AS n FROM chats')[0]['n']==before,'чат не откатился')
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
cached=compose('exec','-T','redis','redis-cli','GET','profile:v1:'+alice['id'])
|
||||
check(alice['id'] in cached,'Redis не используется')
|
||||
ttl=int(compose('exec','-T','redis','redis-cli','TTL','profile:v1:'+alice['id']))
|
||||
check(0<ttl<=60,'нет TTL кэша')
|
||||
started=time.monotonic()
|
||||
try:
|
||||
compose('stop','redis')
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
redis_fallback=time.monotonic()-started
|
||||
c.call('GET','/api/v1/users/me',401)
|
||||
finally:
|
||||
compose('start','redis')
|
||||
# Потеря кэша не теряет сессии и публичные профили.
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
try:
|
||||
compose('stop','db')
|
||||
c.call('GET','/health/live',schema='Health')
|
||||
started=time.monotonic()
|
||||
c.call('GET','/health/ready',503)
|
||||
c.call('GET','/api/v1/users/me',503,actor=alice)
|
||||
db_failure=time.monotonic()-started
|
||||
finally:
|
||||
compose('start','db')
|
||||
wait_ready(c)
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
# В отдельном процессе срок жизни 2 секунды; основной стенд не меняется.
|
||||
name='lyakhonov-lab2-expiry-'+uuid.uuid4().hex[:6]
|
||||
try:
|
||||
compose('run','-d','--name',name,'-p','127.0.0.1:8082:8080','-e','SESSION_TTL_SECONDS=2','api')
|
||||
short=Client('http://localhost:8082')
|
||||
wait_ready(short)
|
||||
a,_,_,_=short.bootstrap()
|
||||
short.call('GET','/api/v1/users/me',actor=a,schema='User')
|
||||
time.sleep(2.2)
|
||||
response=short.call('GET','/api/v1/users/me',401,actor=a)
|
||||
check('Bearer' in response['headers'].get('WWW-Authenticate',''),'нет Bearer challenge')
|
||||
finally:
|
||||
subprocess.run(['docker','rm','-f',name],check=True,capture_output=True)
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
|
||||
c.call('GET','/api/v1/users/me',401,actor=alice)
|
||||
result={'registration_codes':codes,'rollback':'PASS','profile_cache_ttl_seconds':ttl,
|
||||
'redis_fallback':'PASS','redis_stop_and_request_seconds':round(redis_fallback,3),
|
||||
'db_failure':'503, live=200, recovery with same session','two_db_error_requests_seconds':round(db_failure,3),
|
||||
'expiry_seconds':2,'expiry':'401','logout':'401','passed':True}
|
||||
Path('evidence/level4.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
||||
print('PASS: registration race, chat rollback, Redis TTL/fallback/restart, DB outage/recovery, expiry, logout')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user