Implement lab3 replicated API and experiment evidence
This commit is contained in:
+18
-12
@@ -1,13 +1,19 @@
|
|||||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
# Local settings for the lab3 Docker Compose stack.
|
||||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
# Create .env from this template and replace the password.
|
||||||
APP_HOST=0.0.0.0
|
# Never commit .env or real credentials.
|
||||||
APP_PORT=8080
|
|
||||||
APP_ENV=lab
|
POSTGRES_PASSWORD=replace_with_a_local_random_password
|
||||||
|
|
||||||
|
# Lifetime of newly created sessions, in seconds.
|
||||||
SESSION_TTL_SECONDS=3600
|
SESSION_TTL_SECONDS=3600
|
||||||
# Choose credentials locally. File paths contain no secret values.
|
|
||||||
DATABASE_URL_FILE=/run/secrets/database_url
|
# Public user profile cache lifetime, in seconds.
|
||||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
USER_CACHE_TTL_SECONDS=60
|
||||||
SESSION_STORE=postgres
|
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
# Other settings are defined in compose.yaml:
|
||||||
API_REPLICAS=2
|
# - public endpoint: http://127.0.0.1:18082
|
||||||
IDEMPOTENCY_TTL_SECONDS=86400
|
# - two API replicas
|
||||||
|
# - PostgreSQL connection parameters
|
||||||
|
# - Redis connection parameters
|
||||||
|
#
|
||||||
|
# Idempotency records have no automatic expiration or cleanup.
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
FROM python:3.12.10-slim-bookworm
|
||||||
|
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
PIP_NO_CACHE_DIR=1
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt ./
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
RUN addgroup --system appgroup \
|
||||||
|
&& adduser --system --ingroup appgroup --no-create-home appuser \
|
||||||
|
&& chown appuser:appgroup /app
|
||||||
|
|
||||||
|
COPY --chown=appuser:appgroup app ./app
|
||||||
|
COPY --chown=appuser:appgroup migrations ./migrations
|
||||||
|
|
||||||
|
USER appuser
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||||
|
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2).read()" || exit 1
|
||||||
|
|
||||||
|
CMD ["python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080", "--no-access-log"]
|
||||||
@@ -1,37 +1,843 @@
|
|||||||
# Отчёт — лабораторная 3
|
# Отчёт — лабораторная 3
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Соколова Полина БВТ2304.
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка: 4.
|
||||||
- Commit/PR: TODO после публикации
|
- Трек уровня 5: не заявлен.
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Основа реализации: приложение из лабораторной 2 и skeleton
|
||||||
|
лабораторной 3. Публичные тесты использовались для проверки
|
||||||
|
реализации, а не как доказательство всех инфраструктурных критериев.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## 1. Цель работы
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Запустить несколько API-реплик за одной публичной точкой входа
|
||||||
|
и проверить:
|
||||||
|
|
||||||
## Архитектура и решения
|
- работу существующей сессии через разные реплики;
|
||||||
|
- общую идемпотентность отправки сообщения;
|
||||||
|
- сохранность подтверждённых данных после перезапуска;
|
||||||
|
- восстановление работы при остановке одной API-реплики;
|
||||||
|
- поочерёдную замену API-контейнеров под нагрузкой;
|
||||||
|
- потребление ресурсов при заданных ограничениях CPU/RAM.
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
## 2. Окружение и ограничения ресурсов
|
||||||
|
|
||||||
## Доказательства критериев
|
Эксперименты выполнялись в Linux под WSL2:
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
- ядро: `6.6.87.2-microsoft-standard-WSL2`;
|
||||||
|
- доступных логических CPU: 16;
|
||||||
|
- память среды по `free -h`: около 7,6 GiB;
|
||||||
|
- swap: 2,0 GiB.
|
||||||
|
|
||||||
|
Это характеристики среды WSL2, а не ресурсы,
|
||||||
|
гарантированно выделенные каждому контейнеру.
|
||||||
|
|
||||||
|
Зафиксированные в выводе Docker образы:
|
||||||
|
|
||||||
|
- API: `mtusi-messenger:lab3`;
|
||||||
|
- PostgreSQL: `postgres:16.4-bookworm`;
|
||||||
|
- Redis: `redis:7.2.5-bookworm`;
|
||||||
|
- HAProxy: `haproxy:3.0.5-bookworm`.
|
||||||
|
|
||||||
|
Версия Python и базовый образ API задаются в Dockerfile,
|
||||||
|
версии Python-зависимостей — в `requirements.txt`.
|
||||||
|
|
||||||
|
### Лимиты работающих сервисов
|
||||||
|
|
||||||
|
| Сервис | Лимит CPU | Лимит памяти |
|
||||||
|
| --- | ---: | ---: |
|
||||||
|
| Каждая API-реплика | 0,75 CPU | 512 MiB |
|
||||||
|
| PostgreSQL | 1 CPU | 512 MiB |
|
||||||
|
| Redis | 0,25 CPU | 128 MiB |
|
||||||
|
| HAProxy | 0,25 CPU | 128 MiB |
|
||||||
|
|
||||||
|
Ограничения проверены через `docker inspect`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -p mtusi2026lab3 ps -q api postgres redis lb |
|
||||||
|
xargs -r docker inspect --format \
|
||||||
|
'{{.Name}} | NanoCPUs={{.HostConfig.NanoCpus}} | MemoryBytes={{.HostConfig.Memory}}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Доказательство: `evidence/resource-limits.txt`.
|
||||||
|
|
||||||
|
Лимиты не являются измеренным потреблением.
|
||||||
|
Фактические показания CPU/RAM приведены в отдельном эксперименте.
|
||||||
|
|
||||||
|
## 3. Запуск из чистого clone
|
||||||
|
|
||||||
|
### Предварительные условия
|
||||||
|
|
||||||
|
- Git.
|
||||||
|
- Docker Engine с Docker Compose v2.
|
||||||
|
- Python 3.9+ и Make для запуска публичных тестов.
|
||||||
|
- Свободный локальный порт 18082.
|
||||||
|
- Достаточные ресурсы для запуска сервисов с указанными лимитами.
|
||||||
|
|
||||||
|
Ранее запущенная лабораторная 2 для работы стенда не требуется.
|
||||||
|
|
||||||
|
### Подготовка конфигурации
|
||||||
|
|
||||||
|
Создать локальный `.env` в корне проекта через редактор:
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
POSTGRES_PASSWORD=REPLACE_WITH_A_LOCAL_RANDOM_PASSWORD
|
||||||
|
SESSION_TTL_SECONDS=3600
|
||||||
|
USER_CACHE_TTL_SECONDS=60
|
||||||
|
```
|
||||||
|
|
||||||
|
Заменить значение `POSTGRES_PASSWORD` на собственный случайный
|
||||||
|
пароль. Заглушку из примера не использовать как реальный секрет.
|
||||||
|
|
||||||
|
Файл `.env` не публиковать и не добавлять в Git.
|
||||||
|
Секреты не включать в отчёт и evidence-файлы.
|
||||||
|
|
||||||
|
### Сборка и запуск
|
||||||
|
|
||||||
|
Из корня репозитория:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -p mtusi2026lab3 config --quiet
|
||||||
|
|
||||||
|
docker compose -p mtusi2026lab3 up -d --build --scale api=2
|
||||||
|
|
||||||
|
docker compose -p mtusi2026lab3 ps -a
|
||||||
|
```
|
||||||
|
|
||||||
|
Ожидаемый результат:
|
||||||
|
|
||||||
|
- две работающие API-реплики;
|
||||||
|
- PostgreSQL и Redis в состоянии healthy;
|
||||||
|
- работающий HAProxy;
|
||||||
|
- одноразовый сервис migrate завершён с кодом 0;
|
||||||
|
- после завершения стартовых проверок обе API-реплики healthy.
|
||||||
|
|
||||||
|
Проверка готовности через публичную точку входа:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -i --max-time 10 http://localhost:18082/health/ready
|
||||||
|
```
|
||||||
|
|
||||||
|
При запуске сервисов возможна временная неготовность.
|
||||||
|
Проверку повторять до HTTP 200.
|
||||||
|
|
||||||
|
Проверка миграций и публичного сценария:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -p mtusi2026lab3 logs --tail=50 migrate
|
||||||
|
|
||||||
|
make test BASE_URL=http://localhost:18082
|
||||||
|
```
|
||||||
|
|
||||||
|
### Конфигурационные переменные
|
||||||
|
|
||||||
|
В `.env.example` перечислены только параметры, которые
|
||||||
|
подставляются из окружения в `compose.yaml`:
|
||||||
|
|
||||||
|
- `POSTGRES_PASSWORD` — локальный пароль PostgreSQL;
|
||||||
|
- `SESSION_TTL_SECONDS` — срок действия новых сессий в секундах;
|
||||||
|
- `USER_CACHE_TTL_SECONDS` — TTL кэша публичного профиля в секундах.
|
||||||
|
|
||||||
|
Параметры `PGHOST`, `PGPORT`, `PGDATABASE`, `PGUSER`, `PGPASSWORD`,
|
||||||
|
`REDIS_HOST` и `REDIS_PORT` передаются приложению через Compose.
|
||||||
|
В частности, `PGPASSWORD` получает значение `POSTGRES_PASSWORD`.
|
||||||
|
|
||||||
|
Внутренние адреса сервисов, публичный порт балансировщика,
|
||||||
|
команда запуска API и число реплик задаются в `compose.yaml`.
|
||||||
|
|
||||||
|
Файловые интерфейсы `DATABASE_URL_FILE` и `CACHE_URL_FILE`
|
||||||
|
не используются и в актуальном `.env.example` не перечислены.
|
||||||
|
|
||||||
|
Автоматический TTL ключей идемпотентности не реализован:
|
||||||
|
старые записи автоматически не удаляются.
|
||||||
|
|
||||||
|
### Остановка
|
||||||
|
|
||||||
|
Остановка без удаления контейнеров и volumes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -p mtusi2026lab3 stop
|
||||||
|
```
|
||||||
|
|
||||||
|
Повторный запуск существующих контейнеров:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -p mtusi2026lab3 start
|
||||||
|
```
|
||||||
|
|
||||||
|
Намеренное удаление учебного стенда и его volumes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -p mtusi2026lab3 down --volumes
|
||||||
|
```
|
||||||
|
|
||||||
|
Последняя команда удаляет учебные данные.
|
||||||
|
Она не используется в persistence-проверке.
|
||||||
|
|
||||||
|
### Статус проверки чистого запуска
|
||||||
|
|
||||||
|
Работа текущего стенда и повторные запуски проверены.
|
||||||
|
Отдельный запуск из чистого clone с новыми volumes
|
||||||
|
на момент составления отчёта ещё не выполнен.
|
||||||
|
|
||||||
|
Поэтому приведённая инструкция пока не является
|
||||||
|
доказательством проверенного чистого запуска.
|
||||||
|
|
||||||
|
## 4. Архитектура
|
||||||
|
|
||||||
|
```text
|
||||||
|
Клиент
|
||||||
|
|
|
||||||
|
v
|
||||||
|
HAProxy, 127.0.0.1:18082
|
||||||
|
|
|
||||||
|
+---------- API-реплика
|
||||||
|
|
|
||||||
|
+---------- API-реплика
|
||||||
|
|
|
||||||
|
+---------- PostgreSQL
|
||||||
|
|
|
||||||
|
+---------- Redis
|
||||||
|
```
|
||||||
|
|
||||||
|
HAProxy является единственной опубликованной точкой входа.
|
||||||
|
|
||||||
|
У API, PostgreSQL и Redis нет опубликованных портов на хост.
|
||||||
|
В выводе `docker compose ps -a` для них показаны внутренние
|
||||||
|
порты, а у HAProxy — привязка `127.0.0.1:18082->8080/tcp`.
|
||||||
|
|
||||||
|
PostgreSQL является источником истины для пользователей,
|
||||||
|
чатов, участников, сообщений, сессий и ключей идемпотентности.
|
||||||
|
|
||||||
|
Redis используется как кэш публичного профиля.
|
||||||
|
Данные кэша не должны быть единственным источником истины.
|
||||||
|
|
||||||
|
API-реплики используют общие хранилища.
|
||||||
|
Корректность сессии и идемпотентной операции не должна
|
||||||
|
зависеть от попадания клиента на прежнюю реплику.
|
||||||
|
|
||||||
|
### Изменения относительно лабораторной 2
|
||||||
|
|
||||||
|
Сохранена основа приложения, включая API, работу с PostgreSQL,
|
||||||
|
аутентификацию, сессии, сообщения и кэш профиля.
|
||||||
|
|
||||||
|
В лабораторной 3 добавлены или адаптированы:
|
||||||
|
|
||||||
|
- запуск двух API-реплик;
|
||||||
|
- HAProxy;
|
||||||
|
- обнаружение backend-адресов через Docker DNS;
|
||||||
|
- идентификатор экземпляра в `X-Instance-Id`;
|
||||||
|
- общая идемпотентность отправки сообщений;
|
||||||
|
- миграция для хранения идемпотентных операций;
|
||||||
|
- инфраструктурные hooks;
|
||||||
|
- собственные проверки конкуренции, отказов и замены.
|
||||||
|
|
||||||
|
## 5. Балансировка, готовность и остановка
|
||||||
|
|
||||||
|
HAProxy использует Round Robin.
|
||||||
|
Backend-адреса обнаруживаются через Docker DNS
|
||||||
|
с использованием resolvers и server-template.
|
||||||
|
|
||||||
|
Готовность API проверяется через `/health/ready`.
|
||||||
|
|
||||||
|
API возвращает идентификатор экземпляра в `X-Instance-Id`.
|
||||||
|
Он позволяет отличать ответы разных процессов
|
||||||
|
и проверять прохождение запросов через новую реплику.
|
||||||
|
|
||||||
|
При остановке API выполняется graceful shutdown Uvicorn.
|
||||||
|
Это видно в логах:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Shutting down
|
||||||
|
Waiting for application shutdown.
|
||||||
|
Application shutdown complete.
|
||||||
|
Finished server process
|
||||||
|
```
|
||||||
|
|
||||||
|
После запуска нового процесса фиксируются startup-сообщения.
|
||||||
|
|
||||||
|
Предварительное управляемое исключение backend из HAProxy
|
||||||
|
перед плановой остановкой в сценарии замены не реализовано.
|
||||||
|
Из-за этого часть запросов в переходном периоде
|
||||||
|
может попадать на уже недоступный backend.
|
||||||
|
|
||||||
|
Прозрачные повторы HAProxy отключены.
|
||||||
|
Генератор нагрузки также не выполняет автоматические повторы.
|
||||||
|
|
||||||
|
## 6. Сессии и идемпотентность
|
||||||
|
|
||||||
|
Сессии хранятся в общем PostgreSQL.
|
||||||
|
Существующая сессия проверялась после перезапуска
|
||||||
|
и при обращении через новые API-реплики.
|
||||||
|
|
||||||
|
Для отправки сообщения используется `Idempotency-Key`.
|
||||||
|
|
||||||
|
Область ключа включает пользователя и чат для операции
|
||||||
|
отправки сообщения. Один и тот же ключ в другой области
|
||||||
|
не должен ошибочно возвращать чужой результат.
|
||||||
|
|
||||||
|
Поведение:
|
||||||
|
|
||||||
|
- новый ключ создаёт сообщение;
|
||||||
|
- повтор того же запроса возвращает прежнее Message;
|
||||||
|
- тот же ключ с другим текстом возвращает 409;
|
||||||
|
- некорректный или отсутствующий обязательный ключ возвращает 400;
|
||||||
|
- авторизация и доступ к чату проверяются и при повторе.
|
||||||
|
|
||||||
|
Запись сообщения и результата идемпотентной операции
|
||||||
|
выполняется транзакционно в PostgreSQL.
|
||||||
|
Для сериализации конкурентных операций используется
|
||||||
|
транзакционная advisory lock.
|
||||||
|
|
||||||
|
Порядок полей и форматирование JSON не определяют
|
||||||
|
идентичность запроса. Отсутствующий `attachment_ids`
|
||||||
|
и пустой список считаются эквивалентными.
|
||||||
|
Непустые вложения в этой работе не поддерживаются.
|
||||||
|
|
||||||
|
Ключи не удаляются автоматически.
|
||||||
|
Ограничение срока хранения снизу обеспечивается отсутствием
|
||||||
|
очистки, но это создаёт риск неограниченного роста таблицы.
|
||||||
|
|
||||||
|
## 7. Миграции
|
||||||
|
|
||||||
|
Миграции запускаются отдельным одноразовым сервисом migrate.
|
||||||
|
|
||||||
|
В наблюдавшемся стенде migrate завершился с кодом 0.
|
||||||
|
API использовали подготовленную схему PostgreSQL.
|
||||||
|
|
||||||
|
Для хранения идемпотентных операций добавлена миграция
|
||||||
|
`002_message_idempotency.sql`.
|
||||||
|
|
||||||
|
Во время экспериментов замены контейнеров схема не менялась.
|
||||||
|
Проверялась замена контейнеров с текущим образом,
|
||||||
|
а не совместимость двух версий приложения при миграции схемы.
|
||||||
|
|
||||||
|
## 8. Доказательства критериев
|
||||||
|
|
||||||
|
Все пути в таблице указаны относительно корня репозитория.
|
||||||
|
|
||||||
|
| Критерий | Команда или сценарий | Наблюдаемый результат | Доказательство |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Публичный API-сценарий после замены | `make test BASE_URL=http://localhost:18082` | PASS, код 0 | `evidence/smoke-after-replacement.txt` |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Две работающие реплики | `docker compose ps -a` до и после замены | Две healthy API-реплики | `evidence/rolling-replacement.txt` |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Общая сессия при замене | `student-tests/rolling_replacement.py` | Прежняя сессия работает через каждую новую реплику | `evidence/rolling-replacement.txt` |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Сохранность после перезапуска | `make test-persistence` и сравнение StartedAt | PASS, код 0; перезапущены обе API-реплики, PostgreSQL, Redis и HAProxy | `evidence/persistence.txt` |
|
||||||
|
| Отказ первой реплики | Собственный targeted failover | Восстановление записи, сохранение контрольных данных | `evidence/failover-api-1.txt` |
|
||||||
|
| Отказ второй реплики | Собственный targeted failover | Восстановление записи, сохранение контрольных данных | `evidence/failover-api-2.txt` |
|
||||||
|
| Конкурентная идемпотентность | `student-tests/concurrent_idempotency.py` | Один Message на раунд при запросах через две реплики | `evidence/concurrent-idempotency.txt` |
|
||||||
|
| Применённые ограничения ресурсов | `docker inspect` | Проверены CPU/RAM limits | `evidence/resource-limits.txt` |
|
||||||
|
| Поочерёдная замена под нагрузкой | `rolling_replacement.py` одновременно с `tests/load.py` | Обе исходные реплики заменены, контрольные проверки прошли | `evidence/rolling-replacement.txt`, `evidence/load-window.txt`, `evidence/load-during-replacement-repeat.json` |
|
||||||
|
| Нагрузка без отказов | `tests/load.py`, 90 секунд, concurrency 4 | 7061 успешный запрос, 0 ошибок | `evidence/load-resources.json`, `evidence/load-resources-window.txt` |
|
||||||
|
| Фактическое потребление ресурсов | 10 снимков `docker stats` | Сохранены CPU и память пяти контейнеров | `evidence/resources-under-load.txt` |
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
Успех публичного smoke не является самостоятельным
|
||||||
|
подтверждением всех инфраструктурных критериев
|
||||||
|
или гарантией итоговой оценки.
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## 9. Проверка persistence
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Команда:
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
```bash
|
||||||
|
make test-persistence \
|
||||||
|
BASE_URL=http://localhost:18082 \
|
||||||
|
ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверка выполнена 29 октября 2026 года,
|
||||||
|
внешний интервал — 16:44:33–16:44:45 UTC.
|
||||||
|
|
||||||
|
Результат:
|
||||||
|
|
||||||
|
```text
|
||||||
|
PASS: persistence preserved confirmed data and existing session.
|
||||||
|
Hook scope needs operator evidence.
|
||||||
|
Код завершения make: 0
|
||||||
|
```
|
||||||
|
|
||||||
|
Дополнительно сохранены Container ID и StartedAt
|
||||||
|
до и после выполнения hook.
|
||||||
|
|
||||||
|
| Компонент | StartedAt до, UTC | StartedAt после, UTC |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| API-2 | 16:25:47 | 16:44:39 |
|
||||||
|
| API-3 | 16:26:01 | 16:44:39 |
|
||||||
|
| HAProxy | 15:40:54 | 16:44:39 |
|
||||||
|
| PostgreSQL | 15:40:54 | 16:44:39 |
|
||||||
|
| Redis | 15:40:54 | 16:44:38 |
|
||||||
|
|
||||||
|
Container ID остались прежними.
|
||||||
|
Следовательно, в этом сценарии выполнен перезапуск,
|
||||||
|
а не замена контейнеров.
|
||||||
|
|
||||||
|
Изменившийся StartedAt подтверждает область действия hook:
|
||||||
|
перезапущены обе API-реплики, PostgreSQL, Redis и HAProxy.
|
||||||
|
|
||||||
|
Тест подтвердил сохранность проверенных им данных
|
||||||
|
и существующей сессии.
|
||||||
|
|
||||||
|
Сразу после завершения теста API ещё имели Docker health status
|
||||||
|
`starting`. При последующей диагностике обе реплики были healthy,
|
||||||
|
а публичный `/health/ready` вернул 200.
|
||||||
|
|
||||||
|
Доказательство: `evidence/persistence.txt`.
|
||||||
|
|
||||||
|
## 10. Отказ каждой API-реплики
|
||||||
|
|
||||||
|
Собственный сценарий targeted failover запускался
|
||||||
|
последовательно для двух API-контейнеров.
|
||||||
|
Перед следующим сценарием остановленная реплика восстанавливалась.
|
||||||
|
|
||||||
|
Во время отказа выполнялись записи и периодические чтения.
|
||||||
|
Неопределённые попытки отправки повторялись
|
||||||
|
с тем же ключом и телом.
|
||||||
|
|
||||||
|
Ранее зафиксированные результаты:
|
||||||
|
|
||||||
|
| Показатель | Первая реплика | Вторая реплика |
|
||||||
|
| --- | ---: | ---: |
|
||||||
|
| Длительность сценария, с | 15,328 | 15,053 |
|
||||||
|
| Успешные записи | 118 | 112 |
|
||||||
|
| Неуспешные попытки записи | 2 | 2 |
|
||||||
|
| Успешные чтения | 24 | 22 |
|
||||||
|
| Неуспешные попытки чтения | 0 | 0 |
|
||||||
|
| Успешные записи/с | 7,698 | 7,441 |
|
||||||
|
| Время первого восстановления записи, с | 1,583 | 2,965 |
|
||||||
|
|
||||||
|
В обоих сценариях проверялись:
|
||||||
|
|
||||||
|
- фактическая остановка целевого контейнера;
|
||||||
|
- восстановление записи через оставшуюся реплику;
|
||||||
|
- сохранность подтверждённых сообщений;
|
||||||
|
- повтор контрольной операции с прежним результатом;
|
||||||
|
- отсутствие обнаруженных дублей.
|
||||||
|
|
||||||
|
Показатель RPS относится к данному сценарию с паузами
|
||||||
|
и чтениями. Он не является максимальной пропускной способностью.
|
||||||
|
|
||||||
|
Время восстановления включает действия hook
|
||||||
|
и не является изолированным измерением healthcheck HAProxy.
|
||||||
|
|
||||||
|
Доказательства:
|
||||||
|
|
||||||
|
- `evidence/failover-api-1.txt`;
|
||||||
|
- `evidence/failover-api-2.txt`.
|
||||||
|
|
||||||
|
## 11. Конкурентная идемпотентность
|
||||||
|
|
||||||
|
Команда:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 student-tests/concurrent_idempotency.py \
|
||||||
|
--base-url http://localhost:18082
|
||||||
|
```
|
||||||
|
|
||||||
|
Выполнены три раунда по 12 одновременных запросов.
|
||||||
|
|
||||||
|
В каждом раунде наблюдались:
|
||||||
|
|
||||||
|
- 12 ответов 201;
|
||||||
|
- ответы от двух API-реплик;
|
||||||
|
- один уникальный Message ID;
|
||||||
|
- одна соответствующая запись в истории.
|
||||||
|
|
||||||
|
Дополнительно проверялись:
|
||||||
|
|
||||||
|
- конфликт другого текста — 409;
|
||||||
|
- отсутствующий или некорректный ключ — 400;
|
||||||
|
- чужой чат — 404;
|
||||||
|
- независимость области ключей между пользователями и чатами;
|
||||||
|
- повтор с исходным результатом;
|
||||||
|
- отозванная сессия при повторе — 401.
|
||||||
|
|
||||||
|
Итог сценария: PASS.
|
||||||
|
|
||||||
|
Это проверка конкретных конкурентных и негативных сценариев,
|
||||||
|
а не доказательство отсутствия всех возможных гонок.
|
||||||
|
|
||||||
|
Доказательство: `evidence/concurrent-idempotency.txt`.
|
||||||
|
|
||||||
|
## 12. Поочерёдная замена под нагрузкой
|
||||||
|
|
||||||
|
### Гипотеза
|
||||||
|
|
||||||
|
При поочерёдной замене API-контейнеров общие сессии
|
||||||
|
и подтверждённые результаты идемпотентной отправки сохраняются.
|
||||||
|
|
||||||
|
При этом без предварительного drain возможны временные
|
||||||
|
ошибки отдельных запросов.
|
||||||
|
|
||||||
|
### Профиль нагрузки
|
||||||
|
|
||||||
|
Closed-loop POST сообщений:
|
||||||
|
|
||||||
|
- concurrency: 4;
|
||||||
|
- заданная длительность: 90 секунд;
|
||||||
|
- автоматические повторы отключены;
|
||||||
|
- отдельный контролируемый прогрев не задавался.
|
||||||
|
|
||||||
|
Команда:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 tests/load.py \
|
||||||
|
--base-url http://localhost:18082 \
|
||||||
|
--duration 90 \
|
||||||
|
--concurrency 4 \
|
||||||
|
--output evidence/load-during-replacement-repeat.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Параллельно выполнялся сценарий:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 student-tests/rolling_replacement.py \
|
||||||
|
--base-url http://localhost:18082
|
||||||
|
```
|
||||||
|
|
||||||
|
### Временные отметки
|
||||||
|
|
||||||
|
Все времена — UTC, 29 октября 2026 года.
|
||||||
|
|
||||||
|
| Событие | Время |
|
||||||
|
| --- | --- |
|
||||||
|
| Запуск команды нагрузки | 16:50:07 |
|
||||||
|
| Начало сценария замены | 16:50:55 |
|
||||||
|
| Первая новая реплика проверена | 16:51:10 |
|
||||||
|
| Вторая новая реплика проверена | 16:51:28 |
|
||||||
|
| Завершение сценария замены | 16:51:31 |
|
||||||
|
| Завершение команды нагрузки | 16:51:40 |
|
||||||
|
|
||||||
|
Обе замены произошли внутри внешнего интервала запуска
|
||||||
|
генератора. Эти отметки включают подготовку и завершение
|
||||||
|
процесса и не заменяют измеренную генератором длительность.
|
||||||
|
|
||||||
|
### Результаты нагрузки
|
||||||
|
|
||||||
|
| Показатель | Значение |
|
||||||
|
| --- | ---: |
|
||||||
|
| Измеренная длительность | 90,226 с |
|
||||||
|
| Конкурентные клиенты | 4 |
|
||||||
|
| Успешные запросы | 5991 |
|
||||||
|
| Неуспешные запросы | 59 |
|
||||||
|
| Доля ошибок | 0,9752% |
|
||||||
|
| Успешный RPS | 66,4 |
|
||||||
|
| p50 успешных запросов | 44,586 мс |
|
||||||
|
| p95 успешных запросов | 111,2 мс |
|
||||||
|
| p99 успешных запросов | 241,368 мс |
|
||||||
|
|
||||||
|
### Результаты замены
|
||||||
|
|
||||||
|
Первая реплика заменена и проверена за 11,791 секунды.
|
||||||
|
Вторая — за 12,064 секунды.
|
||||||
|
|
||||||
|
Это длительность всего шага, включая создание контейнера,
|
||||||
|
ожидание готовности и проверки, а не длительность
|
||||||
|
недоступности сервиса.
|
||||||
|
|
||||||
|
Сценарий подтвердил для каждого шага:
|
||||||
|
|
||||||
|
- исходный контейнер удалён;
|
||||||
|
- создан новый контейнер с другим Container ID;
|
||||||
|
- изменился X-Instance-Id;
|
||||||
|
- оставшаяся реплика не перезапустилась;
|
||||||
|
- прежняя сессия работает через новую реплику;
|
||||||
|
- повтор контрольной отправки возвращает прежний Message.
|
||||||
|
|
||||||
|
Итог:
|
||||||
|
|
||||||
|
```text
|
||||||
|
PASS: both API containers replaced sequentially;
|
||||||
|
existing session and confirmed message preserved.
|
||||||
|
Код завершения сценария замены: 0
|
||||||
|
```
|
||||||
|
|
||||||
|
После замены работают две новые healthy-реплики:
|
||||||
|
`mtusi2026lab3-api-4` и `mtusi2026lab3-api-5`.
|
||||||
|
|
||||||
|
Доказательства:
|
||||||
|
|
||||||
|
- `evidence/rolling-replacement.txt`;
|
||||||
|
- `evidence/load-window.txt`;
|
||||||
|
- `evidence/load-during-replacement-repeat.json`.
|
||||||
|
|
||||||
|
### Более ранний запуск
|
||||||
|
|
||||||
|
Ранее выполнен ещё один запуск того же профиля:
|
||||||
|
|
||||||
|
| Показатель | Значение |
|
||||||
|
| --- | ---: |
|
||||||
|
| Измеренная длительность | 90,283 с |
|
||||||
|
| Успешные запросы | 7005 |
|
||||||
|
| Неуспешные запросы | 107 |
|
||||||
|
| Доля ошибок | 1,5045% |
|
||||||
|
| Успешный RPS | 77,589 |
|
||||||
|
| p50 | 34,292 мс |
|
||||||
|
| p95 | 111,253 мс |
|
||||||
|
| p99 | 191,745 мс |
|
||||||
|
|
||||||
|
Summary сохранён в `evidence/load-during-replacement.json`.
|
||||||
|
Вывод замены первого запуска также сохранён:
|
||||||
|
`evidence/rolling-replacement-first.txt`.
|
||||||
|
|
||||||
|
Он содержит две успешные замены с длительностями шагов
|
||||||
|
9,198 и 11,641 секунды, итоговый PASS, состояние новых
|
||||||
|
контейнеров и успешный публичный smoke.
|
||||||
|
|
||||||
|
Файл `evidence/rolling-replacement.txt` и временные отметки
|
||||||
|
в `evidence/load-window.txt` относятся к повторному запуску.
|
||||||
|
|
||||||
|
В просмотренной выборке логов этого раннего запуска
|
||||||
|
зафиксировано 107 ответов 503.
|
||||||
|
Показанные состояния SC и sC соответствовали ошибкам
|
||||||
|
и таймаутам подключения HAProxy к backend.
|
||||||
|
|
||||||
|
Индивидуального сопоставления каждого запроса генератора
|
||||||
|
с логом не выполнялось.
|
||||||
|
Причины 59 ошибок повторного запуска отдельно не разбирались.
|
||||||
|
|
||||||
|
Подробный сохранённый вывод замены и `load-window.txt`
|
||||||
|
относятся к повторному запуску, а не к раннему.
|
||||||
|
|
||||||
|
Результаты двух запусков не объединялись.
|
||||||
|
Начальный объём данных и состояние среды строго не выравнивались.
|
||||||
|
Различие RPS не трактуется как доказанное улучшение
|
||||||
|
или ухудшение реализации.
|
||||||
|
|
||||||
|
### Ограничения эксперимента
|
||||||
|
|
||||||
|
- Замена не была безошибочной: генератор получил ошибки.
|
||||||
|
- Проверялась замена с текущим образом, не две версии приложения.
|
||||||
|
- Генератор closed-loop имеет coordinated omission
|
||||||
|
и клиентские накладные расходы.
|
||||||
|
- Процентили относятся только к успешным запросам.
|
||||||
|
- Неуспешная попытка не всегда означает отсутствие записи.
|
||||||
|
- Сохранность каждого успешного ответа генератора отдельно
|
||||||
|
не сверялась с историей.
|
||||||
|
- Контрольное сообщение и сессия проверялись сценарием замены.
|
||||||
|
- Фактические CPU/RAM во время замены не записывались.
|
||||||
|
- Полный начальный размер БД не фиксировался.
|
||||||
|
- Нет серии контролируемых повторов и доверительных интервалов.
|
||||||
|
- Максимальная пропускная способность системы не установлена.
|
||||||
|
|
||||||
|
## 13. Нагрузка без отказов и измерение ресурсов
|
||||||
|
|
||||||
|
Проведён отдельный эксперимент без остановок и замены контейнеров.
|
||||||
|
|
||||||
|
Команда:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 tests/load.py \
|
||||||
|
--base-url http://localhost:18082 \
|
||||||
|
--duration 90 \
|
||||||
|
--concurrency 4 \
|
||||||
|
--output evidence/load-resources.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Внешний интервал запуска команды:
|
||||||
|
29 октября 2026 года, 16:54:26–16:56:00 UTC.
|
||||||
|
|
||||||
|
### Результаты генератора
|
||||||
|
|
||||||
|
| Показатель | Значение |
|
||||||
|
| --- | ---: |
|
||||||
|
| Измеренная длительность | 90,165 с |
|
||||||
|
| Конкурентные клиенты | 4 |
|
||||||
|
| Успешные запросы | 7061 |
|
||||||
|
| Неуспешные запросы | 0 |
|
||||||
|
| Доля ошибок | 0% |
|
||||||
|
| Успешный RPS | 78,312 |
|
||||||
|
| p50 успешных запросов | 37,078 мс |
|
||||||
|
| p95 успешных запросов | 99,704 мс |
|
||||||
|
| p99 успешных запросов | 149,071 мс |
|
||||||
|
|
||||||
|
Код завершения генератора: 0.
|
||||||
|
|
||||||
|
### Сбор ресурсов
|
||||||
|
|
||||||
|
Параллельно сохранены десять снимков `docker stats`.
|
||||||
|
|
||||||
|
Интервал сбора:
|
||||||
|
16:54:33–16:55:47 UTC.
|
||||||
|
|
||||||
|
Все снимки попали внутрь внешнего интервала запуска генератора.
|
||||||
|
Между вызовами задана пауза 5 секунд.
|
||||||
|
Сам вызов также занимает время, поэтому периодичность
|
||||||
|
не является строго пятисекундной.
|
||||||
|
|
||||||
|
| Контейнер | Максимум CPU среди снимков | Максимум памяти среди снимков |
|
||||||
|
| --- | ---: | ---: |
|
||||||
|
| API-4 | 74,05% | 57,2 MiB |
|
||||||
|
| API-5 | 74,03% | 56,45 MiB |
|
||||||
|
| HAProxy | 24,08% | 15,48 MiB |
|
||||||
|
| PostgreSQL | 46,37% | 52,77 MiB |
|
||||||
|
| Redis | 6,98% | 4,844 MiB |
|
||||||
|
|
||||||
|
Максимумы CPU и памяти выбраны отдельно и могут относиться
|
||||||
|
к разным снимкам.
|
||||||
|
|
||||||
|
Приведены показания Docker CPU %, а не процент использования
|
||||||
|
назначенной контейнеру CPU-квоты.
|
||||||
|
|
||||||
|
Это максимальные наблюдавшиеся значения,
|
||||||
|
не гарантированные пики за весь эксперимент.
|
||||||
|
|
||||||
|
Доказательства:
|
||||||
|
|
||||||
|
- `evidence/load-resources.json`;
|
||||||
|
- `evidence/load-resources-window.txt`;
|
||||||
|
- `evidence/resources-under-load.txt`.
|
||||||
|
|
||||||
|
### Ограничения
|
||||||
|
|
||||||
|
- Выполнен один запуск этого сценария.
|
||||||
|
- Начальный размер БД отдельно не фиксировался.
|
||||||
|
- Снимки не покрывают каждую секунду эксперимента.
|
||||||
|
- Сбор ресурсов создаёт дополнительную нагрузку.
|
||||||
|
- Данный результат не доказывает максимальную производительность.
|
||||||
|
- Измерения относятся к нагрузке без отказов,
|
||||||
|
а не к эксперименту замены контейнеров.
|
||||||
|
- Прямое причинное сравнение с другими запусками не выполняется.
|
||||||
|
|
||||||
|
## 14. Публичный smoke после замены
|
||||||
|
|
||||||
|
Команда:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make test BASE_URL=http://localhost:18082
|
||||||
|
```
|
||||||
|
|
||||||
|
Время запуска:
|
||||||
|
29 октября 2026 года, 16:53:33 UTC.
|
||||||
|
|
||||||
|
Результат:
|
||||||
|
|
||||||
|
```text
|
||||||
|
PASS: lab3 public API scenario;
|
||||||
|
infrastructure and grading evidence remain separate.
|
||||||
|
Код завершения make: 0
|
||||||
|
```
|
||||||
|
|
||||||
|
Публичный API-сценарий работает после поочерёдной замены
|
||||||
|
обеих исходных реплик.
|
||||||
|
|
||||||
|
Доказательство: `evidence/smoke-after-replacement.txt`.
|
||||||
|
|
||||||
|
## 15. Сводка отказов и воздействий
|
||||||
|
|
||||||
|
| Воздействие | Ожидание | Наблюдение | Восстановление и данные |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| Перезапуск API, БД, Redis и LB | Сохранить проверенные данные и сессию | Persistence PASS, StartedAt изменился у всех перечисленных компонентов | Проверенные данные и существующая сессия сохранились |
|
||||||
|
| Остановка первой API-реплики | Запись восстановится через оставшуюся | Targeted failover PASS | Первое восстановление 1,583 с; контрольные данные сохранены |
|
||||||
|
| Остановка второй API-реплики | Аналогичное восстановление | Targeted failover PASS | Первое восстановление 2,965 с; контрольные данные сохранены |
|
||||||
|
| Конкурентные запросы с одним ключом | Один Message в области ключа | Три раунда по 12 запросов | В каждом раунде один Message |
|
||||||
|
| Поочерёдная замена под нагрузкой | Сохранить сессию и контрольный Message | Rolling PASS, обе новые реплики healthy | Шаги 11,791 и 12,064 с; 59 ошибок генератора |
|
||||||
|
| Нагрузка без отказов | Измерить работу и ресурсы | 7061 успешный запрос, 0 ошибок | 78,312 успешного запроса/с; сохранены снимки CPU/RAM |
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## 16. Команды повторения проверок
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
Публичный smoke:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make test BASE_URL=http://localhost:18082
|
||||||
|
```
|
||||||
|
|
||||||
|
Persistence с инфраструктурным hook:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make test-persistence \
|
||||||
|
BASE_URL=http://localhost:18082 \
|
||||||
|
ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Публичный failover-сценарий:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make test-failover \
|
||||||
|
BASE_URL=http://localhost:18082 \
|
||||||
|
ACTION_SCRIPT=scripts/stop-one.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Конкурентная идемпотентность:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 student-tests/concurrent_idempotency.py \
|
||||||
|
--base-url http://localhost:18082
|
||||||
|
```
|
||||||
|
|
||||||
|
Собственный targeted failover:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 student-tests/targeted_failover.py \
|
||||||
|
--base-url http://localhost:18082 \
|
||||||
|
--target-container ACTUAL_API_CONTAINER_NAME
|
||||||
|
```
|
||||||
|
|
||||||
|
Актуальное имя контейнера получить перед запуском:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -p mtusi2026lab3 ps -a
|
||||||
|
```
|
||||||
|
|
||||||
|
После targeted failover восстановить остановленную реплику
|
||||||
|
перед следующим экспериментом:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -p mtusi2026lab3 start api
|
||||||
|
```
|
||||||
|
|
||||||
|
Поочерёдная замена:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 student-tests/rolling_replacement.py \
|
||||||
|
--base-url http://localhost:18082
|
||||||
|
```
|
||||||
|
|
||||||
|
Hooks должны быть исполняемыми.
|
||||||
|
Тесты создают синтетические данные.
|
||||||
|
Независимые сценарии отказов не запускаются одновременно.
|
||||||
|
В эксперименте замены параллельно запускается только
|
||||||
|
предусмотренная нагрузка.
|
||||||
|
|
||||||
|
## 17. Ограничения и следующие шаги
|
||||||
|
|
||||||
|
### Ограничения архитектуры
|
||||||
|
|
||||||
|
- Все сервисы находятся на одном Docker-host.
|
||||||
|
- Потеря всего узла не выдерживается.
|
||||||
|
- PostgreSQL, Redis и HAProxy не реплицированы.
|
||||||
|
- Высокая доступность БД и балансировщика не заявляется.
|
||||||
|
- HTTPS в локальном стенде не настроен.
|
||||||
|
- Используются синтетические пользователи и учебные данные.
|
||||||
|
- Rate limiting и защита от cache stampede не реализованы.
|
||||||
|
- Автоматической очистки ключей идемпотентности нет.
|
||||||
|
- Непустые вложения не реализованы.
|
||||||
|
- Предварительный drain API перед остановкой не реализован.
|
||||||
|
- Совместимость двух версий приложения при изменении схемы
|
||||||
|
не проверялась.
|
||||||
|
|
||||||
|
### Ограничения доказательств
|
||||||
|
|
||||||
|
- Чистый запуск из отдельного clone с новыми volumes
|
||||||
|
ещё не проверен.
|
||||||
|
- Ресурсы измерены под обычной нагрузкой,
|
||||||
|
но не во время замены.
|
||||||
|
- Размер и состояние БД перед разными запусками
|
||||||
|
строго не выравнивались.
|
||||||
|
- Доверительные интервалы не рассчитывались.
|
||||||
|
- Результаты не являются доказательством
|
||||||
|
максимальной производительности.
|
||||||
|
- Уровень 5 не заявляется.
|
||||||
|
|
||||||
|
## 18. Использованные материалы и библиотеки
|
||||||
|
|
||||||
|
- README, контракт и публичные тесты skeleton лабораторной 3.
|
||||||
|
- Собственная реализация лабораторной 2.
|
||||||
|
- Docker и Docker Compose.
|
||||||
|
- PostgreSQL.
|
||||||
|
- Redis.
|
||||||
|
- HAProxy.
|
||||||
|
- FastAPI и Uvicorn.
|
||||||
|
- Psycopg.
|
||||||
|
- argon2-cffi.
|
||||||
|
- Стандартная библиотека Python для собственных сценариев.
|
||||||
|
|
||||||
|
Точные версии зависимостей указаны в `requirements.txt`,
|
||||||
|
образы и параметры запуска — в Dockerfile и `compose.yaml`.
|
||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
from argon2 import PasswordHasher, Type
|
||||||
|
from argon2.exceptions import VerificationError
|
||||||
|
from starlette.concurrency import run_in_threadpool
|
||||||
|
|
||||||
|
|
||||||
|
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}", re.ASCII)
|
||||||
|
|
||||||
|
password_hasher = PasswordHasher(
|
||||||
|
time_cost=3,
|
||||||
|
memory_cost=65536,
|
||||||
|
parallelism=4,
|
||||||
|
hash_len=32,
|
||||||
|
salt_len=16,
|
||||||
|
type=Type.ID,
|
||||||
|
)
|
||||||
|
|
||||||
|
DUMMY_PASSWORD_HASH = password_hasher.hash(
|
||||||
|
secrets.token_urlsafe(32)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def hash_password(password: str) -> str:
|
||||||
|
return await run_in_threadpool(
|
||||||
|
password_hasher.hash,
|
||||||
|
password,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def verify_password(
|
||||||
|
password_hash: str,
|
||||||
|
password: str,
|
||||||
|
) -> bool:
|
||||||
|
try:
|
||||||
|
return await run_in_threadpool(
|
||||||
|
password_hasher.verify,
|
||||||
|
password_hash,
|
||||||
|
password,
|
||||||
|
)
|
||||||
|
except VerificationError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def parse_basic_credentials(
|
||||||
|
authorization: str | None,
|
||||||
|
) -> tuple[str, str] | None:
|
||||||
|
if authorization is None or len(authorization) > 2048:
|
||||||
|
return None
|
||||||
|
|
||||||
|
parts = authorization.split()
|
||||||
|
|
||||||
|
if len(parts) != 2 or parts[0].lower() != "basic":
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
decoded = base64.b64decode(
|
||||||
|
parts[1],
|
||||||
|
validate=True,
|
||||||
|
).decode("utf-8")
|
||||||
|
except (binascii.Error, UnicodeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
username, separator, password = decoded.partition(":")
|
||||||
|
|
||||||
|
if not separator:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if USERNAME_RE.fullmatch(username) is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not 12 <= len(password) <= 128:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return username, password
|
||||||
|
|
||||||
|
|
||||||
|
def parse_bearer_token(
|
||||||
|
authorization: str | None,
|
||||||
|
) -> str | None:
|
||||||
|
if authorization is None or len(authorization) > 2048:
|
||||||
|
return None
|
||||||
|
|
||||||
|
parts = authorization.split()
|
||||||
|
|
||||||
|
if len(parts) != 2 or parts[0].lower() != "bearer":
|
||||||
|
return None
|
||||||
|
|
||||||
|
token = parts[1]
|
||||||
|
|
||||||
|
if re.fullmatch(r"[A-Za-z0-9_-]{43}", token) is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def generate_token() -> str:
|
||||||
|
return secrets.token_urlsafe(32)
|
||||||
|
|
||||||
|
|
||||||
|
def hash_token(token: str) -> str:
|
||||||
|
return hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||||
+129
@@ -0,0 +1,129 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from redis.asyncio import Redis
|
||||||
|
from redis.exceptions import RedisError
|
||||||
|
|
||||||
|
from app.store import store
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger("messenger.cache")
|
||||||
|
|
||||||
|
CACHE_TTL_SECONDS = int(
|
||||||
|
os.getenv("USER_CACHE_TTL_SECONDS", "60")
|
||||||
|
)
|
||||||
|
|
||||||
|
if not 1 <= CACHE_TTL_SECONDS <= 3600:
|
||||||
|
raise ValueError(
|
||||||
|
"USER_CACHE_TTL_SECONDS must be between 1 and 3600"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
redis_client = Redis(
|
||||||
|
host=os.getenv("REDIS_HOST", "redis"),
|
||||||
|
port=int(os.getenv("REDIS_PORT", "6379")),
|
||||||
|
decode_responses=True,
|
||||||
|
socket_connect_timeout=0.2,
|
||||||
|
socket_timeout=0.2,
|
||||||
|
retry_on_timeout=False,
|
||||||
|
max_connections=10,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def serialize_user(user: dict) -> str:
|
||||||
|
created_at = user["created_at"]
|
||||||
|
|
||||||
|
return json.dumps(
|
||||||
|
{
|
||||||
|
"id": str(user["id"]),
|
||||||
|
"username": user["username"],
|
||||||
|
"display_name": user["display_name"],
|
||||||
|
"created_at": created_at.astimezone(
|
||||||
|
timezone.utc
|
||||||
|
).isoformat().replace("+00:00", "Z"),
|
||||||
|
},
|
||||||
|
ensure_ascii=False,
|
||||||
|
separators=(",", ":"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def deserialize_user(
|
||||||
|
raw: str,
|
||||||
|
expected_id: UUID,
|
||||||
|
) -> dict:
|
||||||
|
data = json.loads(raw)
|
||||||
|
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise ValueError("Invalid cached user")
|
||||||
|
|
||||||
|
expected_fields = {
|
||||||
|
"id",
|
||||||
|
"username",
|
||||||
|
"display_name",
|
||||||
|
"created_at",
|
||||||
|
}
|
||||||
|
|
||||||
|
if set(data) != expected_fields:
|
||||||
|
raise ValueError("Invalid cached user fields")
|
||||||
|
|
||||||
|
if not all(isinstance(value, str) for value in data.values()):
|
||||||
|
raise ValueError("Invalid cached user types")
|
||||||
|
|
||||||
|
user_id = UUID(data["id"])
|
||||||
|
|
||||||
|
if user_id != expected_id:
|
||||||
|
raise ValueError("Cached user ID mismatch")
|
||||||
|
|
||||||
|
created_at = datetime.fromisoformat(
|
||||||
|
data["created_at"].replace("Z", "+00:00")
|
||||||
|
)
|
||||||
|
|
||||||
|
if created_at.tzinfo is None:
|
||||||
|
raise ValueError("Cached timestamp has no timezone")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": user_id,
|
||||||
|
"username": data["username"],
|
||||||
|
"display_name": data["display_name"],
|
||||||
|
"created_at": created_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def get_cached_user(user_id: UUID) -> dict | None:
|
||||||
|
key = f"user:v1:{user_id}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
raw = await redis_client.get(key)
|
||||||
|
|
||||||
|
if raw is not None:
|
||||||
|
return deserialize_user(raw, user_id)
|
||||||
|
|
||||||
|
except RedisError:
|
||||||
|
logger.warning("User cache read unavailable")
|
||||||
|
except (ValueError, TypeError, OverflowError):
|
||||||
|
logger.warning("Invalid user cache entry ignored")
|
||||||
|
|
||||||
|
user = await store.get_user(user_id)
|
||||||
|
|
||||||
|
if user is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
await redis_client.set(
|
||||||
|
key,
|
||||||
|
serialize_user(user),
|
||||||
|
ex=CACHE_TTL_SECONDS,
|
||||||
|
)
|
||||||
|
except RedisError:
|
||||||
|
logger.warning("User cache write unavailable")
|
||||||
|
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
async def close_cache() -> None:
|
||||||
|
await redis_client.aclose()
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
|
||||||
|
SESSION_TTL_SECONDS = int(
|
||||||
|
os.getenv("SESSION_TTL_SECONDS", "3600")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if SESSION_TTL_SECONDS < 1:
|
||||||
|
raise ValueError("SESSION_TTL_SECONDS must be positive")
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg_pool import AsyncConnectionPool
|
||||||
|
|
||||||
|
|
||||||
|
pool = AsyncConnectionPool(
|
||||||
|
conninfo="",
|
||||||
|
kwargs={
|
||||||
|
"host": os.getenv("PGHOST", "postgres"),
|
||||||
|
"port": int(os.getenv("PGPORT", "5432")),
|
||||||
|
"dbname": os.getenv("PGDATABASE", "messenger"),
|
||||||
|
"user": os.getenv("PGUSER", "messenger"),
|
||||||
|
"password": os.environ.get("PGPASSWORD", ""),
|
||||||
|
"connect_timeout": 3,
|
||||||
|
"options": (
|
||||||
|
"-c statement_timeout=3000 "
|
||||||
|
"-c lock_timeout=2000 "
|
||||||
|
"-c idle_in_transaction_session_timeout=10000"
|
||||||
|
),
|
||||||
|
"row_factory": dict_row,
|
||||||
|
},
|
||||||
|
min_size=1,
|
||||||
|
max_size=5,
|
||||||
|
timeout=3,
|
||||||
|
max_waiting=20,
|
||||||
|
open=False,
|
||||||
|
check=AsyncConnectionPool.check_connection,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def open_db() -> None:
|
||||||
|
await pool.open(wait=True, timeout=10)
|
||||||
|
|
||||||
|
|
||||||
|
async def close_db() -> None:
|
||||||
|
await pool.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def check_db() -> None:
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
await conn.execute("SELECT 1")
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import Request
|
||||||
|
|
||||||
|
from app.auth import hash_token, parse_bearer_token
|
||||||
|
from app.cache import get_cached_user
|
||||||
|
from app.errors import not_found, unauthorized
|
||||||
|
from app.store import store
|
||||||
|
from app.validation import parse_uuid
|
||||||
|
|
||||||
|
|
||||||
|
async def current_user(request: Request) -> tuple[dict, str]:
|
||||||
|
token = parse_bearer_token(
|
||||||
|
request.headers.get("authorization")
|
||||||
|
)
|
||||||
|
|
||||||
|
if token is None:
|
||||||
|
raise unauthorized()
|
||||||
|
|
||||||
|
token_digest = hash_token(token)
|
||||||
|
|
||||||
|
user_id = await store.get_session_user_id(token_digest)
|
||||||
|
|
||||||
|
if user_id is None:
|
||||||
|
raise unauthorized()
|
||||||
|
|
||||||
|
user = await get_cached_user(user_id)
|
||||||
|
|
||||||
|
if user is None:
|
||||||
|
raise unauthorized()
|
||||||
|
|
||||||
|
return user, token_digest
|
||||||
|
|
||||||
|
|
||||||
|
async def accessible_chat(
|
||||||
|
raw_chat_id: str,
|
||||||
|
user_id: UUID,
|
||||||
|
) -> tuple[UUID, dict]:
|
||||||
|
chat_id = parse_uuid(raw_chat_id)
|
||||||
|
|
||||||
|
chat = await store.get_accessible_chat(chat_id, user_id)
|
||||||
|
|
||||||
|
if chat is None:
|
||||||
|
raise not_found()
|
||||||
|
|
||||||
|
return chat_id, chat
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from fastapi import Request
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
|
||||||
|
class ApiError(Exception):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
status: int,
|
||||||
|
code: str,
|
||||||
|
message: str,
|
||||||
|
challenge: str | None = None,
|
||||||
|
):
|
||||||
|
super().__init__(message)
|
||||||
|
self.status = status
|
||||||
|
self.code = code
|
||||||
|
self.message = message
|
||||||
|
self.challenge = challenge
|
||||||
|
|
||||||
|
|
||||||
|
def invalid(message: str = "Некорректный запрос") -> ApiError:
|
||||||
|
return ApiError(400, "invalid_request", message)
|
||||||
|
|
||||||
|
|
||||||
|
def unauthorized(scheme: str = "Bearer") -> ApiError:
|
||||||
|
if scheme == "Basic":
|
||||||
|
challenge = 'Basic realm="messenger", charset="UTF-8"'
|
||||||
|
else:
|
||||||
|
challenge = 'Bearer realm="messenger"'
|
||||||
|
|
||||||
|
return ApiError(
|
||||||
|
401,
|
||||||
|
"unauthorized",
|
||||||
|
"Недействительная аутентификация",
|
||||||
|
challenge,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def not_found() -> ApiError:
|
||||||
|
return ApiError(404, "not_found", "Объект не найден")
|
||||||
|
|
||||||
|
|
||||||
|
def error_response(
|
||||||
|
request: Request,
|
||||||
|
error: ApiError,
|
||||||
|
) -> JSONResponse:
|
||||||
|
request_id = getattr(
|
||||||
|
request.state,
|
||||||
|
"request_id",
|
||||||
|
str(uuid4()),
|
||||||
|
)
|
||||||
|
|
||||||
|
headers = {"X-Request-Id": request_id}
|
||||||
|
|
||||||
|
if error.challenge is not None:
|
||||||
|
headers["WWW-Authenticate"] = error.challenge
|
||||||
|
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=error.status,
|
||||||
|
content={
|
||||||
|
"error": {
|
||||||
|
"code": error.code,
|
||||||
|
"message": error.message,
|
||||||
|
"request_id": request_id,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
from app.db import pool
|
||||||
|
from app.errors import ApiError
|
||||||
|
|
||||||
|
|
||||||
|
async def create_message_once(
|
||||||
|
chat_id: UUID,
|
||||||
|
sender_id: UUID,
|
||||||
|
text: str,
|
||||||
|
key: str,
|
||||||
|
) -> dict:
|
||||||
|
scope = json.dumps(
|
||||||
|
[
|
||||||
|
str(sender_id),
|
||||||
|
"POST",
|
||||||
|
f"/api/v1/chats/{chat_id}/messages",
|
||||||
|
key,
|
||||||
|
],
|
||||||
|
separators=(",", ":"),
|
||||||
|
)
|
||||||
|
|
||||||
|
lock_id = int.from_bytes(
|
||||||
|
hashlib.sha256(scope.encode("utf-8")).digest()[:8],
|
||||||
|
byteorder="big",
|
||||||
|
signed=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
await conn.execute(
|
||||||
|
"SELECT pg_advisory_xact_lock(%s)",
|
||||||
|
(lock_id,),
|
||||||
|
)
|
||||||
|
|
||||||
|
cursor = await conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT i.request_text,
|
||||||
|
m.id, m.chat_id, m.sender_id,
|
||||||
|
m.text, m.created_at
|
||||||
|
FROM message_idempotency AS i
|
||||||
|
JOIN messages AS m ON m.id = i.message_id
|
||||||
|
WHERE i.user_id = %s
|
||||||
|
AND i.chat_id = %s
|
||||||
|
AND i.http_method = 'POST'
|
||||||
|
AND i.idempotency_key = %s
|
||||||
|
""",
|
||||||
|
(sender_id, chat_id, key),
|
||||||
|
)
|
||||||
|
previous = await cursor.fetchone()
|
||||||
|
|
||||||
|
if previous is not None:
|
||||||
|
if previous["request_text"] != text:
|
||||||
|
raise ApiError(
|
||||||
|
409,
|
||||||
|
"conflict",
|
||||||
|
"Ключ уже использован с другим сообщением",
|
||||||
|
)
|
||||||
|
|
||||||
|
message = {
|
||||||
|
field: previous[field]
|
||||||
|
for field in (
|
||||||
|
"id",
|
||||||
|
"chat_id",
|
||||||
|
"sender_id",
|
||||||
|
"text",
|
||||||
|
"created_at",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO messages (
|
||||||
|
id, chat_id, sender_id, text
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
RETURNING id, chat_id, sender_id,
|
||||||
|
text, created_at
|
||||||
|
""",
|
||||||
|
(uuid4(), chat_id, sender_id, text),
|
||||||
|
)
|
||||||
|
message = await cursor.fetchone()
|
||||||
|
|
||||||
|
await conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO message_idempotency (
|
||||||
|
user_id,
|
||||||
|
chat_id,
|
||||||
|
http_method,
|
||||||
|
idempotency_key,
|
||||||
|
request_text,
|
||||||
|
message_id
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, 'POST', %s, %s, %s)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
sender_id,
|
||||||
|
chat_id,
|
||||||
|
key,
|
||||||
|
text,
|
||||||
|
message["id"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
return message
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import socket
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
|
||||||
|
INSTANCE_ID = f"{socket.gethostname()}:{uuid4().hex[:12]}"
|
||||||
+114
@@ -0,0 +1,114 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from psycopg import InterfaceError, OperationalError
|
||||||
|
from psycopg.errors import LockNotAvailable, QueryCanceled
|
||||||
|
from psycopg_pool import PoolTimeout, TooManyRequests
|
||||||
|
from starlette.exceptions import HTTPException
|
||||||
|
|
||||||
|
from app.cache import close_cache
|
||||||
|
from app.instance import INSTANCE_ID
|
||||||
|
from app.db import close_db, open_db
|
||||||
|
from app.errors import ApiError, error_response, invalid, not_found
|
||||||
|
from app.routers import chats, health, messages, sessions, users
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger("messenger.api")
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
try:
|
||||||
|
await open_db()
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
await close_cache()
|
||||||
|
await close_db()
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="Replicated PostgreSQL messenger — Lab 3",
|
||||||
|
docs_url=None,
|
||||||
|
redoc_url=None,
|
||||||
|
openapi_url=None,
|
||||||
|
lifespan=lifespan,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.middleware("http")
|
||||||
|
async def request_middleware(request: Request, call_next):
|
||||||
|
request.state.request_id = str(uuid4())
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = await call_next(request)
|
||||||
|
|
||||||
|
except ApiError as exc:
|
||||||
|
response = error_response(request, exc)
|
||||||
|
|
||||||
|
except (
|
||||||
|
OperationalError,
|
||||||
|
InterfaceError,
|
||||||
|
PoolTimeout,
|
||||||
|
TooManyRequests,
|
||||||
|
QueryCanceled,
|
||||||
|
LockNotAvailable,
|
||||||
|
) as exc:
|
||||||
|
logger.warning(
|
||||||
|
"Database unavailable request_id=%s error_type=%s",
|
||||||
|
request.state.request_id,
|
||||||
|
type(exc).__name__,
|
||||||
|
)
|
||||||
|
response = error_response(
|
||||||
|
request,
|
||||||
|
ApiError(
|
||||||
|
503,
|
||||||
|
"unavailable",
|
||||||
|
"Сервис временно недоступен",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error(
|
||||||
|
"Unhandled error request_id=%s error_type=%s",
|
||||||
|
request.state.request_id,
|
||||||
|
type(exc).__name__,
|
||||||
|
)
|
||||||
|
response = error_response(
|
||||||
|
request,
|
||||||
|
ApiError(
|
||||||
|
500,
|
||||||
|
"internal_error",
|
||||||
|
"Внутренняя ошибка сервера",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
response.headers["X-Request-Id"] = request.state.request_id
|
||||||
|
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(RequestValidationError)
|
||||||
|
async def validation_error_handler(request: Request, exc):
|
||||||
|
return error_response(request, invalid())
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(HTTPException)
|
||||||
|
async def http_error_handler(request: Request, exc: HTTPException):
|
||||||
|
if exc.status_code == 404:
|
||||||
|
error = not_found()
|
||||||
|
else:
|
||||||
|
error = invalid("Недопустимый HTTP-запрос")
|
||||||
|
|
||||||
|
return error_response(request, error)
|
||||||
|
|
||||||
|
|
||||||
|
app.include_router(health.router)
|
||||||
|
app.include_router(users.router)
|
||||||
|
app.include_router(sessions.router)
|
||||||
|
app.include_router(chats.router)
|
||||||
|
app.include_router(messages.router)
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
|
||||||
|
|
||||||
|
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
|
||||||
|
MIGRATION_LOCK_ID = 202602001
|
||||||
|
|
||||||
|
|
||||||
|
def apply_migrations() -> None:
|
||||||
|
files = sorted(MIGRATIONS_DIR.glob("[0-9]*_*.sql"))
|
||||||
|
|
||||||
|
if not files:
|
||||||
|
raise RuntimeError("Migration files not found")
|
||||||
|
|
||||||
|
with psycopg.connect(
|
||||||
|
host=os.getenv("PGHOST", "postgres"),
|
||||||
|
port=int(os.getenv("PGPORT", "5432")),
|
||||||
|
dbname=os.getenv("PGDATABASE", "messenger"),
|
||||||
|
user=os.getenv("PGUSER", "messenger"),
|
||||||
|
password=os.environ["PGPASSWORD"],
|
||||||
|
connect_timeout=5,
|
||||||
|
options="-c statement_timeout=30000 -c lock_timeout=10000",
|
||||||
|
) as conn:
|
||||||
|
conn.execute(
|
||||||
|
"SELECT pg_advisory_xact_lock(%s)",
|
||||||
|
(MIGRATION_LOCK_ID,),
|
||||||
|
)
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version TEXT PRIMARY KEY,
|
||||||
|
checksum TEXT NOT NULL,
|
||||||
|
applied_at TIMESTAMPTZ NOT NULL
|
||||||
|
DEFAULT clock_timestamp()
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
for path in files:
|
||||||
|
version = path.name
|
||||||
|
content = path.read_bytes()
|
||||||
|
checksum = hashlib.sha256(content).hexdigest()
|
||||||
|
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT checksum
|
||||||
|
FROM schema_migrations
|
||||||
|
WHERE version = %s
|
||||||
|
""",
|
||||||
|
(version,),
|
||||||
|
).fetchone()
|
||||||
|
|
||||||
|
if row is not None:
|
||||||
|
if row[0] != checksum:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Applied migration was modified: {version}"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"Already applied: {version}", flush=True)
|
||||||
|
continue
|
||||||
|
|
||||||
|
conn.execute(content.decode("utf-8"), prepare=False)
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO schema_migrations (version, checksum)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
""",
|
||||||
|
(version, checksum),
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"Executed: {version} (pending commit)", flush=True)
|
||||||
|
|
||||||
|
print("Migrations committed successfully", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
apply_migrations()
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import Request
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
from app.errors import invalid
|
||||||
|
from app.responses import json_response, utc_text
|
||||||
|
|
||||||
|
|
||||||
|
def encode_cursor(scope: str, item: dict) -> str:
|
||||||
|
raw = json.dumps(
|
||||||
|
{
|
||||||
|
"scope": scope,
|
||||||
|
"created_at": utc_text(item["created_at"]),
|
||||||
|
"id": str(item["id"]),
|
||||||
|
},
|
||||||
|
separators=(",", ":"),
|
||||||
|
).encode("utf-8")
|
||||||
|
|
||||||
|
return (
|
||||||
|
base64.urlsafe_b64encode(raw)
|
||||||
|
.decode("ascii")
|
||||||
|
.rstrip("=")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def decode_cursor(
|
||||||
|
cursor: str,
|
||||||
|
scope: str,
|
||||||
|
) -> tuple[datetime, UUID]:
|
||||||
|
if not cursor or len(cursor) > 2048:
|
||||||
|
raise invalid("Некорректный cursor")
|
||||||
|
|
||||||
|
try:
|
||||||
|
padded = cursor + "=" * (-len(cursor) % 4)
|
||||||
|
|
||||||
|
raw = base64.b64decode(
|
||||||
|
padded,
|
||||||
|
altchars=b"-_",
|
||||||
|
validate=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
data = json.loads(raw.decode("utf-8"))
|
||||||
|
|
||||||
|
if (
|
||||||
|
not isinstance(data, dict)
|
||||||
|
or set(data) != {"scope", "created_at", "id"}
|
||||||
|
or data["scope"] != scope
|
||||||
|
):
|
||||||
|
raise ValueError
|
||||||
|
|
||||||
|
timestamp = data["created_at"]
|
||||||
|
|
||||||
|
if (
|
||||||
|
not isinstance(timestamp, str)
|
||||||
|
or not timestamp.endswith("Z")
|
||||||
|
or not isinstance(data["id"], str)
|
||||||
|
):
|
||||||
|
raise ValueError
|
||||||
|
|
||||||
|
created_at = datetime.fromisoformat(
|
||||||
|
timestamp[:-1] + "+00:00"
|
||||||
|
)
|
||||||
|
|
||||||
|
item_id = UUID(data["id"])
|
||||||
|
|
||||||
|
return created_at, item_id
|
||||||
|
|
||||||
|
except (
|
||||||
|
ValueError,
|
||||||
|
TypeError,
|
||||||
|
UnicodeError,
|
||||||
|
binascii.Error,
|
||||||
|
OverflowError,
|
||||||
|
):
|
||||||
|
raise invalid("Некорректный cursor") from None
|
||||||
|
|
||||||
|
|
||||||
|
def pagination(
|
||||||
|
request: Request,
|
||||||
|
scope: str,
|
||||||
|
) -> tuple[int, tuple[datetime, UUID] | None]:
|
||||||
|
raw_limit = request.query_params.get("limit", "50")
|
||||||
|
|
||||||
|
if (
|
||||||
|
len(raw_limit) > 10
|
||||||
|
or re.fullmatch(r"[0-9]+", raw_limit) is None
|
||||||
|
):
|
||||||
|
raise invalid("Некорректный limit")
|
||||||
|
|
||||||
|
limit = int(raw_limit)
|
||||||
|
|
||||||
|
if not 1 <= limit <= 100:
|
||||||
|
raise invalid("Некорректный limit")
|
||||||
|
|
||||||
|
raw_cursor = request.query_params.get("cursor")
|
||||||
|
after = None
|
||||||
|
|
||||||
|
if raw_cursor is not None:
|
||||||
|
after = decode_cursor(raw_cursor, scope)
|
||||||
|
|
||||||
|
return limit, after
|
||||||
|
|
||||||
|
|
||||||
|
def page_response(
|
||||||
|
rows: list[dict],
|
||||||
|
limit: int,
|
||||||
|
scope: str,
|
||||||
|
) -> JSONResponse:
|
||||||
|
items = rows[:limit]
|
||||||
|
next_cursor = None
|
||||||
|
|
||||||
|
if len(rows) > limit:
|
||||||
|
next_cursor = encode_cursor(scope, items[-1])
|
||||||
|
|
||||||
|
return json_response(
|
||||||
|
{
|
||||||
|
"items": items,
|
||||||
|
"next_cursor": next_cursor,
|
||||||
|
}
|
||||||
|
)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
|
||||||
|
def utc_text(value: datetime) -> str:
|
||||||
|
return (
|
||||||
|
value.astimezone(timezone.utc)
|
||||||
|
.isoformat(timespec="microseconds")
|
||||||
|
.replace("+00:00", "Z")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def to_json(value):
|
||||||
|
if isinstance(value, UUID):
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return utc_text(value)
|
||||||
|
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return {
|
||||||
|
key: to_json(item)
|
||||||
|
for key, item in value.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
if isinstance(value, (list, tuple)):
|
||||||
|
return [to_json(item) for item in value]
|
||||||
|
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def json_response(value, status: int = 200) -> JSONResponse:
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=status,
|
||||||
|
content=to_json(value),
|
||||||
|
)
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Request
|
||||||
|
|
||||||
|
from app.dependencies import accessible_chat, current_user
|
||||||
|
from app.errors import invalid
|
||||||
|
from app.pagination import page_response, pagination
|
||||||
|
from app.responses import json_response
|
||||||
|
from app.store import InvalidMembersError, store
|
||||||
|
from app.validation import parse_uuid, read_payload, valid_text
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/v1/chats")
|
||||||
|
async def create_chat(request: Request):
|
||||||
|
user, _ = await current_user(request)
|
||||||
|
|
||||||
|
payload = await read_payload(
|
||||||
|
request,
|
||||||
|
{"title", "member_ids"},
|
||||||
|
)
|
||||||
|
|
||||||
|
if not valid_text(payload["title"], 100):
|
||||||
|
raise invalid("Некорректный title")
|
||||||
|
|
||||||
|
raw_members = payload["member_ids"]
|
||||||
|
|
||||||
|
if (
|
||||||
|
not isinstance(raw_members, list)
|
||||||
|
or not 1 <= len(raw_members) <= 100
|
||||||
|
):
|
||||||
|
raise invalid("Некорректный member_ids")
|
||||||
|
|
||||||
|
member_ids = [parse_uuid(item) for item in raw_members]
|
||||||
|
|
||||||
|
if len(set(member_ids)) != len(member_ids):
|
||||||
|
raise invalid("В member_ids есть дубликаты")
|
||||||
|
|
||||||
|
if user["id"] not in member_ids:
|
||||||
|
raise invalid("Создатель должен входить в member_ids")
|
||||||
|
|
||||||
|
try:
|
||||||
|
chat = await store.create_chat(
|
||||||
|
payload["title"],
|
||||||
|
member_ids,
|
||||||
|
)
|
||||||
|
except InvalidMembersError:
|
||||||
|
raise invalid(
|
||||||
|
"В member_ids есть неизвестный пользователь"
|
||||||
|
) from None
|
||||||
|
|
||||||
|
return json_response(chat, 201)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/v1/chats")
|
||||||
|
async def list_chats(request: Request):
|
||||||
|
user, _ = await current_user(request)
|
||||||
|
|
||||||
|
scope = f"chats:{user['id']}"
|
||||||
|
limit, after = pagination(request, scope)
|
||||||
|
|
||||||
|
rows = await store.list_chats(user["id"], limit, after)
|
||||||
|
|
||||||
|
return page_response(rows, limit, scope)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/v1/chats/{chat_id}")
|
||||||
|
async def get_chat(chat_id: str, request: Request):
|
||||||
|
user, _ = await current_user(request)
|
||||||
|
|
||||||
|
_, chat = await accessible_chat(chat_id, user["id"])
|
||||||
|
|
||||||
|
return json_response(chat)
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.db import check_db
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health/live")
|
||||||
|
async def health_live():
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health/ready")
|
||||||
|
async def health_ready():
|
||||||
|
await check_db()
|
||||||
|
return {"status": "ok"}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Request
|
||||||
|
|
||||||
|
from app.dependencies import accessible_chat, current_user
|
||||||
|
from app.errors import invalid
|
||||||
|
from app.idempotency import create_message_once
|
||||||
|
from app.pagination import page_response, pagination
|
||||||
|
from app.responses import json_response
|
||||||
|
from app.store import store
|
||||||
|
from app.validation import read_payload, valid_text
|
||||||
|
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}", re.ASCII)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/v1/chats/{chat_id}/messages")
|
||||||
|
async def create_message(chat_id: str, request: Request):
|
||||||
|
user, _ = await current_user(request)
|
||||||
|
|
||||||
|
chat_uuid, _ = await accessible_chat(
|
||||||
|
chat_id,
|
||||||
|
user["id"],
|
||||||
|
)
|
||||||
|
|
||||||
|
keys = request.headers.getlist("idempotency-key")
|
||||||
|
if len(keys) != 1 or KEY_RE.fullmatch(keys[0]) is None:
|
||||||
|
raise invalid("Требуется корректный Idempotency-Key")
|
||||||
|
|
||||||
|
payload = await read_payload(
|
||||||
|
request,
|
||||||
|
{"text"},
|
||||||
|
optional_fields={"attachment_ids"},
|
||||||
|
)
|
||||||
|
|
||||||
|
if not valid_text(payload["text"], 4000):
|
||||||
|
raise invalid("Некорректный текст сообщения")
|
||||||
|
|
||||||
|
attachments = payload.get("attachment_ids", [])
|
||||||
|
if not isinstance(attachments, list) or attachments:
|
||||||
|
raise invalid("В ЛР 3 поддерживаются сообщения без вложений")
|
||||||
|
|
||||||
|
message = await create_message_once(
|
||||||
|
chat_uuid,
|
||||||
|
user["id"],
|
||||||
|
payload["text"],
|
||||||
|
keys[0],
|
||||||
|
)
|
||||||
|
|
||||||
|
return json_response(message, 201)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/v1/chats/{chat_id}/messages")
|
||||||
|
async def list_messages(chat_id: str, request: Request):
|
||||||
|
user, _ = await current_user(request)
|
||||||
|
|
||||||
|
chat_uuid, _ = await accessible_chat(
|
||||||
|
chat_id,
|
||||||
|
user["id"],
|
||||||
|
)
|
||||||
|
|
||||||
|
scope = f"messages:{chat_uuid}"
|
||||||
|
limit, after = pagination(request, scope)
|
||||||
|
|
||||||
|
rows = await store.list_messages(
|
||||||
|
chat_uuid,
|
||||||
|
limit,
|
||||||
|
after,
|
||||||
|
)
|
||||||
|
|
||||||
|
return page_response(rows, limit, scope)
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Request
|
||||||
|
from fastapi.responses import Response
|
||||||
|
|
||||||
|
from app.auth import (
|
||||||
|
DUMMY_PASSWORD_HASH,
|
||||||
|
generate_token,
|
||||||
|
hash_token,
|
||||||
|
parse_basic_credentials,
|
||||||
|
verify_password,
|
||||||
|
)
|
||||||
|
from app.config import SESSION_TTL_SECONDS
|
||||||
|
from app.dependencies import current_user
|
||||||
|
from app.errors import invalid, unauthorized
|
||||||
|
from app.responses import json_response
|
||||||
|
from app.store import store
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/v1/auth/sessions")
|
||||||
|
async def create_session(request: Request):
|
||||||
|
credentials = parse_basic_credentials(
|
||||||
|
request.headers.get("authorization")
|
||||||
|
)
|
||||||
|
|
||||||
|
if credentials is None:
|
||||||
|
raise unauthorized("Basic")
|
||||||
|
|
||||||
|
username, password = credentials
|
||||||
|
|
||||||
|
user = await store.get_user_for_login(username)
|
||||||
|
|
||||||
|
stored_hash = (
|
||||||
|
DUMMY_PASSWORD_HASH
|
||||||
|
if user is None
|
||||||
|
else user["password_hash"]
|
||||||
|
)
|
||||||
|
|
||||||
|
password_ok = await verify_password(stored_hash, password)
|
||||||
|
|
||||||
|
if user is None or not password_ok:
|
||||||
|
raise unauthorized("Basic")
|
||||||
|
|
||||||
|
if await request.body():
|
||||||
|
raise invalid("Тело запроса при входе не допускается")
|
||||||
|
|
||||||
|
token = generate_token()
|
||||||
|
|
||||||
|
session = await store.create_session(
|
||||||
|
user["id"],
|
||||||
|
hash_token(token),
|
||||||
|
SESSION_TTL_SECONDS,
|
||||||
|
)
|
||||||
|
|
||||||
|
public_user = {
|
||||||
|
field: user[field]
|
||||||
|
for field in ("id", "username", "display_name", "created_at")
|
||||||
|
}
|
||||||
|
|
||||||
|
return json_response(
|
||||||
|
{
|
||||||
|
"token": token,
|
||||||
|
"token_type": "Bearer",
|
||||||
|
"expires_at": session["expires_at"],
|
||||||
|
"user": public_user,
|
||||||
|
},
|
||||||
|
201,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/v1/auth/sessions/current")
|
||||||
|
async def revoke_session(request: Request):
|
||||||
|
_, token_digest = await current_user(request)
|
||||||
|
|
||||||
|
revoked = await store.revoke_session(token_digest)
|
||||||
|
|
||||||
|
if not revoked:
|
||||||
|
raise unauthorized()
|
||||||
|
|
||||||
|
return Response(status_code=204)
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Request
|
||||||
|
|
||||||
|
from app.auth import USERNAME_RE, hash_password
|
||||||
|
from app.dependencies import current_user
|
||||||
|
from app.errors import ApiError, invalid
|
||||||
|
from app.responses import json_response
|
||||||
|
from app.store import store
|
||||||
|
from app.validation import read_payload, valid_text
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/v1/users")
|
||||||
|
async def create_user(request: Request):
|
||||||
|
payload = await read_payload(
|
||||||
|
request,
|
||||||
|
{"username", "display_name", "password"},
|
||||||
|
)
|
||||||
|
|
||||||
|
username = payload["username"]
|
||||||
|
display_name = payload["display_name"]
|
||||||
|
password = payload["password"]
|
||||||
|
|
||||||
|
if (
|
||||||
|
not isinstance(username, str)
|
||||||
|
or USERNAME_RE.fullmatch(username) is None
|
||||||
|
):
|
||||||
|
raise invalid("Некорректный username")
|
||||||
|
|
||||||
|
if not valid_text(display_name, 100):
|
||||||
|
raise invalid("Некорректное display_name")
|
||||||
|
|
||||||
|
if not valid_text(password, 128) or len(password) < 12:
|
||||||
|
raise invalid("Пароль должен содержать от 12 до 128 символов")
|
||||||
|
|
||||||
|
password_digest = await hash_password(password)
|
||||||
|
|
||||||
|
user = await store.create_user(
|
||||||
|
username,
|
||||||
|
display_name,
|
||||||
|
password_digest,
|
||||||
|
)
|
||||||
|
|
||||||
|
if user is None:
|
||||||
|
raise ApiError(
|
||||||
|
409,
|
||||||
|
"conflict",
|
||||||
|
"Username уже занят",
|
||||||
|
)
|
||||||
|
|
||||||
|
return json_response(user, 201)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/v1/users/me")
|
||||||
|
async def get_current_user(request: Request):
|
||||||
|
user, _ = await current_user(request)
|
||||||
|
return json_response(user)
|
||||||
+273
@@ -0,0 +1,273 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
from psycopg.errors import ForeignKeyViolation, UniqueViolation
|
||||||
|
|
||||||
|
from app.db import pool
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidMembersError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class PostgresStore:
|
||||||
|
async def create_user(
|
||||||
|
self,
|
||||||
|
username: str,
|
||||||
|
display_name: str,
|
||||||
|
password_hash: str,
|
||||||
|
) -> dict | None:
|
||||||
|
try:
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO users (
|
||||||
|
id, username, display_name, password_hash
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
RETURNING id, username, display_name, created_at
|
||||||
|
""",
|
||||||
|
(uuid4(), username, display_name, password_hash),
|
||||||
|
)
|
||||||
|
user = await cursor.fetchone()
|
||||||
|
|
||||||
|
return user
|
||||||
|
except UniqueViolation as exc:
|
||||||
|
if exc.diag.constraint_name == "users_username_unique":
|
||||||
|
return None
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def get_user(self, user_id: UUID) -> dict | None:
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, username, display_name, created_at
|
||||||
|
FROM users
|
||||||
|
WHERE id = %s
|
||||||
|
""",
|
||||||
|
(user_id,),
|
||||||
|
)
|
||||||
|
return await cursor.fetchone()
|
||||||
|
|
||||||
|
async def get_user_for_login(self, username: str) -> dict | None:
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, username, display_name,
|
||||||
|
password_hash, created_at
|
||||||
|
FROM users
|
||||||
|
WHERE username = %s
|
||||||
|
""",
|
||||||
|
(username,),
|
||||||
|
)
|
||||||
|
return await cursor.fetchone()
|
||||||
|
|
||||||
|
async def create_chat(
|
||||||
|
self,
|
||||||
|
title: str,
|
||||||
|
member_ids: list[UUID],
|
||||||
|
) -> dict:
|
||||||
|
chat_id = uuid4()
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO chats (id, title)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
RETURNING id, title, created_at
|
||||||
|
""",
|
||||||
|
(chat_id, title),
|
||||||
|
)
|
||||||
|
chat = await cursor.fetchone()
|
||||||
|
|
||||||
|
async with conn.cursor() as cursor:
|
||||||
|
await cursor.executemany(
|
||||||
|
"""
|
||||||
|
INSERT INTO chat_members (chat_id, user_id)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
""",
|
||||||
|
[(chat_id, user_id) for user_id in member_ids],
|
||||||
|
)
|
||||||
|
|
||||||
|
chat["member_ids"] = member_ids
|
||||||
|
|
||||||
|
return chat
|
||||||
|
except ForeignKeyViolation as exc:
|
||||||
|
raise InvalidMembersError from exc
|
||||||
|
|
||||||
|
async def get_accessible_chat(
|
||||||
|
self,
|
||||||
|
chat_id: UUID,
|
||||||
|
user_id: UUID,
|
||||||
|
) -> dict | None:
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT c.id, c.title, c.created_at,
|
||||||
|
ARRAY(
|
||||||
|
SELECT cm.user_id
|
||||||
|
FROM chat_members AS cm
|
||||||
|
WHERE cm.chat_id = c.id
|
||||||
|
ORDER BY cm.user_id
|
||||||
|
) AS member_ids
|
||||||
|
FROM chats AS c
|
||||||
|
WHERE c.id = %s
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM chat_members AS access
|
||||||
|
WHERE access.chat_id = c.id
|
||||||
|
AND access.user_id = %s
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
(chat_id, user_id),
|
||||||
|
)
|
||||||
|
return await cursor.fetchone()
|
||||||
|
|
||||||
|
async def list_chats(
|
||||||
|
self,
|
||||||
|
user_id: UUID,
|
||||||
|
limit: int,
|
||||||
|
after: tuple[datetime, UUID] | None = None,
|
||||||
|
) -> list[dict]:
|
||||||
|
params: list[object] = [user_id]
|
||||||
|
after_sql = ""
|
||||||
|
|
||||||
|
if after is not None:
|
||||||
|
after_sql = "AND (c.created_at, c.id) > (%s, %s)"
|
||||||
|
params.extend(after)
|
||||||
|
|
||||||
|
params.append(limit + 1)
|
||||||
|
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
f"""
|
||||||
|
SELECT c.id, c.title, c.created_at,
|
||||||
|
ARRAY(
|
||||||
|
SELECT cm.user_id
|
||||||
|
FROM chat_members AS cm
|
||||||
|
WHERE cm.chat_id = c.id
|
||||||
|
ORDER BY cm.user_id
|
||||||
|
) AS member_ids
|
||||||
|
FROM chats AS c
|
||||||
|
JOIN chat_members AS access
|
||||||
|
ON access.chat_id = c.id
|
||||||
|
WHERE access.user_id = %s
|
||||||
|
{after_sql}
|
||||||
|
ORDER BY c.created_at, c.id
|
||||||
|
LIMIT %s
|
||||||
|
""",
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
return await cursor.fetchall()
|
||||||
|
|
||||||
|
async def create_message(
|
||||||
|
self,
|
||||||
|
chat_id: UUID,
|
||||||
|
sender_id: UUID,
|
||||||
|
text: str,
|
||||||
|
) -> dict:
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
RETURNING id, chat_id, sender_id, text, created_at
|
||||||
|
""",
|
||||||
|
(uuid4(), chat_id, sender_id, text),
|
||||||
|
)
|
||||||
|
message = await cursor.fetchone()
|
||||||
|
|
||||||
|
return message
|
||||||
|
|
||||||
|
async def list_messages(
|
||||||
|
self,
|
||||||
|
chat_id: UUID,
|
||||||
|
limit: int,
|
||||||
|
after: tuple[datetime, UUID] | None = None,
|
||||||
|
) -> list[dict]:
|
||||||
|
params: list[object] = [chat_id]
|
||||||
|
after_sql = ""
|
||||||
|
|
||||||
|
if after is not None:
|
||||||
|
after_sql = "AND (created_at, id) > (%s, %s)"
|
||||||
|
params.extend(after)
|
||||||
|
|
||||||
|
params.append(limit + 1)
|
||||||
|
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
f"""
|
||||||
|
SELECT id, chat_id, sender_id, text, created_at
|
||||||
|
FROM messages
|
||||||
|
WHERE chat_id = %s
|
||||||
|
{after_sql}
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT %s
|
||||||
|
""",
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
return await cursor.fetchall()
|
||||||
|
|
||||||
|
async def create_session(
|
||||||
|
self,
|
||||||
|
user_id: UUID,
|
||||||
|
token_hash: str,
|
||||||
|
ttl_seconds: int,
|
||||||
|
) -> dict:
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO sessions (
|
||||||
|
token_hash, user_id, created_at, expires_at
|
||||||
|
)
|
||||||
|
VALUES (
|
||||||
|
%s, %s, statement_timestamp(),
|
||||||
|
statement_timestamp()
|
||||||
|
+ (%s * INTERVAL '1 second')
|
||||||
|
)
|
||||||
|
RETURNING expires_at
|
||||||
|
""",
|
||||||
|
(token_hash, user_id, ttl_seconds),
|
||||||
|
)
|
||||||
|
session = await cursor.fetchone()
|
||||||
|
|
||||||
|
return session
|
||||||
|
|
||||||
|
async def get_session_user_id(
|
||||||
|
self,
|
||||||
|
token_hash: str,
|
||||||
|
) -> UUID | None:
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT user_id
|
||||||
|
FROM sessions
|
||||||
|
WHERE token_hash = %s
|
||||||
|
AND expires_at > statement_timestamp()
|
||||||
|
""",
|
||||||
|
(token_hash,),
|
||||||
|
)
|
||||||
|
row = await cursor.fetchone()
|
||||||
|
|
||||||
|
return None if row is None else row["user_id"]
|
||||||
|
|
||||||
|
async def revoke_session(self, token_hash: str) -> bool:
|
||||||
|
async with pool.connection() as conn:
|
||||||
|
cursor = await conn.execute(
|
||||||
|
"""
|
||||||
|
DELETE FROM sessions
|
||||||
|
WHERE token_hash = %s
|
||||||
|
AND expires_at > statement_timestamp()
|
||||||
|
RETURNING token_hash
|
||||||
|
""",
|
||||||
|
(token_hash,),
|
||||||
|
)
|
||||||
|
row = await cursor.fetchone()
|
||||||
|
|
||||||
|
return row is not None
|
||||||
|
|
||||||
|
|
||||||
|
store = PostgresStore()
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import Request
|
||||||
|
|
||||||
|
from app.errors import ApiError, invalid
|
||||||
|
|
||||||
|
|
||||||
|
def parse_uuid(value: object) -> UUID:
|
||||||
|
if not isinstance(value, str):
|
||||||
|
raise invalid("Некорректный UUID")
|
||||||
|
|
||||||
|
try:
|
||||||
|
return UUID(value)
|
||||||
|
except ValueError:
|
||||||
|
raise invalid("Некорректный UUID") from None
|
||||||
|
|
||||||
|
|
||||||
|
def valid_text(value: object, maximum: int) -> bool:
|
||||||
|
return (
|
||||||
|
isinstance(value, str)
|
||||||
|
and 1 <= len(value) <= maximum
|
||||||
|
and bool(value.strip())
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def read_payload(
|
||||||
|
request: Request,
|
||||||
|
expected_fields: set[str],
|
||||||
|
optional_fields: set[str] | None = None,
|
||||||
|
) -> dict:
|
||||||
|
content_type = (
|
||||||
|
request.headers.get("content-type", "")
|
||||||
|
.split(";", 1)[0]
|
||||||
|
.strip()
|
||||||
|
.lower()
|
||||||
|
)
|
||||||
|
|
||||||
|
if content_type != "application/json":
|
||||||
|
raise ApiError(
|
||||||
|
415,
|
||||||
|
"unsupported_media_type",
|
||||||
|
"Требуется Content-Type: application/json",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
payload = await request.json()
|
||||||
|
except (ValueError, UnicodeError):
|
||||||
|
raise invalid("Некорректный JSON") from None
|
||||||
|
|
||||||
|
allowed_fields = expected_fields | (optional_fields or set())
|
||||||
|
|
||||||
|
if (
|
||||||
|
not isinstance(payload, dict)
|
||||||
|
or not expected_fields.issubset(payload)
|
||||||
|
or not set(payload).issubset(allowed_fields)
|
||||||
|
):
|
||||||
|
raise invalid("Некорректные поля запроса")
|
||||||
|
|
||||||
|
return payload
|
||||||
+132
@@ -0,0 +1,132 @@
|
|||||||
|
name: mtusi2026lab3
|
||||||
|
|
||||||
|
x-db-environment: &db-environment
|
||||||
|
PGHOST: postgres
|
||||||
|
PGPORT: "5432"
|
||||||
|
PGDATABASE: messenger
|
||||||
|
PGUSER: messenger
|
||||||
|
PGPASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16.4-bookworm
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: messenger
|
||||||
|
POSTGRES_USER: messenger
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
- CMD-SHELL
|
||||||
|
- pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"
|
||||||
|
interval: 2s
|
||||||
|
timeout: 2s
|
||||||
|
retries: 15
|
||||||
|
start_period: 20s
|
||||||
|
cpus: "1.0"
|
||||||
|
mem_limit: 512m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7.2.5-bookworm
|
||||||
|
command:
|
||||||
|
- redis-server
|
||||||
|
- --appendonly
|
||||||
|
- "yes"
|
||||||
|
- --appendfsync
|
||||||
|
- everysec
|
||||||
|
- --maxmemory
|
||||||
|
- 64mb
|
||||||
|
- --maxmemory-policy
|
||||||
|
- allkeys-lru
|
||||||
|
volumes:
|
||||||
|
- redis_data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 2s
|
||||||
|
retries: 10
|
||||||
|
start_period: 5s
|
||||||
|
cpus: "0.25"
|
||||||
|
mem_limit: 128m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
migrate:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
image: mtusi-messenger:lab3
|
||||||
|
command: ["python", "-m", "app.migrate"]
|
||||||
|
environment: *db-environment
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
cpus: "0.5"
|
||||||
|
mem_limit: 256m
|
||||||
|
restart: "no"
|
||||||
|
|
||||||
|
api:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
image: mtusi-messenger:lab3
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- -m
|
||||||
|
- uvicorn
|
||||||
|
- app.main:app
|
||||||
|
- --host
|
||||||
|
- 0.0.0.0
|
||||||
|
- --port
|
||||||
|
- "8080"
|
||||||
|
- --workers
|
||||||
|
- "1"
|
||||||
|
- --timeout-graceful-shutdown
|
||||||
|
- "5"
|
||||||
|
- --no-access-log
|
||||||
|
environment:
|
||||||
|
<<: *db-environment
|
||||||
|
REDIS_HOST: redis
|
||||||
|
REDIS_PORT: "6379"
|
||||||
|
USER_CACHE_TTL_SECONDS: "${USER_CACHE_TTL_SECONDS:-60}"
|
||||||
|
SESSION_TTL_SECONDS: "${SESSION_TTL_SECONDS:-3600}"
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
- CMD
|
||||||
|
- python
|
||||||
|
- -c
|
||||||
|
- "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2).read()"
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
|
deploy:
|
||||||
|
replicas: 2
|
||||||
|
cpus: "0.75"
|
||||||
|
mem_limit: 512m
|
||||||
|
stop_grace_period: 10s
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
lb:
|
||||||
|
image: haproxy:3.0.5-bookworm
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:18082:8080"
|
||||||
|
volumes:
|
||||||
|
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||||
|
depends_on:
|
||||||
|
api:
|
||||||
|
condition: service_started
|
||||||
|
cpus: "0.25"
|
||||||
|
mem_limit: 128m
|
||||||
|
stop_grace_period: 10s
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
redis_data:
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
polina@Luntik:~/projects/mtusi2026lab3$ python3 student-tests/concurrent_idempotency.py \
|
||||||
|
--base-url http://localhost:18082
|
||||||
|
{"round": 1, "requests": 12, "responses_201": 12, "observed_instances": 2, "responses_by_instance": {"6f4df9719dbe:522a89485c0b": 6, "cdfebf3e392f:185372b9d3fa": 6}, "unique_message_ids": 1, "matching_history_messages": 1, "duration_seconds": 0.106}
|
||||||
|
{"round": 2, "requests": 12, "responses_201": 12, "observed_instances": 2, "responses_by_instance": {"6f4df9719dbe:522a89485c0b": 6, "cdfebf3e392f:185372b9d3fa": 6}, "unique_message_ids": 1, "matching_history_messages": 1, "duration_seconds": 0.136}
|
||||||
|
{"round": 3, "requests": 12, "responses_201": 12, "observed_instances": 2, "responses_by_instance": {"cdfebf3e392f:185372b9d3fa": 6, "6f4df9719dbe:522a89485c0b": 6}, "unique_message_ids": 1, "matching_history_messages": 1, "duration_seconds": 0.1}
|
||||||
|
{"rounds": 3, "concurrent_requests_per_round": 12, "concurrent_requests_total": 36, "body_conflict_409": true, "missing_and_invalid_key_400": true, "foreign_user_404": true, "user_scope_independent": true, "chat_scope_independent": true, "replay_preserved": true, "revoked_session_401": true, "unexpected_messages": 0}
|
||||||
|
PASS: concurrent cross-replica idempotency, scope, validation and authorization checks.
|
||||||
|
polina@Luntik:~/projects/mtusi2026lab3$
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
polina@Luntik:~/projects/mtusi2026lab3$ docker compose -p mtusi2026lab3 start api
|
||||||
|
[+] Running 3/3
|
||||||
|
✔ Container mtusi2026lab3-postgres-1 Healthy 1.7s
|
||||||
|
✔ Container mtusi2026lab3-migrate-1 Exited 2.2s
|
||||||
|
✔ Container mtusi2026lab3-api-2 Started 0.6s
|
||||||
|
polina@Luntik:~/projects/mtusi2026lab3$ docker compose -p mtusi2026lab3 ps -a
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
mtusi2026lab3-api-1 mtusi-messenger:lab3 "python -m uvicorn a…" api 29 minutes ago Up 6 minutes (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-api-2 mtusi-messenger:lab3 "python -m uvicorn a…" api 29 minutes ago Up 8 seconds (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-lb-1 haproxy:3.0.5-bookworm "docker-entrypoint.s…" lb 29 minutes ago Up 21 minutes 127.0.0.1:18082->8080/tcp
|
||||||
|
mtusi2026lab3-migrate-1 mtusi-messenger:lab3 "python -m app.migra…" migrate 29 minutes ago Exited (0) 9 seconds ago
|
||||||
|
mtusi2026lab3-postgres-1 postgres:16.4-bookworm "docker-entrypoint.s…" postgres 29 minutes ago Up 21 minutes (healthy) 5432/tcp
|
||||||
|
mtusi2026lab3-redis-1 redis:7.2.5-bookworm "docker-entrypoint.s…" redis 29 minutes ago Up 21 minutes (healthy) 6379/tcp
|
||||||
|
polina@Luntik:~/projects/mtusi2026lab3$ python3 student-tests/targeted_failover.py \
|
||||||
|
--base-url http://localhost:18082 \
|
||||||
|
--target-container mtusi2026lab3-api-1
|
||||||
|
Target container: mtusi2026lab3-api-1 | instance: cdfebf3e392f:2d90c4bb4d19
|
||||||
|
{"target_container": "mtusi2026lab3-api-1", "target_instance": "cdfebf3e392f:2d90c4bb4d19", "observed_instances_before": 2, "duration_seconds": 15.328, "successful_writes": 118, "failed_write_attempts": 2, "successful_reads": 24, "failed_read_attempts": 0, "successful_write_rps": 7.698, "first_recovery_seconds": 1.583, "replay_preserved": true, "target_stopped": true}
|
||||||
|
PASS: targeted failover; session, messages and replay preserved. Target remains stopped.
|
||||||
|
polina@Luntik:~/projects/mtusi2026lab3$ docker compose -p mtusi2026lab3 ps -a
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
mtusi2026lab3-api-1 mtusi-messenger:lab3 "python -m uvicorn a…" api 30 minutes ago Exited (0) 29 seconds ago
|
||||||
|
mtusi2026lab3-api-2 mtusi-messenger:lab3 "python -m uvicorn a…" api 30 minutes ago Up 52 seconds (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-lb-1 haproxy:3.0.5-bookworm "docker-entrypoint.s…" lb 30 minutes ago Up 22 minutes 127.0.0.1:18082->8080/tcp
|
||||||
|
mtusi2026lab3-migrate-1 mtusi-messenger:lab3 "python -m app.migra…" migrate 30 minutes ago Exited (0) 53 seconds ago
|
||||||
|
mtusi2026lab3-postgres-1 postgres:16.4-bookworm "docker-entrypoint.s…" postgres 30 minutes ago Up 22 minutes (healthy) 5432/tcp
|
||||||
|
mtusi2026lab3-redis-1 redis:7.2.5-bookworm "docker-entrypoint.s…" redis 30 minutes ago Up 22 minutes (healthy) 6379/tcp
|
||||||
|
polina@Luntik:~/projects/mtusi2026lab3$ docker compose -p mtusi2026lab3 start api
|
||||||
|
[+] Running 3/3
|
||||||
|
✔ Container mtusi2026lab3-postgres-1 Healthy 1.8s
|
||||||
|
✔ Container mtusi2026lab3-migrate-1 Exited 3.1s
|
||||||
|
✔ Container mtusi2026lab3-api-1 Started 0.5s
|
||||||
|
polina@Luntik:~/projects/mtusi2026lab3$
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
polina@Luntik:~/projects/mtusi2026lab3$ python3 student-tests/targeted_failover.py \
|
||||||
|
--base-url http://localhost:18082 \
|
||||||
|
--target-container mtusi2026lab3-api-2
|
||||||
|
Target container: mtusi2026lab3-api-2 | instance: 6f4df9719dbe:7a5d16e1ffb3
|
||||||
|
{"target_container": "mtusi2026lab3-api-2", "target_instance": "6f4df9719dbe:7a5d16e1ffb3", "observed_instances_before": 2, "duration_seconds": 15.053, "successful_writes": 112, "failed_write_attempts": 2, "successful_reads": 22, "failed_read_attempts": 0, "successful_write_rps": 7.441, "first_recovery_seconds": 2.965, "replay_preserved": true, "target_stopped": true}
|
||||||
|
PASS: targeted failover; session, messages and replay preserved. Target remains stopped.
|
||||||
|
polina@Luntik:~/projects/mtusi2026lab3$ docker compose -p mtusi2026lab3 ps -a
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
mtusi2026lab3-api-1 mtusi-messenger:lab3 "python -m uvicorn a…" api 26 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-api-2 mtusi-messenger:lab3 "python -m uvicorn a…" api 26 minutes ago Exited (0) 19 seconds ago
|
||||||
|
mtusi2026lab3-lb-1 haproxy:3.0.5-bookworm "docker-entrypoint.s…" lb 26 minutes ago Up 17 minutes 127.0.0.1:18082->8080/tcp
|
||||||
|
mtusi2026lab3-migrate-1 mtusi-messenger:lab3 "python -m app.migra…" migrate 26 minutes ago Exited (0) 2 minutes ago
|
||||||
|
mtusi2026lab3-postgres-1 postgres:16.4-bookworm "docker-entrypoint.s…" postgres 26 minutes ago Up 18 minutes (healthy) 5432/tcp
|
||||||
|
mtusi2026lab3-redis-1 redis:7.2.5-bookworm "docker-entrypoint.s…" redis 26 minutes ago Up 18 minutes (healthy) 6379/tcp
|
||||||
|
polina@Luntik:~/projects/mtusi2026lab3$
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"lab": 3,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 90.0,
|
||||||
|
"elapsed_seconds": 90.226,
|
||||||
|
"concurrency": 4,
|
||||||
|
"successful_requests": 5991,
|
||||||
|
"failed_requests": 59,
|
||||||
|
"error_ratio": 0.009752,
|
||||||
|
"successful_rps": 66.4,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 44.586,
|
||||||
|
"p95": 111.2,
|
||||||
|
"p99": 241.368
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"lab": 3,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 90.0,
|
||||||
|
"elapsed_seconds": 90.283,
|
||||||
|
"concurrency": 4,
|
||||||
|
"successful_requests": 7005,
|
||||||
|
"failed_requests": 107,
|
||||||
|
"error_ratio": 0.015045,
|
||||||
|
"successful_rps": 77.589,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 34.292,
|
||||||
|
"p95": 111.253,
|
||||||
|
"p99": 191.745
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
=== Нагрузка для измерения ресурсов, без отказов ===
|
||||||
|
Команда: python3 tests/load.py --base-url http://localhost:18082 --duration 90 --concurrency 4 --output evidence/load-resources.json
|
||||||
|
LOAD START: 2026-10-29T16:54:26Z
|
||||||
|
{
|
||||||
|
"lab": 3,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 90.0,
|
||||||
|
"elapsed_seconds": 90.165,
|
||||||
|
"concurrency": 4,
|
||||||
|
"successful_requests": 7061,
|
||||||
|
"failed_requests": 0,
|
||||||
|
"error_ratio": 0.0,
|
||||||
|
"successful_rps": 78.312,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 37.078,
|
||||||
|
"p95": 99.704,
|
||||||
|
"p99": 149.071
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
|
LOAD END: 2026-10-29T16:56:00Z
|
||||||
|
Код завершения генератора: 0
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"lab": 3,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 90.0,
|
||||||
|
"elapsed_seconds": 90.165,
|
||||||
|
"concurrency": 4,
|
||||||
|
"successful_requests": 7061,
|
||||||
|
"failed_requests": 0,
|
||||||
|
"error_ratio": 0.0,
|
||||||
|
"successful_rps": 78.312,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 37.078,
|
||||||
|
"p95": 99.704,
|
||||||
|
"p99": 149.071
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
=== Повтор нагрузки при замене реплик ===
|
||||||
|
Команда: python3 tests/load.py --base-url http://localhost:18082 --duration 90 --concurrency 4 --output evidence/load-during-replacement-repeat.json
|
||||||
|
LOAD START: 2026-10-29T16:50:07Z
|
||||||
|
{
|
||||||
|
"lab": 3,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 90.0,
|
||||||
|
"elapsed_seconds": 90.226,
|
||||||
|
"concurrency": 4,
|
||||||
|
"successful_requests": 5991,
|
||||||
|
"failed_requests": 59,
|
||||||
|
"error_ratio": 0.009752,
|
||||||
|
"successful_rps": 66.4,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 44.586,
|
||||||
|
"p95": 111.2,
|
||||||
|
"p99": 241.368
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
|
LOAD END: 2026-10-29T16:51:40Z
|
||||||
|
Код завершения генератора: 0
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
=== Повторная проверка persistence ===
|
||||||
|
UTC: 2026-10-29T16:44:33Z
|
||||||
|
|
||||||
|
=== Контейнеры и StartedAt ДО проверки ===
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
mtusi2026lab3-api-2 mtusi-messenger:lab3 "python -m uvicorn a…" api 18 minutes ago Up 18 minutes (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-api-3 mtusi-messenger:lab3 "python -m uvicorn a…" api 18 minutes ago Up 18 minutes (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-lb-1 haproxy:3.0.5-bookworm "docker-entrypoint.s…" lb About an hour ago Up About an hour 127.0.0.1:18082->8080/tcp
|
||||||
|
mtusi2026lab3-migrate-1 mtusi-messenger:lab3 "python -m app.migra…" migrate About an hour ago Exited (0) 40 minutes ago
|
||||||
|
mtusi2026lab3-postgres-1 postgres:16.4-bookworm "docker-entrypoint.s…" postgres About an hour ago Up About an hour (healthy) 5432/tcp
|
||||||
|
mtusi2026lab3-redis-1 redis:7.2.5-bookworm "docker-entrypoint.s…" redis About an hour ago Up About an hour (healthy) 6379/tcp
|
||||||
|
/mtusi2026lab3-api-2 | ID=0b926b215c5bd9a5503587b8977241c563d0c9297edb6596b450fcc806312246 | StartedAt=2026-10-29T16:25:47.209634263Z
|
||||||
|
/mtusi2026lab3-api-3 | ID=d180fdf312493c47f36dcf15588a5eb5cc0ece952b3edcfbf0681f68c1738930 | StartedAt=2026-10-29T16:26:01.913602506Z
|
||||||
|
/mtusi2026lab3-lb-1 | ID=3acfe83752108ff0b52b915ce1253942cc886c98f568e5e924bd90bc511e6516 | StartedAt=2026-10-29T15:40:54.834083062Z
|
||||||
|
/mtusi2026lab3-postgres-1 | ID=b608e7d62fdd6ef31ef066641afe4686ab9e660c23a8ae8b7449e0740a54d0a9 | StartedAt=2026-10-29T15:40:54.342535557Z
|
||||||
|
/mtusi2026lab3-redis-1 | ID=0bd25c343af100fcbcc1f7ba5d25c1681d622f1b02ebb451ef6cda4b6463be25 | StartedAt=2026-10-29T15:40:54.669575857Z
|
||||||
|
|
||||||
|
=== Команда ===
|
||||||
|
make test-persistence BASE_URL=http://localhost:18082 ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
|
||||||
|
=== Результат теста ===
|
||||||
|
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:18082"
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
|
||||||
|
Код завершения make: 0
|
||||||
|
|
||||||
|
=== Контейнеры и StartedAt ПОСЛЕ проверки ===
|
||||||
|
/mtusi2026lab3-api-2 | ID=0b926b215c5bd9a5503587b8977241c563d0c9297edb6596b450fcc806312246 | StartedAt=2026-10-29T16:44:39.314015108Z
|
||||||
|
/mtusi2026lab3-api-3 | ID=d180fdf312493c47f36dcf15588a5eb5cc0ece952b3edcfbf0681f68c1738930 | StartedAt=2026-10-29T16:44:39.400809138Z
|
||||||
|
/mtusi2026lab3-lb-1 | ID=3acfe83752108ff0b52b915ce1253942cc886c98f568e5e924bd90bc511e6516 | StartedAt=2026-10-29T16:44:39.600053051Z
|
||||||
|
/mtusi2026lab3-postgres-1 | ID=b608e7d62fdd6ef31ef066641afe4686ab9e660c23a8ae8b7449e0740a54d0a9 | StartedAt=2026-10-29T16:44:39.014962677Z
|
||||||
|
/mtusi2026lab3-redis-1 | ID=0bd25c343af100fcbcc1f7ba5d25c1681d622f1b02ebb451ef6cda4b6463be25 | StartedAt=2026-10-29T16:44:38.896928023Z
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
mtusi2026lab3-api-2 mtusi-messenger:lab3 "python -m uvicorn a…" api 18 minutes ago Up 6 seconds (health: starting) 8080/tcp
|
||||||
|
mtusi2026lab3-api-3 mtusi-messenger:lab3 "python -m uvicorn a…" api 18 minutes ago Up 6 seconds (health: starting) 8080/tcp
|
||||||
|
mtusi2026lab3-lb-1 haproxy:3.0.5-bookworm "docker-entrypoint.s…" lb About an hour ago Up 6 seconds 127.0.0.1:18082->8080/tcp
|
||||||
|
mtusi2026lab3-migrate-1 mtusi-messenger:lab3 "python -m app.migra…" migrate About an hour ago Exited (0) 41 minutes ago
|
||||||
|
mtusi2026lab3-postgres-1 postgres:16.4-bookworm "docker-entrypoint.s…" postgres About an hour ago Up 6 seconds (healthy) 5432/tcp
|
||||||
|
mtusi2026lab3-redis-1 redis:7.2.5-bookworm "docker-entrypoint.s…" redis About an hour ago Up 6 seconds (healthy) 6379/tcp
|
||||||
|
|
||||||
|
UTC: 2026-10-29T16:44:45Z
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
polina@Luntik:~/projects/mtusi2026lab3$ docker compose -p mtusi2026lab3 ps -q api postgres redis lb |
|
||||||
|
xargs -r docker inspect --format \
|
||||||
|
'{{.Name}} | NanoCPUs={{.HostConfig.NanoCpus}} | MemoryBytes={{.HostConfig.Memory}}'
|
||||||
|
/mtusi2026lab3-api-2 | NanoCPUs=750000000 | MemoryBytes=536870912
|
||||||
|
/mtusi2026lab3-api-3 | NanoCPUs=750000000 | MemoryBytes=536870912
|
||||||
|
/mtusi2026lab3-lb-1 | NanoCPUs=250000000 | MemoryBytes=134217728
|
||||||
|
/mtusi2026lab3-postgres-1 | NanoCPUs=1000000000 | MemoryBytes=536870912
|
||||||
|
/mtusi2026lab3-redis-1 | NanoCPUs=250000000 | MemoryBytes=134217728
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
=== Снимки ресурсов при нагрузке без отказов ===
|
||||||
|
|
||||||
|
=== Снимок 1 ===
|
||||||
|
SAMPLE START: 2026-10-29T16:54:33Z
|
||||||
|
NAME CPU % MEM USAGE / LIMIT MEM %
|
||||||
|
mtusi2026lab3-api-4 72.42% 54.38MiB / 512MiB 10.62%
|
||||||
|
mtusi2026lab3-api-5 64.65% 53.03MiB / 512MiB 10.36%
|
||||||
|
mtusi2026lab3-lb-1 20.86% 14.27MiB / 128MiB 11.15%
|
||||||
|
mtusi2026lab3-postgres-1 44.35% 49.56MiB / 512MiB 9.68%
|
||||||
|
mtusi2026lab3-redis-1 2.04% 3.285MiB / 128MiB 2.57%
|
||||||
|
SAMPLE END: 2026-10-29T16:54:36Z
|
||||||
|
|
||||||
|
=== Снимок 2 ===
|
||||||
|
SAMPLE START: 2026-10-29T16:54:41Z
|
||||||
|
NAME CPU % MEM USAGE / LIMIT MEM %
|
||||||
|
mtusi2026lab3-api-4 72.95% 55.55MiB / 512MiB 10.85%
|
||||||
|
mtusi2026lab3-api-5 73.24% 56.21MiB / 512MiB 10.98%
|
||||||
|
mtusi2026lab3-lb-1 16.37% 14.39MiB / 128MiB 11.25%
|
||||||
|
mtusi2026lab3-postgres-1 35.97% 52.37MiB / 512MiB 10.23%
|
||||||
|
mtusi2026lab3-redis-1 1.86% 3.285MiB / 128MiB 2.57%
|
||||||
|
SAMPLE END: 2026-10-29T16:54:44Z
|
||||||
|
|
||||||
|
=== Снимок 3 ===
|
||||||
|
SAMPLE START: 2026-10-29T16:54:49Z
|
||||||
|
NAME CPU % MEM USAGE / LIMIT MEM %
|
||||||
|
mtusi2026lab3-api-4 74.05% 57.2MiB / 512MiB 11.17%
|
||||||
|
mtusi2026lab3-api-5 57.66% 43.75MiB / 512MiB 8.55%
|
||||||
|
mtusi2026lab3-lb-1 18.52% 14.5MiB / 128MiB 11.33%
|
||||||
|
mtusi2026lab3-postgres-1 28.49% 50.21MiB / 512MiB 9.81%
|
||||||
|
mtusi2026lab3-redis-1 4.17% 4.609MiB / 128MiB 3.60%
|
||||||
|
SAMPLE END: 2026-10-29T16:54:52Z
|
||||||
|
|
||||||
|
=== Снимок 4 ===
|
||||||
|
SAMPLE START: 2026-10-29T16:54:57Z
|
||||||
|
NAME CPU % MEM USAGE / LIMIT MEM %
|
||||||
|
mtusi2026lab3-api-4 62.33% 44.63MiB / 512MiB 8.72%
|
||||||
|
mtusi2026lab3-api-5 45.19% 43.84MiB / 512MiB 8.56%
|
||||||
|
mtusi2026lab3-lb-1 22.79% 14.7MiB / 128MiB 11.48%
|
||||||
|
mtusi2026lab3-postgres-1 46.03% 50.54MiB / 512MiB 9.87%
|
||||||
|
mtusi2026lab3-redis-1 1.56% 3.289MiB / 128MiB 2.57%
|
||||||
|
SAMPLE END: 2026-10-29T16:55:00Z
|
||||||
|
|
||||||
|
=== Снимок 5 ===
|
||||||
|
SAMPLE START: 2026-10-29T16:55:05Z
|
||||||
|
NAME CPU % MEM USAGE / LIMIT MEM %
|
||||||
|
mtusi2026lab3-api-4 57.58% 44.38MiB / 512MiB 8.67%
|
||||||
|
mtusi2026lab3-api-5 44.67% 43.83MiB / 512MiB 8.56%
|
||||||
|
mtusi2026lab3-lb-1 23.80% 15.07MiB / 128MiB 11.77%
|
||||||
|
mtusi2026lab3-postgres-1 34.24% 50.85MiB / 512MiB 9.93%
|
||||||
|
mtusi2026lab3-redis-1 6.98% 4.297MiB / 128MiB 3.36%
|
||||||
|
SAMPLE END: 2026-10-29T16:55:08Z
|
||||||
|
|
||||||
|
=== Снимок 6 ===
|
||||||
|
SAMPLE START: 2026-10-29T16:55:13Z
|
||||||
|
NAME CPU % MEM USAGE / LIMIT MEM %
|
||||||
|
mtusi2026lab3-api-4 51.01% 44.62MiB / 512MiB 8.72%
|
||||||
|
mtusi2026lab3-api-5 70.18% 53.83MiB / 512MiB 10.51%
|
||||||
|
mtusi2026lab3-lb-1 22.58% 15.22MiB / 128MiB 11.89%
|
||||||
|
mtusi2026lab3-postgres-1 45.96% 51.18MiB / 512MiB 10.00%
|
||||||
|
mtusi2026lab3-redis-1 1.80% 3.289MiB / 128MiB 2.57%
|
||||||
|
SAMPLE END: 2026-10-29T16:55:16Z
|
||||||
|
|
||||||
|
=== Снимок 7 ===
|
||||||
|
SAMPLE START: 2026-10-29T16:55:21Z
|
||||||
|
NAME CPU % MEM USAGE / LIMIT MEM %
|
||||||
|
mtusi2026lab3-api-4 37.25% 44.37MiB / 512MiB 8.67%
|
||||||
|
mtusi2026lab3-api-5 74.03% 56.45MiB / 512MiB 11.03%
|
||||||
|
mtusi2026lab3-lb-1 17.15% 15.11MiB / 128MiB 11.80%
|
||||||
|
mtusi2026lab3-postgres-1 27.07% 51.71MiB / 512MiB 10.10%
|
||||||
|
mtusi2026lab3-redis-1 4.62% 4.844MiB / 128MiB 3.78%
|
||||||
|
SAMPLE END: 2026-10-29T16:55:23Z
|
||||||
|
|
||||||
|
=== Снимок 8 ===
|
||||||
|
SAMPLE START: 2026-10-29T16:55:28Z
|
||||||
|
NAME CPU % MEM USAGE / LIMIT MEM %
|
||||||
|
mtusi2026lab3-api-4 44.54% 44.37MiB / 512MiB 8.67%
|
||||||
|
mtusi2026lab3-api-5 65.53% 44.09MiB / 512MiB 8.61%
|
||||||
|
mtusi2026lab3-lb-1 21.66% 15.48MiB / 128MiB 12.09%
|
||||||
|
mtusi2026lab3-postgres-1 46.37% 52.11MiB / 512MiB 10.18%
|
||||||
|
mtusi2026lab3-redis-1 1.85% 3.297MiB / 128MiB 2.58%
|
||||||
|
SAMPLE END: 2026-10-29T16:55:31Z
|
||||||
|
|
||||||
|
=== Снимок 9 ===
|
||||||
|
SAMPLE START: 2026-10-29T16:55:36Z
|
||||||
|
NAME CPU % MEM USAGE / LIMIT MEM %
|
||||||
|
mtusi2026lab3-api-4 64.04% 53.68MiB / 512MiB 10.48%
|
||||||
|
mtusi2026lab3-api-5 58.31% 43.85MiB / 512MiB 8.56%
|
||||||
|
mtusi2026lab3-lb-1 17.46% 15.37MiB / 128MiB 12.01%
|
||||||
|
mtusi2026lab3-postgres-1 39.60% 52.68MiB / 512MiB 10.29%
|
||||||
|
mtusi2026lab3-redis-1 2.06% 3.289MiB / 128MiB 2.57%
|
||||||
|
SAMPLE END: 2026-10-29T16:55:39Z
|
||||||
|
|
||||||
|
=== Снимок 10 ===
|
||||||
|
SAMPLE START: 2026-10-29T16:55:44Z
|
||||||
|
NAME CPU % MEM USAGE / LIMIT MEM %
|
||||||
|
mtusi2026lab3-api-4 63.15% 53.88MiB / 512MiB 10.52%
|
||||||
|
mtusi2026lab3-api-5 72.93% 43.86MiB / 512MiB 8.57%
|
||||||
|
mtusi2026lab3-lb-1 24.08% 15.44MiB / 128MiB 12.06%
|
||||||
|
mtusi2026lab3-postgres-1 42.52% 52.77MiB / 512MiB 10.31%
|
||||||
|
mtusi2026lab3-redis-1 1.88% 3.293MiB / 128MiB 2.57%
|
||||||
|
SAMPLE END: 2026-10-29T16:55:47Z
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
python3 student-tests/rolling_replacement.py \
|
||||||
|
--base-url http://localhost:18082
|
||||||
|
{"event": "replacement_started", "utc": "2026-10-29T16:25:42.695871+00:00", "original_container_ids": ["6f4df9719dbe1c0052c8f13d5c4291917021abcb855679559c1aec35ad6bdefd", "cdfebf3e392f63991755ef30612e1d77c872209b75fa6cce6ccfd0bb6e49de0a"]}
|
||||||
|
{"event": "replacing", "utc": "2026-10-29T16:25:45.475660+00:00", "old_container_id": "6f4df9719dbe1c0052c8f13d5c4291917021abcb855679559c1aec35ad6bdefd", "old_instance": "6f4df9719dbe:522a89485c0b", "remaining_container_id": "cdfebf3e392f63991755ef30612e1d77c872209b75fa6cce6ccfd0bb6e49de0a"}
|
||||||
|
[+] Running 2/2
|
||||||
|
✔ Container mtusi2026lab3-api-1 Running0.0s
|
||||||
|
✔ Container mtusi2026lab3-api-2 Started0.7s
|
||||||
|
{"event": "replacement_ready", "utc": "2026-10-29T16:25:54.674011+00:00", "old_container_id": "6f4df9719dbe1c0052c8f13d5c4291917021abcb855679559c1aec35ad6bdefd", "new_container_id": "0b926b215c5bd9a5503587b8977241c563d0c9297edb6596b450fcc806312246", "old_instance": "6f4df9719dbe:522a89485c0b", "new_instance": "0b926b215c5b:8d1da1670102", "step_seconds": 9.198, "other_api_not_restarted": true, "existing_session_works": true, "replay_preserved": true}
|
||||||
|
{"event": "replacing", "utc": "2026-10-29T16:26:00.012568+00:00", "old_container_id": "cdfebf3e392f63991755ef30612e1d77c872209b75fa6cce6ccfd0bb6e49de0a", "old_instance": "cdfebf3e392f:185372b9d3fa", "remaining_container_id": "0b926b215c5bd9a5503587b8977241c563d0c9297edb6596b450fcc806312246"}
|
||||||
|
[+] Running 2/2
|
||||||
|
✔ Container mtusi2026lab3-api-2 Running0.0s
|
||||||
|
✔ Container mtusi2026lab3-api-3 Started0.7s
|
||||||
|
{"event": "replacement_ready", "utc": "2026-10-29T16:26:11.653375+00:00", "old_container_id": "cdfebf3e392f63991755ef30612e1d77c872209b75fa6cce6ccfd0bb6e49de0a", "new_container_id": "d180fdf312493c47f36dcf15588a5eb5cc0ece952b3edcfbf0681f68c1738930", "old_instance": "cdfebf3e392f:185372b9d3fa", "new_instance": "d180fdf31249:d3abba61eba9", "step_seconds": 11.641, "other_api_not_restarted": true, "existing_session_works": true, "replay_preserved": true}
|
||||||
|
{"event": "replacement_finished", "utc": "2026-10-29T16:26:15.078745+00:00", "replacements": 2, "final_container_ids": ["0b926b215c5bd9a5503587b8977241c563d0c9297edb6596b450fcc806312246", "d180fdf312493c47f36dcf15588a5eb5cc0ece952b3edcfbf0681f68c1738930"]}
|
||||||
|
PASS: both API containers replaced sequentially; existing session and confirmed message preserved.
|
||||||
|
polina@Luntik:~/projects/mtusi2026lab3$ docker compose -p mtusi2026lab3 ps -a
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
mtusi2026lab3-api-2 mtusi-messenger:lab3 "python -m uvicorn a…" api About a minute ago Up About a minute (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-api-3 mtusi-messenger:lab3 "python -m uvicorn a…" api 56 seconds ago Up 55 seconds (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-lb-1 haproxy:3.0.5-bookworm "docker-entrypoint.s…" lb 54 minutes ago Up 46 minutes 127.0.0.1:18082->8080/tcp
|
||||||
|
mtusi2026lab3-migrate-1 mtusi-messenger:lab3 "python -m app.migra…" migrate 54 minutes ago Exited (0) 23 minutes ago
|
||||||
|
mtusi2026lab3-postgres-1 postgres:16.4-bookworm "docker-entrypoint.s…" postgres 54 minutes ago Up 46 minutes (healthy) 5432/tcp
|
||||||
|
mtusi2026lab3-redis-1 redis:7.2.5-bookworm "docker-entrypoint.s…" redis 54 minutes ago Up 46 minutes (healthy) 6379/tcp
|
||||||
|
polina@Luntik:~/projects/mtusi2026lab3$ make test BASE_URL=http://localhost:18082
|
||||||
|
python3 tests/smoke.py --base-url "http://localhost:18082"
|
||||||
|
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
=== Повтор поочерёдной замены API ===
|
||||||
|
ROLLING COMMAND START: 2026-10-29T16:50:47Z
|
||||||
|
|
||||||
|
=== Состояние ДО замены ===
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
mtusi2026lab3-api-2 mtusi-messenger:lab3 "python -m uvicorn a…" api 25 minutes ago Up 6 minutes (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-api-3 mtusi-messenger:lab3 "python -m uvicorn a…" api 24 minutes ago Up 6 minutes (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-lb-1 haproxy:3.0.5-bookworm "docker-entrypoint.s…" lb About an hour ago Up 6 minutes 127.0.0.1:18082->8080/tcp
|
||||||
|
mtusi2026lab3-migrate-1 mtusi-messenger:lab3 "python -m app.migra…" migrate About an hour ago Exited (0) 47 minutes ago
|
||||||
|
mtusi2026lab3-postgres-1 postgres:16.4-bookworm "docker-entrypoint.s…" postgres About an hour ago Up 6 minutes (healthy) 5432/tcp
|
||||||
|
mtusi2026lab3-redis-1 redis:7.2.5-bookworm "docker-entrypoint.s…" redis About an hour ago Up 6 minutes (healthy) 6379/tcp
|
||||||
|
|
||||||
|
=== Команда ===
|
||||||
|
python3 student-tests/rolling_replacement.py --base-url http://localhost:18082
|
||||||
|
{"event": "replacement_started", "utc": "2026-10-29T16:50:55.306658+00:00", "original_container_ids": ["0b926b215c5bd9a5503587b8977241c563d0c9297edb6596b450fcc806312246", "d180fdf312493c47f36dcf15588a5eb5cc0ece952b3edcfbf0681f68c1738930"]}
|
||||||
|
{"event": "replacing", "utc": "2026-10-29T16:50:58.908779+00:00", "old_container_id": "0b926b215c5bd9a5503587b8977241c563d0c9297edb6596b450fcc806312246", "old_instance": "0b926b215c5b:0ce4605ebea4", "remaining_container_id": "d180fdf312493c47f36dcf15588a5eb5cc0ece952b3edcfbf0681f68c1738930"}
|
||||||
|
Container mtusi2026lab3-api-3 Running
|
||||||
|
Container mtusi2026lab3-api-4 Creating
|
||||||
|
Container mtusi2026lab3-api-4 Created
|
||||||
|
Container mtusi2026lab3-api-4 Starting
|
||||||
|
Container mtusi2026lab3-api-4 Started
|
||||||
|
{"event": "replacement_ready", "utc": "2026-10-29T16:51:10.700064+00:00", "old_container_id": "0b926b215c5bd9a5503587b8977241c563d0c9297edb6596b450fcc806312246", "new_container_id": "a55b0960bdec618c241102e83f0b87d459a6e0b5e8109871e0cc526541f372f5", "old_instance": "0b926b215c5b:0ce4605ebea4", "new_instance": "a55b0960bdec:865331549779", "step_seconds": 11.791, "other_api_not_restarted": true, "existing_session_works": true, "replay_preserved": true}
|
||||||
|
{"event": "replacing", "utc": "2026-10-29T16:51:16.191913+00:00", "old_container_id": "d180fdf312493c47f36dcf15588a5eb5cc0ece952b3edcfbf0681f68c1738930", "old_instance": "d180fdf31249:ce15c606e240", "remaining_container_id": "a55b0960bdec618c241102e83f0b87d459a6e0b5e8109871e0cc526541f372f5"}
|
||||||
|
Container mtusi2026lab3-api-4 Running
|
||||||
|
Container mtusi2026lab3-api-5 Creating
|
||||||
|
Container mtusi2026lab3-api-5 Created
|
||||||
|
Container mtusi2026lab3-api-5 Starting
|
||||||
|
Container mtusi2026lab3-api-5 Started
|
||||||
|
{"event": "replacement_ready", "utc": "2026-10-29T16:51:28.256136+00:00", "old_container_id": "d180fdf312493c47f36dcf15588a5eb5cc0ece952b3edcfbf0681f68c1738930", "new_container_id": "a87550bfa88fcaa93b6c9566837c824ab587028efe87e8c7646b201e31ff73e6", "old_instance": "d180fdf31249:ce15c606e240", "new_instance": "a87550bfa88f:b26efdce49e9", "step_seconds": 12.064, "other_api_not_restarted": true, "existing_session_works": true, "replay_preserved": true}
|
||||||
|
{"event": "replacement_finished", "utc": "2026-10-29T16:51:31.820921+00:00", "replacements": 2, "final_container_ids": ["a55b0960bdec618c241102e83f0b87d459a6e0b5e8109871e0cc526541f372f5", "a87550bfa88fcaa93b6c9566837c824ab587028efe87e8c7646b201e31ff73e6"]}
|
||||||
|
PASS: both API containers replaced sequentially; existing session and confirmed message preserved.
|
||||||
|
|
||||||
|
Код завершения сценария замены: 0
|
||||||
|
ROLLING COMMAND END: 2026-10-29T16:51:31Z
|
||||||
|
|
||||||
|
=== Состояние ПОСЛЕ замены ===
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
mtusi2026lab3-api-4 mtusi-messenger:lab3 "python -m uvicorn a…" api 32 seconds ago Up 31 seconds (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-api-5 mtusi-messenger:lab3 "python -m uvicorn a…" api 15 seconds ago Up 14 seconds (healthy) 8080/tcp
|
||||||
|
mtusi2026lab3-lb-1 haproxy:3.0.5-bookworm "docker-entrypoint.s…" lb About an hour ago Up 6 minutes 127.0.0.1:18082->8080/tcp
|
||||||
|
mtusi2026lab3-migrate-1 mtusi-messenger:lab3 "python -m app.migra…" migrate About an hour ago Exited (0) 47 minutes ago
|
||||||
|
mtusi2026lab3-postgres-1 postgres:16.4-bookworm "docker-entrypoint.s…" postgres About an hour ago Up 6 minutes (healthy) 5432/tcp
|
||||||
|
mtusi2026lab3-redis-1 redis:7.2.5-bookworm "docker-entrypoint.s…" redis About an hour ago Up 6 minutes (healthy) 6379/tcp
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
=== Smoke после повторной замены API ===
|
||||||
|
UTC: 2026-10-29T16:53:33Z
|
||||||
|
python3 tests/smoke.py --base-url "http://localhost:18082"
|
||||||
|
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
Код завершения make: 0
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
global
|
||||||
|
log stdout format raw local0
|
||||||
|
maxconn 512
|
||||||
|
|
||||||
|
defaults
|
||||||
|
log global
|
||||||
|
mode http
|
||||||
|
option httplog
|
||||||
|
option dontlognull
|
||||||
|
timeout connect 1s
|
||||||
|
timeout client 30s
|
||||||
|
timeout server 30s
|
||||||
|
timeout http-request 10s
|
||||||
|
timeout http-keep-alive 5s
|
||||||
|
timeout queue 3s
|
||||||
|
timeout check 1s
|
||||||
|
retries 0
|
||||||
|
|
||||||
|
resolvers docker
|
||||||
|
nameserver dns 127.0.0.11:53
|
||||||
|
accepted_payload_size 8192
|
||||||
|
resolve_retries 3
|
||||||
|
timeout resolve 1s
|
||||||
|
timeout retry 1s
|
||||||
|
hold valid 1s
|
||||||
|
hold obsolete 1s
|
||||||
|
hold nx 1s
|
||||||
|
hold timeout 1s
|
||||||
|
hold refused 1s
|
||||||
|
hold other 1s
|
||||||
|
|
||||||
|
frontend public_api
|
||||||
|
bind :8080
|
||||||
|
default_backend api_replicas
|
||||||
|
|
||||||
|
backend api_replicas
|
||||||
|
balance roundrobin
|
||||||
|
option httpchk
|
||||||
|
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host localhost
|
||||||
|
http-check expect status 200
|
||||||
|
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 1
|
||||||
|
server-template api 1-4 api:8080 check resolvers docker resolve-prefer ipv4 init-addr none
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
CREATE TABLE users (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
|
||||||
|
CONSTRAINT users_username_unique UNIQUE (username),
|
||||||
|
CONSTRAINT users_username_format
|
||||||
|
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||||
|
CONSTRAINT users_display_name_length
|
||||||
|
CHECK (char_length(display_name) BETWEEN 1 AND 100)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE chats (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
|
||||||
|
CONSTRAINT chats_title_length
|
||||||
|
CHECK (char_length(title) BETWEEN 1 AND 100)
|
||||||
|
);
|
||||||
|
|
||||||
|
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_chat_idx
|
||||||
|
ON chat_members (user_id, chat_id);
|
||||||
|
|
||||||
|
CREATE INDEX chats_created_id_idx
|
||||||
|
ON chats (created_at, id);
|
||||||
|
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID NOT NULL,
|
||||||
|
sender_id UUID NOT NULL,
|
||||||
|
text TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
|
||||||
|
CONSTRAINT messages_sender_membership_fk
|
||||||
|
FOREIGN KEY (chat_id, sender_id)
|
||||||
|
REFERENCES chat_members (chat_id, user_id),
|
||||||
|
|
||||||
|
CONSTRAINT messages_text_length
|
||||||
|
CHECK (char_length(text) BETWEEN 1 AND 4000)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX messages_chat_created_id_idx
|
||||||
|
ON messages (chat_id, created_at, id);
|
||||||
|
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
token_hash TEXT PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT sessions_token_hash_format
|
||||||
|
CHECK (token_hash ~ '^[0-9a-f]{64}$'),
|
||||||
|
CONSTRAINT sessions_expiry_order
|
||||||
|
CHECK (expires_at > created_at)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX sessions_expires_at_idx
|
||||||
|
ON sessions (expires_at);
|
||||||
|
|
||||||
|
CREATE INDEX sessions_user_id_idx
|
||||||
|
ON sessions (user_id);
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
CREATE TABLE message_idempotency (
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||||
|
http_method TEXT NOT NULL DEFAULT 'POST',
|
||||||
|
idempotency_key TEXT NOT NULL,
|
||||||
|
request_text TEXT NOT NULL,
|
||||||
|
message_id UUID NOT NULL REFERENCES messages(id),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
|
||||||
|
PRIMARY KEY (
|
||||||
|
user_id, chat_id, http_method, idempotency_key
|
||||||
|
),
|
||||||
|
|
||||||
|
CONSTRAINT message_idempotency_method
|
||||||
|
CHECK (http_method = 'POST'),
|
||||||
|
|
||||||
|
CONSTRAINT message_idempotency_key_format
|
||||||
|
CHECK (
|
||||||
|
char_length(idempotency_key) BETWEEN 1 AND 128
|
||||||
|
AND idempotency_key ~ '^[A-Za-z0-9._:-]+$'
|
||||||
|
)
|
||||||
|
);
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
fastapi==0.115.12
|
||||||
|
uvicorn[standard]==0.34.2
|
||||||
|
psycopg[binary]==3.2.6
|
||||||
|
psycopg-pool==3.2.6
|
||||||
|
redis==5.2.1
|
||||||
|
argon2-cffi==23.1.0
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||||
|
cd "$ROOT"
|
||||||
|
|
||||||
|
docker compose -p mtusi2026lab3 restart postgres redis api lb
|
||||||
Executable
+42
@@ -0,0 +1,42 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||||
|
cd "$ROOT"
|
||||||
|
|
||||||
|
if [ -z "${TARGET_INSTANCE_ID:-}" ]; then
|
||||||
|
echo "TARGET_INSTANCE_ID is required" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
TARGET_CONTAINER=""
|
||||||
|
MATCHES=0
|
||||||
|
|
||||||
|
for container in $(docker compose -p mtusi2026lab3 ps -q api); do
|
||||||
|
instance_id=$(
|
||||||
|
docker exec "$container" python -c '
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
"http://127.0.0.1:8080/health/live",
|
||||||
|
timeout=2,
|
||||||
|
) as response:
|
||||||
|
print(response.headers.get("X-Instance-Id", ""))
|
||||||
|
' 2>/dev/null
|
||||||
|
) || continue
|
||||||
|
|
||||||
|
if [ "$instance_id" = "$TARGET_INSTANCE_ID" ]; then
|
||||||
|
TARGET_CONTAINER="$container"
|
||||||
|
MATCHES=$((MATCHES + 1))
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "$MATCHES" -ne 1 ]; then
|
||||||
|
echo "Expected exactly one matching API container; found $MATCHES" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Stopping API instance: $TARGET_INSTANCE_ID"
|
||||||
|
docker stop --time 10 "$TARGET_CONTAINER" >/dev/null
|
||||||
|
|
||||||
|
echo "Target API container stopped"
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
from collections import Counter
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / "tests"))
|
||||||
|
|
||||||
|
from client import Client, arguments, check, run
|
||||||
|
from resilience import history
|
||||||
|
|
||||||
|
|
||||||
|
WORKERS = 12
|
||||||
|
ROUNDS = 3
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = arguments("Concurrent cross-replica idempotency")
|
||||||
|
|
||||||
|
control = Client(
|
||||||
|
args.base_url,
|
||||||
|
args.ca_file,
|
||||||
|
timeout=10,
|
||||||
|
)
|
||||||
|
alice, bob, eve, chat = control.bootstrap()
|
||||||
|
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||||
|
|
||||||
|
check(
|
||||||
|
history(control, alice, chat) == [],
|
||||||
|
"fresh test chat is not empty",
|
||||||
|
)
|
||||||
|
|
||||||
|
clients = [
|
||||||
|
Client(args.base_url, args.ca_file, timeout=10)
|
||||||
|
for _ in range(WORKERS)
|
||||||
|
]
|
||||||
|
|
||||||
|
saved_messages = []
|
||||||
|
round_results = []
|
||||||
|
first_key = None
|
||||||
|
|
||||||
|
for round_number in range(1, ROUNDS + 1):
|
||||||
|
key = uuid.uuid4().hex
|
||||||
|
text = f"Один ключ — одно сообщение: {round_number} {key}"
|
||||||
|
|
||||||
|
if first_key is None:
|
||||||
|
first_key = key
|
||||||
|
|
||||||
|
barrier = threading.Barrier(WORKERS)
|
||||||
|
|
||||||
|
def send(index):
|
||||||
|
if index % 3 == 0:
|
||||||
|
body = {"text": text}
|
||||||
|
elif index % 3 == 1:
|
||||||
|
body = {
|
||||||
|
"attachment_ids": [],
|
||||||
|
"text": text,
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
body = {
|
||||||
|
"text": text,
|
||||||
|
"attachment_ids": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
raw = json.dumps(
|
||||||
|
body,
|
||||||
|
ensure_ascii=False,
|
||||||
|
indent=2 if index % 2 else None,
|
||||||
|
).encode("utf-8")
|
||||||
|
|
||||||
|
barrier.wait(timeout=15)
|
||||||
|
|
||||||
|
return clients[index].call(
|
||||||
|
"POST",
|
||||||
|
path,
|
||||||
|
expected=201,
|
||||||
|
actor=alice,
|
||||||
|
raw=raw,
|
||||||
|
headers={
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Idempotency-Key": key,
|
||||||
|
},
|
||||||
|
schema="Message",
|
||||||
|
)
|
||||||
|
|
||||||
|
started = time.monotonic()
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=WORKERS) as executor:
|
||||||
|
responses = list(executor.map(send, range(WORKERS)))
|
||||||
|
|
||||||
|
elapsed = time.monotonic() - started
|
||||||
|
|
||||||
|
original = responses[0]["json"]
|
||||||
|
|
||||||
|
check(
|
||||||
|
all(
|
||||||
|
response["json"] == original
|
||||||
|
for response in responses
|
||||||
|
),
|
||||||
|
"same key returned different Message objects",
|
||||||
|
)
|
||||||
|
|
||||||
|
instances = Counter(
|
||||||
|
response["headers"]["X-Instance-Id"]
|
||||||
|
for response in responses
|
||||||
|
)
|
||||||
|
|
||||||
|
check(
|
||||||
|
len(instances) >= 2,
|
||||||
|
"concurrent requests did not reach two replicas",
|
||||||
|
)
|
||||||
|
|
||||||
|
messages = history(control, bob, chat)
|
||||||
|
same_text = [
|
||||||
|
message
|
||||||
|
for message in messages
|
||||||
|
if message["text"] == text
|
||||||
|
]
|
||||||
|
|
||||||
|
check(
|
||||||
|
same_text == [original],
|
||||||
|
"concurrent repeats created zero or multiple messages",
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
len(messages) == round_number,
|
||||||
|
"unexpected message count after concurrent round",
|
||||||
|
)
|
||||||
|
|
||||||
|
saved_messages.append(original)
|
||||||
|
|
||||||
|
result = {
|
||||||
|
"round": round_number,
|
||||||
|
"requests": WORKERS,
|
||||||
|
"responses_201": len(responses),
|
||||||
|
"observed_instances": len(instances),
|
||||||
|
"responses_by_instance": dict(instances),
|
||||||
|
"unique_message_ids": len(
|
||||||
|
{
|
||||||
|
response["json"]["id"]
|
||||||
|
for response in responses
|
||||||
|
}
|
||||||
|
),
|
||||||
|
"matching_history_messages": len(same_text),
|
||||||
|
"duration_seconds": round(elapsed, 3),
|
||||||
|
}
|
||||||
|
round_results.append(result)
|
||||||
|
print(json.dumps(result, ensure_ascii=False))
|
||||||
|
|
||||||
|
conflict = control.call(
|
||||||
|
"POST",
|
||||||
|
path,
|
||||||
|
expected=409,
|
||||||
|
actor=alice,
|
||||||
|
body={"text": "Другой текст с прежним ключом"},
|
||||||
|
headers={"Idempotency-Key": first_key},
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
conflict["json"]["error"]["code"] == "conflict",
|
||||||
|
"wrong error code for body conflict",
|
||||||
|
)
|
||||||
|
|
||||||
|
control.call(
|
||||||
|
"POST",
|
||||||
|
path,
|
||||||
|
expected=400,
|
||||||
|
actor=alice,
|
||||||
|
body={"text": "Без ключа"},
|
||||||
|
)
|
||||||
|
|
||||||
|
for invalid_key in ("bad key", "x" * 129):
|
||||||
|
control.call(
|
||||||
|
"POST",
|
||||||
|
path,
|
||||||
|
expected=400,
|
||||||
|
actor=alice,
|
||||||
|
body={"text": "Некорректный ключ"},
|
||||||
|
headers={"Idempotency-Key": invalid_key},
|
||||||
|
)
|
||||||
|
|
||||||
|
control.call(
|
||||||
|
"POST",
|
||||||
|
path,
|
||||||
|
expected=404,
|
||||||
|
actor=eve,
|
||||||
|
body={"text": saved_messages[0]["text"]},
|
||||||
|
headers={"Idempotency-Key": first_key},
|
||||||
|
)
|
||||||
|
|
||||||
|
bob_message = control.message(
|
||||||
|
bob,
|
||||||
|
chat,
|
||||||
|
"Тот же ключ другого пользователя",
|
||||||
|
key=first_key,
|
||||||
|
)["json"]
|
||||||
|
|
||||||
|
check(
|
||||||
|
bob_message["sender_id"] == bob["id"],
|
||||||
|
"wrong sender for another user's scope",
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
bob_message["id"] != saved_messages[0]["id"],
|
||||||
|
"key incorrectly shared between users",
|
||||||
|
)
|
||||||
|
|
||||||
|
second_chat = control.call(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/chats",
|
||||||
|
expected=201,
|
||||||
|
actor=alice,
|
||||||
|
body={
|
||||||
|
"title": "Другой чат для области ключа",
|
||||||
|
"member_ids": [alice["id"], bob["id"]],
|
||||||
|
},
|
||||||
|
schema="Chat",
|
||||||
|
)["json"]
|
||||||
|
|
||||||
|
other_chat_message = control.message(
|
||||||
|
alice,
|
||||||
|
second_chat,
|
||||||
|
"Тот же ключ в другом чате",
|
||||||
|
key=first_key,
|
||||||
|
)["json"]
|
||||||
|
|
||||||
|
check(
|
||||||
|
other_chat_message["chat_id"] == second_chat["id"],
|
||||||
|
"wrong chat in scoped result",
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
other_chat_message["id"] != saved_messages[0]["id"],
|
||||||
|
"key incorrectly shared between chats",
|
||||||
|
)
|
||||||
|
|
||||||
|
replay = control.message(
|
||||||
|
alice,
|
||||||
|
chat,
|
||||||
|
saved_messages[0]["text"],
|
||||||
|
key=first_key,
|
||||||
|
)["json"]
|
||||||
|
|
||||||
|
check(
|
||||||
|
replay == saved_messages[0],
|
||||||
|
"original result changed after scope tests",
|
||||||
|
)
|
||||||
|
|
||||||
|
messages = history(control, bob, chat)
|
||||||
|
expected = saved_messages + [bob_message]
|
||||||
|
|
||||||
|
check(
|
||||||
|
len(messages) == len(expected),
|
||||||
|
"unexpected final message count",
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
{message["id"] for message in messages}
|
||||||
|
== {message["id"] for message in expected},
|
||||||
|
"missing or extra messages in first chat",
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
history(control, bob, second_chat) == [other_chat_message],
|
||||||
|
"unexpected history in second chat",
|
||||||
|
)
|
||||||
|
|
||||||
|
control.call(
|
||||||
|
"DELETE",
|
||||||
|
"/api/v1/auth/sessions/current",
|
||||||
|
expected=204,
|
||||||
|
actor=alice,
|
||||||
|
)
|
||||||
|
|
||||||
|
control.call(
|
||||||
|
"POST",
|
||||||
|
path,
|
||||||
|
expected=401,
|
||||||
|
actor=alice,
|
||||||
|
body={"text": saved_messages[0]["text"]},
|
||||||
|
headers={"Idempotency-Key": first_key},
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"rounds": ROUNDS,
|
||||||
|
"concurrent_requests_per_round": WORKERS,
|
||||||
|
"concurrent_requests_total": WORKERS * ROUNDS,
|
||||||
|
"body_conflict_409": True,
|
||||||
|
"missing_and_invalid_key_400": True,
|
||||||
|
"foreign_user_404": True,
|
||||||
|
"user_scope_independent": True,
|
||||||
|
"chat_scope_independent": True,
|
||||||
|
"replay_preserved": True,
|
||||||
|
"revoked_session_401": True,
|
||||||
|
"unexpected_messages": 0,
|
||||||
|
},
|
||||||
|
ensure_ascii=False,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
"PASS: concurrent cross-replica idempotency, "
|
||||||
|
"scope, validation and authorization checks."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run(main)
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / "tests"))
|
||||||
|
|
||||||
|
from client import Client, Failure, arguments, check, run
|
||||||
|
|
||||||
|
|
||||||
|
PROJECT = "mtusi2026lab3"
|
||||||
|
|
||||||
|
|
||||||
|
def timestamp():
|
||||||
|
return datetime.now(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def command(*args):
|
||||||
|
return subprocess.check_output(
|
||||||
|
list(args),
|
||||||
|
cwd=ROOT,
|
||||||
|
text=True,
|
||||||
|
timeout=45,
|
||||||
|
).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args):
|
||||||
|
return command(
|
||||||
|
"docker",
|
||||||
|
"compose",
|
||||||
|
"-p",
|
||||||
|
PROJECT,
|
||||||
|
*args,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def inspect(container, template):
|
||||||
|
return command(
|
||||||
|
"docker",
|
||||||
|
"inspect",
|
||||||
|
"--format",
|
||||||
|
template,
|
||||||
|
container,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def api_ids():
|
||||||
|
ids = compose("ps", "-q", "api").split()
|
||||||
|
return {
|
||||||
|
inspect(container, "{{.Id}}")
|
||||||
|
for container in ids
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def healthy(container):
|
||||||
|
return inspect(
|
||||||
|
container,
|
||||||
|
"{{.State.Running}} {{.State.Health.Status}}",
|
||||||
|
) == "true healthy"
|
||||||
|
|
||||||
|
|
||||||
|
def instance_id(container):
|
||||||
|
code = (
|
||||||
|
"import urllib.request; "
|
||||||
|
"r=urllib.request.urlopen("
|
||||||
|
"'http://127.0.0.1:8080/health/live', timeout=2); "
|
||||||
|
"print(r.headers.get('X-Instance-Id', '')); "
|
||||||
|
"r.close()"
|
||||||
|
)
|
||||||
|
return command(
|
||||||
|
"docker",
|
||||||
|
"exec",
|
||||||
|
container,
|
||||||
|
"python",
|
||||||
|
"-c",
|
||||||
|
code,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = arguments("Sequential API container replacement")
|
||||||
|
|
||||||
|
client = Client(
|
||||||
|
args.base_url,
|
||||||
|
args.ca_file,
|
||||||
|
timeout=2,
|
||||||
|
)
|
||||||
|
alice, bob, eve, chat = client.bootstrap()
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
key = uuid.uuid4().hex
|
||||||
|
text = "Сохранить при замене " + key
|
||||||
|
|
||||||
|
original_message = client.message(
|
||||||
|
alice,
|
||||||
|
chat,
|
||||||
|
text,
|
||||||
|
key=key,
|
||||||
|
)["json"]
|
||||||
|
|
||||||
|
original_ids = sorted(api_ids())
|
||||||
|
check(len(original_ids) == 2, "expected exactly two API containers")
|
||||||
|
|
||||||
|
for container in original_ids:
|
||||||
|
check(healthy(container), "both API containers must be healthy")
|
||||||
|
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"event": "replacement_started",
|
||||||
|
"utc": timestamp(),
|
||||||
|
"original_container_ids": original_ids,
|
||||||
|
},
|
||||||
|
ensure_ascii=False,
|
||||||
|
),
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
replacements = []
|
||||||
|
|
||||||
|
for old in original_ids:
|
||||||
|
current = api_ids()
|
||||||
|
check(len(current) == 2, "expected two APIs before replacement")
|
||||||
|
check(old in current, "original target container is missing")
|
||||||
|
|
||||||
|
other = next(container for container in current if container != old)
|
||||||
|
check(healthy(other), "remaining API is not healthy")
|
||||||
|
|
||||||
|
other_started = inspect(other, "{{.State.StartedAt}}")
|
||||||
|
old_instance = instance_id(old)
|
||||||
|
step_started = time.monotonic()
|
||||||
|
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"event": "replacing",
|
||||||
|
"utc": timestamp(),
|
||||||
|
"old_container_id": old,
|
||||||
|
"old_instance": old_instance,
|
||||||
|
"remaining_container_id": other,
|
||||||
|
},
|
||||||
|
ensure_ascii=False,
|
||||||
|
),
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
command("docker", "stop", "--time", "10", old)
|
||||||
|
command("docker", "rm", old)
|
||||||
|
|
||||||
|
compose(
|
||||||
|
"up",
|
||||||
|
"-d",
|
||||||
|
"--no-deps",
|
||||||
|
"--no-recreate",
|
||||||
|
"--no-build",
|
||||||
|
"--scale",
|
||||||
|
"api=2",
|
||||||
|
"api",
|
||||||
|
)
|
||||||
|
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
replacement = None
|
||||||
|
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
current = api_ids()
|
||||||
|
candidates = current - {other}
|
||||||
|
|
||||||
|
if (
|
||||||
|
len(current) == 2
|
||||||
|
and len(candidates) == 1
|
||||||
|
and other in current
|
||||||
|
):
|
||||||
|
candidate = next(iter(candidates))
|
||||||
|
if candidate != old and healthy(candidate):
|
||||||
|
replacement = candidate
|
||||||
|
break
|
||||||
|
|
||||||
|
time.sleep(0.5)
|
||||||
|
|
||||||
|
check(replacement is not None, "replacement did not become healthy")
|
||||||
|
|
||||||
|
new_instance = instance_id(replacement)
|
||||||
|
check(new_instance != old_instance, "instance did not change")
|
||||||
|
|
||||||
|
seen_through_lb = False
|
||||||
|
deadline = time.monotonic() + 20
|
||||||
|
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
response = client.call(
|
||||||
|
"GET",
|
||||||
|
"/api/v1/users/me",
|
||||||
|
actor=alice,
|
||||||
|
schema="User",
|
||||||
|
)
|
||||||
|
except Failure:
|
||||||
|
time.sleep(0.2)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if response["headers"]["X-Instance-Id"] == new_instance:
|
||||||
|
seen_through_lb = True
|
||||||
|
break
|
||||||
|
|
||||||
|
time.sleep(0.2)
|
||||||
|
|
||||||
|
check(
|
||||||
|
seen_through_lb,
|
||||||
|
"new API was not observed through LB with existing session",
|
||||||
|
)
|
||||||
|
check(healthy(other), "remaining API became unhealthy")
|
||||||
|
check(
|
||||||
|
inspect(other, "{{.State.StartedAt}}") == other_started,
|
||||||
|
"the other API was restarted unexpectedly",
|
||||||
|
)
|
||||||
|
|
||||||
|
replay = client.message(
|
||||||
|
alice,
|
||||||
|
chat,
|
||||||
|
text,
|
||||||
|
key=key,
|
||||||
|
)["json"]
|
||||||
|
|
||||||
|
check(
|
||||||
|
replay == original_message,
|
||||||
|
"confirmed message or idempotency result changed",
|
||||||
|
)
|
||||||
|
|
||||||
|
result = {
|
||||||
|
"event": "replacement_ready",
|
||||||
|
"utc": timestamp(),
|
||||||
|
"old_container_id": old,
|
||||||
|
"new_container_id": replacement,
|
||||||
|
"old_instance": old_instance,
|
||||||
|
"new_instance": new_instance,
|
||||||
|
"step_seconds": round(
|
||||||
|
time.monotonic() - step_started, 3
|
||||||
|
),
|
||||||
|
"other_api_not_restarted": True,
|
||||||
|
"existing_session_works": True,
|
||||||
|
"replay_preserved": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
replacements.append(result)
|
||||||
|
print(json.dumps(result, ensure_ascii=False), flush=True)
|
||||||
|
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
final_ids = api_ids()
|
||||||
|
|
||||||
|
check(len(final_ids) == 2, "expected two APIs after replacement")
|
||||||
|
check(
|
||||||
|
not final_ids.intersection(original_ids),
|
||||||
|
"some original API containers were not replaced",
|
||||||
|
)
|
||||||
|
|
||||||
|
for container in final_ids:
|
||||||
|
check(healthy(container), "final API is not healthy")
|
||||||
|
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"event": "replacement_finished",
|
||||||
|
"utc": timestamp(),
|
||||||
|
"replacements": len(replacements),
|
||||||
|
"final_container_ids": sorted(final_ids),
|
||||||
|
},
|
||||||
|
ensure_ascii=False,
|
||||||
|
),
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
"PASS: both API containers replaced sequentially; "
|
||||||
|
"existing session and confirmed message preserved.",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run(main)
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Targeted API failure test. Uses synthetic data; leaves target stopped."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / "tests"))
|
||||||
|
|
||||||
|
from client import Client, Failure, arguments, check, run
|
||||||
|
from resilience import history
|
||||||
|
|
||||||
|
|
||||||
|
PROJECT = "mtusi2026lab3"
|
||||||
|
|
||||||
|
|
||||||
|
def docker_output(*args):
|
||||||
|
return subprocess.check_output(
|
||||||
|
["docker", *args],
|
||||||
|
cwd=ROOT,
|
||||||
|
text=True,
|
||||||
|
).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def target_instance(container):
|
||||||
|
labels = json.loads(
|
||||||
|
docker_output(
|
||||||
|
"inspect",
|
||||||
|
"--format",
|
||||||
|
"{{json .Config.Labels}}",
|
||||||
|
container,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
check(
|
||||||
|
labels.get("com.docker.compose.project") == PROJECT,
|
||||||
|
"target belongs to another Compose project",
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
labels.get("com.docker.compose.service") == "api",
|
||||||
|
"target is not an API container",
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
docker_output(
|
||||||
|
"inspect",
|
||||||
|
"--format",
|
||||||
|
"{{.State.Running}}",
|
||||||
|
container,
|
||||||
|
) == "true",
|
||||||
|
"target container is not running",
|
||||||
|
)
|
||||||
|
|
||||||
|
code = (
|
||||||
|
"import urllib.request; "
|
||||||
|
"r=urllib.request.urlopen("
|
||||||
|
"'http://127.0.0.1:8080/health/live', timeout=2); "
|
||||||
|
"print(r.headers.get('X-Instance-Id', '')); "
|
||||||
|
"r.close()"
|
||||||
|
)
|
||||||
|
|
||||||
|
instance = docker_output(
|
||||||
|
"exec", container, "python", "-c", code
|
||||||
|
)
|
||||||
|
check(bool(instance), "target has no X-Instance-Id")
|
||||||
|
return instance
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
def configure(parser):
|
||||||
|
parser.add_argument(
|
||||||
|
"--target-container",
|
||||||
|
required=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
args = arguments(
|
||||||
|
"Targeted API failover through the load balancer",
|
||||||
|
configure,
|
||||||
|
)
|
||||||
|
|
||||||
|
script = ROOT / "scripts" / "stop-one.sh"
|
||||||
|
check(
|
||||||
|
script.is_file() and os.access(script, os.X_OK),
|
||||||
|
"stop-one.sh must exist and be executable",
|
||||||
|
)
|
||||||
|
|
||||||
|
target = target_instance(args.target_container)
|
||||||
|
client = Client(args.base_url, args.ca_file, timeout=2)
|
||||||
|
|
||||||
|
alice, bob, eve, chat = client.bootstrap()
|
||||||
|
|
||||||
|
original_key = uuid.uuid4().hex
|
||||||
|
original_text = "Подтверждено до отказа " + original_key
|
||||||
|
original = client.message(
|
||||||
|
alice,
|
||||||
|
chat,
|
||||||
|
original_text,
|
||||||
|
key=original_key,
|
||||||
|
)["json"]
|
||||||
|
|
||||||
|
observed = set()
|
||||||
|
for _ in range(40):
|
||||||
|
response = client.call(
|
||||||
|
"GET",
|
||||||
|
"/api/v1/users/me",
|
||||||
|
actor=alice,
|
||||||
|
schema="User",
|
||||||
|
)
|
||||||
|
observed.add(response["headers"]["X-Instance-Id"])
|
||||||
|
|
||||||
|
check(len(observed) >= 2, "less than two API instances")
|
||||||
|
check(target in observed, "target is not observed through LB")
|
||||||
|
|
||||||
|
env = dict(os.environ)
|
||||||
|
env["TARGET_INSTANCE_ID"] = target
|
||||||
|
|
||||||
|
print(
|
||||||
|
"Target container:",
|
||||||
|
args.target_container,
|
||||||
|
"| instance:",
|
||||||
|
target,
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
started = time.monotonic()
|
||||||
|
proc = subprocess.Popen(
|
||||||
|
[str(script)],
|
||||||
|
cwd=ROOT,
|
||||||
|
env=env,
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
)
|
||||||
|
|
||||||
|
successes = []
|
||||||
|
write_failures = 0
|
||||||
|
read_successes = 0
|
||||||
|
read_failures = 0
|
||||||
|
after_instances = []
|
||||||
|
first_recovery = None
|
||||||
|
attempts = 0
|
||||||
|
|
||||||
|
key = uuid.uuid4().hex
|
||||||
|
text = "Во время отказа " + key
|
||||||
|
|
||||||
|
try:
|
||||||
|
while time.monotonic() - started < 15:
|
||||||
|
code = proc.poll()
|
||||||
|
elapsed = time.monotonic() - started
|
||||||
|
|
||||||
|
check(
|
||||||
|
code is None or code == 0,
|
||||||
|
"stop-one hook failed",
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
code is not None or elapsed < 10,
|
||||||
|
"stop-one hook exceeded 10 seconds",
|
||||||
|
)
|
||||||
|
|
||||||
|
attempts += 1
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = client.message(
|
||||||
|
alice,
|
||||||
|
chat,
|
||||||
|
text,
|
||||||
|
key=key,
|
||||||
|
)
|
||||||
|
except Failure:
|
||||||
|
write_failures += 1
|
||||||
|
# Keep the same key and text after uncertain POST.
|
||||||
|
else:
|
||||||
|
successes.append(response["json"])
|
||||||
|
|
||||||
|
if proc.poll() == 0:
|
||||||
|
if first_recovery is None:
|
||||||
|
first_recovery = time.monotonic() - started
|
||||||
|
|
||||||
|
after_instances.append(
|
||||||
|
response["headers"]["X-Instance-Id"]
|
||||||
|
)
|
||||||
|
|
||||||
|
key = uuid.uuid4().hex
|
||||||
|
text = "Во время отказа " + key
|
||||||
|
|
||||||
|
if attempts % 5 == 0:
|
||||||
|
try:
|
||||||
|
page = client.call(
|
||||||
|
"GET",
|
||||||
|
(
|
||||||
|
"/api/v1/chats/"
|
||||||
|
+ chat["id"]
|
||||||
|
+ "/messages?limit=100"
|
||||||
|
),
|
||||||
|
actor=bob,
|
||||||
|
schema="MessagePage",
|
||||||
|
)["json"]
|
||||||
|
except Failure:
|
||||||
|
read_failures += 1
|
||||||
|
else:
|
||||||
|
check(
|
||||||
|
any(
|
||||||
|
message == original
|
||||||
|
for message in page["items"]
|
||||||
|
),
|
||||||
|
"confirmed message absent during read",
|
||||||
|
)
|
||||||
|
read_successes += 1
|
||||||
|
|
||||||
|
time.sleep(0.1)
|
||||||
|
|
||||||
|
elapsed = time.monotonic() - started
|
||||||
|
|
||||||
|
check(proc.poll() == 0, "stop-one hook did not finish")
|
||||||
|
check(
|
||||||
|
first_recovery is not None and first_recovery <= 10,
|
||||||
|
"writes did not recover within 10 seconds",
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
len(after_instances) >= 5,
|
||||||
|
"too few writes after stop",
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
target not in after_instances[-5:],
|
||||||
|
"stopped instance still serves requests",
|
||||||
|
)
|
||||||
|
check(read_successes > 0, "no successful history reads")
|
||||||
|
|
||||||
|
check(
|
||||||
|
docker_output(
|
||||||
|
"inspect",
|
||||||
|
"--format",
|
||||||
|
"{{.State.Running}}",
|
||||||
|
args.target_container,
|
||||||
|
) == "false",
|
||||||
|
"target container is still running",
|
||||||
|
)
|
||||||
|
|
||||||
|
replay = client.message(
|
||||||
|
alice,
|
||||||
|
chat,
|
||||||
|
original_text,
|
||||||
|
key=original_key,
|
||||||
|
)["json"]
|
||||||
|
|
||||||
|
check(
|
||||||
|
replay == original,
|
||||||
|
"replay after failure returned another message",
|
||||||
|
)
|
||||||
|
|
||||||
|
messages = history(client, bob, chat)
|
||||||
|
by_id = {message["id"]: message for message in messages}
|
||||||
|
|
||||||
|
check(
|
||||||
|
len(by_id) == len(messages),
|
||||||
|
"duplicate message IDs",
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
by_id.get(original["id"]) == original,
|
||||||
|
"pre-failure message lost or altered",
|
||||||
|
)
|
||||||
|
|
||||||
|
for message in successes:
|
||||||
|
check(
|
||||||
|
by_id.get(message["id"]) == message,
|
||||||
|
"confirmed in-flight message lost or altered",
|
||||||
|
)
|
||||||
|
|
||||||
|
texts = [message["text"] for message in messages]
|
||||||
|
check(
|
||||||
|
len(texts) == len(set(texts)),
|
||||||
|
"retry created duplicate message text",
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"target_container": args.target_container,
|
||||||
|
"target_instance": target,
|
||||||
|
"observed_instances_before": len(observed),
|
||||||
|
"duration_seconds": round(elapsed, 3),
|
||||||
|
"successful_writes": len(successes),
|
||||||
|
"failed_write_attempts": write_failures,
|
||||||
|
"successful_reads": read_successes,
|
||||||
|
"failed_read_attempts": read_failures,
|
||||||
|
"successful_write_rps": round(
|
||||||
|
len(successes) / elapsed, 3
|
||||||
|
),
|
||||||
|
"first_recovery_seconds": round(
|
||||||
|
first_recovery, 3
|
||||||
|
),
|
||||||
|
"replay_preserved": True,
|
||||||
|
"target_stopped": True,
|
||||||
|
},
|
||||||
|
ensure_ascii=False,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
"PASS: targeted failover; session, messages "
|
||||||
|
"and replay preserved. Target remains stopped."
|
||||||
|
)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if proc.poll() is None:
|
||||||
|
proc.terminate()
|
||||||
|
try:
|
||||||
|
proc.wait(timeout=5)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
proc.kill()
|
||||||
|
proc.wait()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run(main)
|
||||||
Reference in New Issue
Block a user