Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d9e13a06d9 |
+4
-5
@@ -1,13 +1,12 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
# Скопировать в .env. Секреты сюда не класть: их создаёт scripts/bootstrap.py в secrets/.
|
||||
# APP_PORT — порт балансировщика на localhost. Реплики API наружу не публикуются.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
SESSION_STORE=redis
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
POOL_MAX=10
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
*.sh text eol=lf
|
||||
*.cfg text eol=lf
|
||||
Dockerfile text eol=lf
|
||||
*.sql text eol=lf
|
||||
@@ -1,18 +1,18 @@
|
||||
## Лабораторная 3
|
||||
|
||||
Автор / группа: TODO
|
||||
Целевая оценка (3/4/5): TODO
|
||||
Трек 5, если заявлен: TODO
|
||||
Автор / группа: Орлова В. / БПИ2301
|
||||
Целевая оценка (3/4/5): 5
|
||||
Трек 5, если заявлен: 1, цена масштабирования
|
||||
|
||||
Что реализовано и что перенесено: TODO
|
||||
Команды запуска из чистого clone: TODO
|
||||
Результаты проверок и ссылка на REPORT.md: TODO
|
||||
Ограничения / известные ошибки: TODO
|
||||
Источники и использование ИИ: TODO
|
||||
Что реализовано и что перенесено: из lab2 перенесены Postgres, Redis-сессии, Argon2id, cursor и проверка UUID без учёта регистра. Добавлены HAProxy, две и более реплик API без публикации их портов, отдельный сервис миграций, `X-Instance-Id`, общий `Idempotency-Key`.
|
||||
Команды запуска из чистого clone: `python scripts/bootstrap.py`, затем `docker compose --env-file .env up -d --build --scale api=2`, затем `python scripts/wait_ready.py`. Подробности и проверка отказов — в REPORT.md.
|
||||
Результаты проверок и ссылка на REPORT.md: `scripts/check_contract.py` и `tests/smoke.py` (это цели make check и make test; утилиты make на машине нет) PASS, persistence и два failover PASS. Поочерёдный отказ и rolling — evidence/grade4.txt, трек 1 — evidence/track1_*. REPORT.md.
|
||||
Ограничения / известные ошибки: один хост, один LB и одна база остаются единой точкой отказа. Пул 2 быстрее на независимых вставках, но по умолчанию оставлен 10 из-за пачки одинаковых ключей.
|
||||
Источники и использование ИИ: lab2, документация Postgres/Redis/HAProxy, RFC 7617. Реализацию и отчёт готовила с помощью Cursor, прогоны локальные.
|
||||
|
||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [ ] Контракт и публичные тесты не ослаблены.
|
||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [x] Контракт и публичные тесты не ослаблены.
|
||||
- [x] make check и make test выполнены; приложен реальный вывод.
|
||||
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
FROM python:3.12.10-slim-bookworm
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PYTHONPATH=/app/src \
|
||||
APP_HOST=0.0.0.0 \
|
||||
APP_PORT=8080
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN useradd --uid 10001 --create-home --shell /usr/sbin/nologin app
|
||||
|
||||
COPY requirements.txt /app/requirements.txt
|
||||
RUN pip install --no-cache-dir --upgrade pip==25.0.1 \
|
||||
&& pip install --no-cache-dir -r /app/requirements.txt
|
||||
|
||||
COPY migrations /app/migrations
|
||||
COPY src /app/src
|
||||
|
||||
USER 10001
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=25s --retries=8 \
|
||||
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)"
|
||||
|
||||
CMD ["python", "/app/src/main.py"]
|
||||
@@ -1,37 +1,173 @@
|
||||
# Отчёт — лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Орлова В. / БПИ2301
|
||||
- Целевая оценка; выбранный трек 5: 5, трек 1 (цена масштабирования). Трек 2 не брала: на одном Docker-хосте нельзя честно показать потерю узла.
|
||||
- Commit/PR: не публиковала
|
||||
- Использованные источники, библиотеки и помощь ИИ: код lab2 (FastAPI, Postgres, Redis, Argon2id, cursor, Basic/Bearer). Новое: HAProxy 2.8, общая идемпотентность в Postgres, отдельный контейнер миграций. Образы и документация: PostgreSQL 16, Redis AOF, HAProxy `server-template` и health checks, RFC 7617. Реализацию и текст отчёта готовила с помощью Cursor; команды и измерения ниже прогнала локально и могу объяснить.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Docker и Python 3.11+ на хосте (тесты). Секретов в репозитории нет. На Windows официальные hook — это shell-скрипты, их запускала из WSL, где есть `python3` и `docker`. На Linux достаточно `chmod +x` и `python3`. У меня консоль Windows в cp1251, поэтому локально к `python` добавляла `-X utf8`. На Linux это не нужно.
|
||||
|
||||
```sh
|
||||
python scripts/bootstrap.py
|
||||
docker compose --env-file .env up -d --build --scale api=2
|
||||
python scripts/wait_ready.py
|
||||
python tests/smoke.py --base-url http://127.0.0.1:8080
|
||||
```
|
||||
|
||||
`bootstrap.py` один раз пишет `.env` и `secrets/` (пароль Postgres и URL Redis/Postgres). В консоль пароль не печатает и повторно файлы не перезаписывает: volume уже инициализирован этим паролем.
|
||||
|
||||
Дальше:
|
||||
|
||||
```sh
|
||||
chmod +x scripts/restart.sh scripts/stop-one.sh scripts/rolling-restart.sh
|
||||
python tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url http://127.0.0.1:8080
|
||||
python tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url http://127.0.0.1:8080
|
||||
# hook оставляет реплику остановленной. Вернуть:
|
||||
docker compose --env-file .env start api
|
||||
python tests/load.py --base-url http://127.0.0.1:8080 --duration 20 --concurrency 8 --output evidence/load.json
|
||||
python student-tests/run.py
|
||||
python student-tests/run_grade4.py
|
||||
python student-tests/run_track1.py
|
||||
python student-tests/run_track1_db.py
|
||||
```
|
||||
|
||||
Остановка без удаления данных: `docker compose --env-file .env stop`.
|
||||
Снести учебные данные: `docker compose --env-file .env down -v`. Пароль в `secrets/` после этого подходит к новому пустому volume. Новый пароль — удалить `secrets/` и снова запустить bootstrap.
|
||||
|
||||
Образы, не `latest`:
|
||||
|
||||
| Образ | Digest |
|
||||
| --- | --- |
|
||||
| `python:3.12.10-slim-bookworm` | `sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db` |
|
||||
| `postgres:16.10-bookworm` | `sha256:38471f330eb885e04de130b768d6db4e10469e2311879c7e5c699f6d2d8a1c74` |
|
||||
| `redis:7.4.2-bookworm` | `sha256:fbdbaea47b9ae4ecc2082ecdb4e1cea81e32176ffb1dcf643d422ad07427e5d9` |
|
||||
| `haproxy:2.8.14` | `sha256:2344d1efbf7a932c7a3d49b60748c28af81c70fd11fcadd983e2be1f0376a69d` |
|
||||
|
||||
Свой API собирается в `mtusi-lab3-api:local`. Процесс внутри — пользователь 10001. Снаружи опубликован только `127.0.0.1:8080` у HAProxy. У реплик API `PortBindings` пустой.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Из lab2 перенесены пользователи, чаты, keyset-история, Argon2id, сессии в Redis и атомарное создание чата. In-memory состояния по-прежнему нет. Канонический UUID для участников чата тоже остался: один и тот же id в разном регистре — это один участник, ответ 400, строка чата не создаётся.
|
||||
|
||||
Клиент ходит только в HAProxy. Дальше round-robin по репликам API. Sticky cookie нет: иначе разные `X-Instance-Id` одной сессии были бы случайностью, а не свойством стенда. Сессия лежит в общем Redis, поэтому второй процесс принимает тот же Bearer.
|
||||
|
||||
`X-Instance-Id` — hostname контейнера. Docker ставит его равным id контейнера и не меняет, пока контейнер жив. `scripts/stop-one.sh` ищет API этого проекта с таким hostname и делает `docker stop --time 5`. Это учебный alias lab3. Для lab7 он слишком говорящий, там понадобится отдельное случайное имя.
|
||||
|
||||
Postgres — источник истины для пользователей, чатов, сообщений и результатов идемпотентности. Redis хранит только сессии (`appendonly yes`, `appendfsync everysec`, volume `/data`). Историю в Redis не клала.
|
||||
|
||||
Идемпотентность — таблица `idempotency_keys`. Область: пользователь + `POST` + путь чата + ключ. Каноническое тело — JSON с отсортированными ключами, где пропущенный `attachment_ids` равен `[]`. Непустой список вложений в этой лабе отклоняется: файлов ещё нет. В одной транзакции с `INSERT` сообщения берётся `pg_advisory_xact_lock` по хешу области. Повтор того же тела читает уже записанное сообщение и возвращает тот же 201. Другое тело — 409, второй строки нет. Откат транзакции не оставляет ключ занятым, поэтому 5xx можно повторить тем же ключом. Срок — `IDEMPOTENCY_TTL_SECONDS`, по умолчанию 86400, сравнение делает Postgres. Чужой пользователь или другой чат с тем же ключом — отдельная область. Повтор всё равно начинается с проверки сессии и членства.
|
||||
|
||||
Миграции выполняет одноразовый сервис `migrate` и выходит. Реплики API схему не накатывают: они ждут строку `002_idempotency` в `schema_migrations`. Повторный запуск migrate пишет `already applied`. Добавляется только новая таблица, старые таблицы lab2 не меняются.
|
||||
|
||||
`/health/live` смотрит только процесс. `/health/ready` — 200, если не идёт остановка, в базе есть версия `002_idempotency` и Redis отвечает на ping. Иначе 503 без имени хранилища. HAProxy опрашивает именно ready.
|
||||
|
||||
Проверки LB, из `infra/haproxy.cfg`:
|
||||
|
||||
- период `inter 500ms`, `fall 2`, `rise 2`, `timeout check 800ms`, `timeout connect 500ms`
|
||||
- верхняя оценка обнаружения мёртвого backend: один интервал + ещё одна неудача + timeout проверки, около 1.8 с, плюс время самого `docker stop`
|
||||
- DNS Docker `127.0.0.11`, `server-template` на 8 слотов, `hold valid 1s`
|
||||
- POST буферизуется и при обрыве соединения повторяется на другой живой backend. Это безопасно, потому что ключ идемпотентности общий. Наблюдение: в официальном failover из ~90–95 записей сорвалась одна
|
||||
|
||||
`depends_on` и healthcheck контейнера только выстраивают старт. Они не выбирают живый backend на каждый запрос и не убирают умерший процесс из публичного адреса. Это делает HAProxy.
|
||||
|
||||
При `SIGTERM` uvicorn перестаёт принимать соединения (`timeout_graceful_shutdown=5`, в compose `init: true`, чтобы сигнал дошёл до процесса). `docker stop` в hook ждёт до 5 с. Оба официальных отказа закончились кодом 143, это SIGTERM. Политика `restart: unless-stopped`: явная остановка не поднимает реплику обратно.
|
||||
|
||||
Лимиты обычного стенда: API 0.50 CPU и 256 МиБ на реплику, Postgres 1.00 CPU и 512 МиБ, Redis 0.25 CPU и 128 МиБ, HAProxy 0.25 CPU и 128 МиБ. `container_name` нет, сервис `api` масштабируется `--scale`. Пул psycopg по умолчанию 10 на реплику, `statement_timeout` 5 с. Postgres: `fsync=on`, `synchronous_commit=on`, `full_page_writes=on`, `max_connections=80`.
|
||||
|
||||
Соответствие `.env`: `APP_PORT` — порт HAProxy на localhost, внутри API всегда 8080. `SESSION_TTL_SECONDS` — абсолютный срок сессии. `SESSION_STORE=redis`, другое значение процесс не принимает. `IDEMPOTENCY_TTL_SECONDS` — срок ключа. `POOL_MAX` — размер пула. `API_REPLICAS` — подсказка для `--scale`, в compose ещё записано `deploy.replicas: 2`. Секреты читаются из файлов, не из переменных с паролем.
|
||||
|
||||
Отказ процесса и отказ узла — разные вещи. `stop-one.sh` убивает один контейнер API. Второй API, HAProxy, Postgres и Redis остаются на том же хосте. Потеря хоста уносит все эти процессы сразу. Этот стенд такое не переживает, и я это не заявляю.
|
||||
|
||||
Если бы сессии жили в памяти процесса, второй API отвечал бы 401 на тот же токен. Sticky session спрятала бы это, пока жива «своя» реплика, и сломалась бы ровно в момент её остановки. Поэтому сессия в Redis, а балансировка без прилипания.
|
||||
|
||||
Повторять после timeout можно `POST` сообщения с тем же `Idempotency-Key` и тем же телом: либо вернётся исходное сообщение, либо, если транзакция откатилась, создастся одно. Другое тело с тем же ключом — 409, не вторая запись. Регистрация, логин и создание чата таким ключом не защищены: повтор может создать ещё один объект. Их я автоматически не повторяю.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
Стенд измерений: Docker Engine 26.1.4, Intel Core i5-10300H, 8 логических CPU, 17008717824 байт RAM. Дата прогонов 2026-11-06. В `docker stats` 100% — это одно ядро: лимит 0.35 CPU виден как потолок около 35%.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Offline check | `python -X utf8 scripts/check_contract.py` | `PASS: offline skeleton structure` | вывод команды |
|
||||
| Публичный smoke | `python -X utf8 tests/smoke.py --base-url http://127.0.0.1:8080` | `PASS: lab3 public API scenario` | evidence/smoke.txt |
|
||||
| Две реплики, одна сессия, разные `X-Instance-Id` | `student-tests/run.py`, 30 GET `/users/me` | `instances 2` | evidence/student_checks.txt |
|
||||
| API без наружных портов, CPU/RAM лимиты | тот же прогон, `docker inspect` | `PortBindings` пустой, `NanoCpus>0`, `Memory>0`; после трека снова 0.50 CPU и 256 МиБ, портов нет | evidence/student_checks.txt |
|
||||
| Общий Redis, не локальная память | failover без повторного логина | старый токен пишет через оставшуюся реплику | evidence/failover.txt |
|
||||
| Идемпотентность: то же тело, другой JSON-порядок и `attachment_ids: []`, другой регистр UUID в пути | `run.py` | второй ответ равен первому | evidence/student_checks.txt |
|
||||
| Другое тело — 409, без второй строки | `run.py` | 409, в таблице одно сообщение с этим id | evidence/student_checks.txt |
|
||||
| 8 параллельных POST с одним ключом | `run.py` | `8x201, 1 row` | evidence/student_checks.txt |
|
||||
| Тот же ключ у другого пользователя | отдельная проверка двух участников одного чата | два разных id сообщений | вывод команды, в отчёт не клала токены |
|
||||
| Ключ старше 24 ч можно занять снова | `UPDATE created_at` на −25 ч, тот же ключ и текст | новый id | evidence/student_checks.txt |
|
||||
| Нет ключа, ключ с пробелом, пробельный текст | `run.py` | три раза 400 | код `run.py`, прогон дошёл до PASS |
|
||||
| Cursor другого чата | отдельная проверка | 400 `invalid_request` | вместе с проверкой двух пользователей |
|
||||
| Один UUID участника в двух регистрах | `run.py` | 400, число чатов не выросло | прогон PASS |
|
||||
| Миграции один раз и не из реплик | лог `migrate`, `schema_migrations` | сначала `applied`, повторно `already applied`; версии `001_init`, `002_idempotency` | evidence/persistence.txt, evidence/student_checks.txt |
|
||||
| Persistence: API и оба хранилища, volume цел, старый токен | `tests/resilience.py --mode persistence` | PASS; StartedAt сменился у postgres, redis и api, у lb нет | evidence/persistence.txt |
|
||||
| Официальный failover, две разные реплики | два прогона `tests/resilience.py --mode failover` | 95 и 91 успешных записей, по 1 ошибке, восстановление 1.99 с и 1.371 с, оба PASS, остановленный контейнер `Exited (143)` | evidence/failover.txt |
|
||||
| Каждая реплика по очереди, RPS и ошибки | `student-tests/run_grade4.py` | первая: 498/499 ok, 33.2 RPS; вторая: 623/624 ok, 41.6 RPS; обе реально stopped | evidence/grade4.txt |
|
||||
| Rolling под нагрузкой | тот же скрипт, `docker restart` по одной | 1189/1190 ok, 42.5 RPS, `restarted: 2`, после этого снова 2 instance id | evidence/grade4.txt |
|
||||
| LB снимает мёртвый backend | официальный тест: после возврата hook остановленного id нет в последних ответах | период проверки 500 мс, fall 2 | evidence/failover.txt, infra/haproxy.cfg |
|
||||
| Публичная нагрузка | `tests/load.py --duration 20 --concurrency 8` | 326 успехов, 0 ошибок, 14.787 RPS, p50 312 мс, p95 1422 мс, p99 1656 мс | evidence/load.json |
|
||||
| Трек 1 | серии ниже | см. следующий раздел | evidence/track1_* |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
`docker compose start api` заодно снова стартует `migrate`, потому что это зависимость. На данных это no-op: в логе `already applied`.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Гипотеза трека: при фиксированном суммарном CPU/RAM API рост числа реплик перестаёт поднимать RPS, когда упираемся не в число процессов, а в общий бюджет CPU либо в единственный Postgres. Отдельно проверяла, маленький ли пул соединений сам режет успехи.
|
||||
|
||||
Методика одна для всех точек, генератор `student-tests/run_track1.py`: closed-loop POST с новым ключом на каждый запрос, новый чат на повтор, прогрев 4 с выбрасывается, измерение 12 с, два повтора. Ошибки не входят в latency. Это не открытый поток и не пик стенда: клиент ждёт ответ, прежде чем послать следующий. `docker stats` снимала раз в 2 с только в окне измерения.
|
||||
|
||||
Серия A. Суммарно 1.0 CPU и 1024 МиБ на все API, Postgres 1.0 CPU, пул 10, concurrency 8.
|
||||
|
||||
| Реплики | CPU на реплику | Средний успешный RPS | p50, мс | CPU API, % | CPU Postgres, % |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 1 | 1.00 | 23.1 | 328–344 | 104 | 16–18 |
|
||||
| 2 | 0.50 | 17.0 | 219 | 39–41 | 18–19 |
|
||||
| 4 | 0.25 | 23.7 | 94–110 | 18–22 | 16–26 |
|
||||
|
||||
Ошибок не было. Одна реплика уже сидит на своём лимите (около 100% = одно ядро). Postgres при этом занят примерно на пятую часть ядра. Четыре реплики дают тот же порядок RPS, что и одна, медиана лучше, хвост p95 остаётся 1.2–1.5 с. Две реплики в этом бюджете оказались медленнее обеих крайних точек. Рост числа процессов при том же суммарном CPU пропускную способность не поднимает: делить уже занятое ядро неоткуда, а база ещё свободна.
|
||||
|
||||
Серия B. Две реплики по 0.50 CPU, concurrency 8, лимит Postgres 0.30 / 0.60 / 1.20. Средний RPS: 20.9, 18.0, 22.3. CPU Postgres 13–21%, то есть даже лимит 0.30 не выбран. Колена нет. В этом профиле база не насыщена, и я не утверждаю, что добавка CPU Postgres здесь что-то ускорила.
|
||||
|
||||
Серия C. Те же две реплики по 0.50 CPU, concurrency 16.
|
||||
|
||||
| POOL_MAX | Повторы, RPS | Среднее | p95, мс | Ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 2 | 48.0, 36.7 | 42.4 | 922–1312 | 0 |
|
||||
| 10 | 20.4, 17.7 | 19.0 | 1718–2312 | 0 |
|
||||
|
||||
Диапазоны не пересекаются. Это подтверждённое улучшение для независимых вставок: пул 2 при concurrency 16 дал примерно вдвое больше успешных RPS, чем пул 10, на тех же CPU. Объяснение, которое сходится с цифрами: реплика и так упёрта в 0.50 CPU (в обоих вариантах stats около 45% на контейнер). Десять одновременных соединений только увеличивают очередь и хвост. Два соединения держат работу короче.
|
||||
|
||||
Пул 2 я не сделала значением по умолчанию. Восемь параллельных запросов с одним ключом ждут advisory lock, каждый держит соединение. При пуле 2 часть из них получит 503, хотя сообщение по-прежнему будет одно. Для контракта оставлен `POOL_MAX=10`. Улучшение измерено как настройка под этот профиль, не как новая константа стенда.
|
||||
|
||||
Серия D, `run_track1_db.py`. API больше не режу: 1.0 CPU на реплику, concurrency 16, пул 10.
|
||||
|
||||
| Точка | Средний RPS | CPU Postgres, % |
|
||||
| --- | --- | --- |
|
||||
| 2 API, Postgres 0.35 | 62.5 | 22–25 |
|
||||
| 4 API, Postgres 0.35 | 48.8 | 35–38 |
|
||||
| 2 API, Postgres 1.50 | 59.3 | 26–32 |
|
||||
|
||||
На двух репликах лимит 0.35 не выбран, и подъём до 1.50 RPS не увеличил (62.5 и 59.3 — один разброс). На четырёх репликах Postgres встал в свой потолок около 35–38%, а успешный RPS упал. Здесь saturation point — CPU единственного Postgres: дополнительные API его добивают и сами становятся лишними. Отдельный прогон «4 API и Postgres 1.50» я не делала, поэтому не пишу, что снятие лимита базы вернуло бы RPS. Это следующая проверка, не результат.
|
||||
|
||||
Графики средних: `evidence/track1_replicas.svg`, `evidence/track1_postgres.svg`, `evidence/track1_pool.svg`, `evidence/track1_db.svg`. Сырые повторы: `evidence/track1_runs.csv`, `evidence/track1_runs.json`, `evidence/track1_db.json`.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| `scripts/restart.sh` | старый токен и сообщение на месте, volume цел, базы реально перезапущены | persistence PASS; StartedAt обновлён у postgres, redis и api, lb остался прежним | данные целы, повтор миграции ничего не дописал |
|
||||
| `scripts/stop-one.sh`, официальный тест, дважды | через ≤10 с снова можно писать, остановленной реплики в последних ответах нет, дублей нет | 1.99 с и 1.371 с, по одной ошибке, PASS, контейнер `Exited (143)` | подтверждённые сообщения на месте |
|
||||
| Остановка каждой реплики под записью | короткая ошибка, потом RPS с оставшейся | 1 ошибка из 499 и 1 из 624 | обе реплики после `docker start` снова видны |
|
||||
| Поочерёдный `docker restart` под записью | сервис не встаёт целиком | 1 ошибка из 1190, 42.5 RPS, оба контейнера сменили старт | дубли не считала: у нагрузки уникальные ключи |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Выдерживается: смерть одного контейнера API, рестарт API вместе с Postgres и Redis при живых volume, общая сессия, конкурентный одинаковый ключ, поочерёдная замена реплик. Не выдерживается: смерть хоста, смерть HAProxy, смерть Postgres или Redis. Один балансировщик и одна база — SPOF. Несколько API-процессов этого не лечат.
|
||||
|
||||
Подтверждено измерением: при фиксированном 1.0 CPU на все API число реплик 1/2/4 не поднимает RPS выше одиночного процесса, потому что этот процесс уже занимает ядро, а Postgres свободен. Когда API получают по целому ядру, четыре реплики упирают Postgres в лимит 0.35 CPU и RPS падает. На concurrency 16 уменьшение пула с 10 до 2 подняло RPS с 19.0 до 42.4.
|
||||
|
||||
Не подтверждено: что в слабом профиле (две реплики по 0.50 CPU, concurrency 8) Postgres или его лимит вообще участвуют. Серия 0.30/0.60/1.20 лежит в шуме. Не подтверждено и то, что пул 2 лучше для пачки одинаковых ключей: там он как раз тесный.
|
||||
|
||||
Учебные упрощения: Redis без пароля и только во внутренней сети; `X-Instance-Id` равен id контейнера; HAProxy может повторить POST при обрыве; миграция аддитивная, две версии API одновременно я не гоняла; closed-loop занижает хвост и не является пиковой мощностью.
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
name: mtusi-lab3
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.10-bookworm
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
command:
|
||||
- postgres
|
||||
- -c
|
||||
- fsync=on
|
||||
- -c
|
||||
- synchronous_commit=on
|
||||
- -c
|
||||
- full_page_writes=on
|
||||
- -c
|
||||
- max_connections=80
|
||||
- -c
|
||||
- shared_buffers=64MB
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
secrets:
|
||||
- postgres_password
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 10s
|
||||
cpus: "1.00"
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- lab
|
||||
|
||||
redis:
|
||||
image: redis:7.4.2-bookworm
|
||||
command:
|
||||
- redis-server
|
||||
- --appendonly
|
||||
- "yes"
|
||||
- --appendfsync
|
||||
- everysec
|
||||
- --dir
|
||||
- /data
|
||||
- --save
|
||||
- "60"
|
||||
- "1"
|
||||
- --bind
|
||||
- 0.0.0.0
|
||||
- --protected-mode
|
||||
- "no"
|
||||
volumes:
|
||||
- redis-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 5s
|
||||
cpus: "0.25"
|
||||
mem_limit: 128m
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- lab
|
||||
|
||||
migrate:
|
||||
build: .
|
||||
image: mtusi-lab3-api:local
|
||||
command: ["python", "/app/src/migrate.py"]
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
secrets:
|
||||
- database_url
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
disable: true
|
||||
cpus: "0.50"
|
||||
mem_limit: 256m
|
||||
restart: "no"
|
||||
networks:
|
||||
- lab
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: mtusi-lab3-api:local
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
SESSION_STORE: redis
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
POOL_MAX: ${POOL_MAX:-10}
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
secrets:
|
||||
- database_url
|
||||
- cache_url
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 8
|
||||
start_period: 25s
|
||||
init: true
|
||||
stop_grace_period: 10s
|
||||
cpus: "0.50"
|
||||
mem_limit: 256m
|
||||
deploy:
|
||||
replicas: 2
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- lab
|
||||
|
||||
lb:
|
||||
image: haproxy:2.8.14
|
||||
volumes:
|
||||
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
ports:
|
||||
- "127.0.0.1:${APP_PORT:-8080}:8080"
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
cpus: "0.25"
|
||||
mem_limit: 128m
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- lab
|
||||
|
||||
networks:
|
||||
lab:
|
||||
name: mtusi-lab3-net
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
redis-data:
|
||||
|
||||
secrets:
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
cache_url:
|
||||
file: ./secrets/cache_url
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
@@ -0,0 +1,17 @@
|
||||
Официальный tests/resilience.py --mode failover, hook scripts/stop-one.sh.
|
||||
|
||||
Первый прогон, реплика api-2:
|
||||
{"observed_instances_before": 2, "successful_writes": 95, "failed_attempts": 1, "first_recovery_seconds": 1.99}
|
||||
PASS
|
||||
После hook: mtusi-lab3-api-2 Exited (143). 143 = SIGTERM, не SIGKILL.
|
||||
Восстановление: docker compose --env-file .env start api
|
||||
|
||||
Второй прогон, реплика api-5 (после экспериментов трека контейнеры уже другие):
|
||||
{"observed_instances_before": 2, "successful_writes": 91, "failed_attempts": 1, "first_recovery_seconds": 1.371}
|
||||
PASS
|
||||
После hook: mtusi-lab3-api-5 Exited (143), api-4 остался healthy.
|
||||
|
||||
Поочерёдно обе реплики ещё раз останавливал student-tests/run_grade4.py.
|
||||
Там контейнеры d7ab2fdafb51 и 8050bd440097: оба stopped_still_running=false, после start снова видны 2 instance id.
|
||||
Поле served_by_stopped_after=true в том файле — запросы, стартовавшие пока docker stop ещё ждал завершения процесса.
|
||||
Официальный тест смотрит ответы только после возврата hook: остановленного id в последних ответах нет.
|
||||
@@ -0,0 +1,5 @@
|
||||
rolling {"requests": 1190, "ok": 1189, "errors": 1, "error_ratio": 0.0008, "successful_rps": 42.536, "instances_after_mark": ["8050bd440097", "d7ab2fdafb51"], "restarted": 2}
|
||||
failover {"requests": 499, "ok": 498, "errors": 1, "error_ratio": 0.002, "successful_rps": 33.235, "instances_after_mark": ["8050bd440097", "d7ab2fdafb51"], "stopped": "d7ab2fdafb51", "stopped_still_running": false, "served_by_stopped_after": true}
|
||||
restored instances 2
|
||||
failover {"requests": 624, "ok": 623, "errors": 1, "error_ratio": 0.0016, "successful_rps": 41.619, "instances_after_mark": ["8050bd440097", "d7ab2fdafb51"], "stopped": "8050bd440097", "stopped_still_running": false, "served_by_stopped_after": true}
|
||||
restored instances 2
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 3,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 20.0,
|
||||
"elapsed_seconds": 22.047,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 326,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 14.787,
|
||||
"successful_latency_ms": {
|
||||
"p50": 312.0,
|
||||
"p95": 1422.0,
|
||||
"p99": 1656.0
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
wsl --cd <repo> python3 tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url http://127.0.0.1:8080
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
StartedAt сразу после hook (UTC):
|
||||
lb 2026-11-06T12:17:26Z не входил в restart.sh, старт стенда сохранился
|
||||
postgres 2026-11-06T12:20:22Z restart.sh перезапустил
|
||||
redis 2026-11-06T12:20:22Z restart.sh перезапустил
|
||||
api-1 2026-11-06T12:20:27Z restart.sh перезапустил
|
||||
|
||||
Volume не удалялся. Повторный запуск migrate после этого написал
|
||||
"001_init already applied" и "002_idempotency already applied".
|
||||
@@ -0,0 +1,2 @@
|
||||
python -X utf8 tests/smoke.py --base-url http://127.0.0.1:8080
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,6 @@
|
||||
instances 2
|
||||
parallel same key: 8x201, 1 row
|
||||
expired key created a new message
|
||||
migrations 001_init,002_idempotency
|
||||
api replicas 2 have cpu/memory limits and no published ports
|
||||
PASS student checks
|
||||
@@ -0,0 +1,168 @@
|
||||
[
|
||||
{
|
||||
"name": "api2-pg0.35",
|
||||
"repeat": 1,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 1.0,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 0.35,
|
||||
"pool_max": 10,
|
||||
"concurrency": 16,
|
||||
"api_cpu_percent_avg": 74.5,
|
||||
"postgres_cpu_percent_avg": 21.97,
|
||||
"elapsed_seconds": 12.282,
|
||||
"ok": 864,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 70.347,
|
||||
"p50_ms": 188.0,
|
||||
"p95_ms": 625.0,
|
||||
"instances": {
|
||||
"bb43af69d38d": 432,
|
||||
"bec8720c1884": 432
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 864
|
||||
},
|
||||
"warmup_rps": 65.939
|
||||
},
|
||||
{
|
||||
"name": "api2-pg0.35",
|
||||
"repeat": 2,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 1.0,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 0.35,
|
||||
"pool_max": 10,
|
||||
"concurrency": 16,
|
||||
"api_cpu_percent_avg": 91.39,
|
||||
"postgres_cpu_percent_avg": 24.72,
|
||||
"elapsed_seconds": 12.297,
|
||||
"ok": 672,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 54.647,
|
||||
"p50_ms": 188.0,
|
||||
"p95_ms": 984.0,
|
||||
"instances": {
|
||||
"bec8720c1884": 336,
|
||||
"bb43af69d38d": 336
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 672
|
||||
},
|
||||
"warmup_rps": 61.102
|
||||
},
|
||||
{
|
||||
"name": "api4-pg0.35",
|
||||
"repeat": 1,
|
||||
"api_replicas": 4,
|
||||
"api_cpus_each": 1.0,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 0.35,
|
||||
"pool_max": 10,
|
||||
"concurrency": 16,
|
||||
"api_cpu_percent_avg": 46.45,
|
||||
"postgres_cpu_percent_avg": 35.11,
|
||||
"elapsed_seconds": 12.328,
|
||||
"ok": 490,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 39.747,
|
||||
"p50_ms": 344.0,
|
||||
"p95_ms": 766.0,
|
||||
"instances": {
|
||||
"53ff00e3f61a": 123,
|
||||
"3632c2791ab8": 122,
|
||||
"3c753e9eb000": 123,
|
||||
"3f51f2dd36c3": 122
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 490
|
||||
},
|
||||
"warmup_rps": 42.19
|
||||
},
|
||||
{
|
||||
"name": "api4-pg0.35",
|
||||
"repeat": 2,
|
||||
"api_replicas": 4,
|
||||
"api_cpus_each": 1.0,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 0.35,
|
||||
"pool_max": 10,
|
||||
"concurrency": 16,
|
||||
"api_cpu_percent_avg": 60.29,
|
||||
"postgres_cpu_percent_avg": 37.55,
|
||||
"elapsed_seconds": 12.313,
|
||||
"ok": 713,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 57.906,
|
||||
"p50_ms": 235.0,
|
||||
"p95_ms": 547.0,
|
||||
"instances": {
|
||||
"3632c2791ab8": 179,
|
||||
"3c753e9eb000": 178,
|
||||
"53ff00e3f61a": 178,
|
||||
"3f51f2dd36c3": 178
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 713
|
||||
},
|
||||
"warmup_rps": 65.323
|
||||
},
|
||||
{
|
||||
"name": "api2-pg1.50",
|
||||
"repeat": 1,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 1.0,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 1.5,
|
||||
"pool_max": 10,
|
||||
"concurrency": 16,
|
||||
"api_cpu_percent_avg": 81.52,
|
||||
"postgres_cpu_percent_avg": 31.94,
|
||||
"elapsed_seconds": 12.438,
|
||||
"ok": 769,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 61.827,
|
||||
"p50_ms": 203.0,
|
||||
"p95_ms": 765.0,
|
||||
"instances": {
|
||||
"3e9fcfcec734": 384,
|
||||
"d110678c8117": 385
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 769
|
||||
},
|
||||
"warmup_rps": 42.502
|
||||
},
|
||||
{
|
||||
"name": "api2-pg1.50",
|
||||
"repeat": 2,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 1.0,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 1.5,
|
||||
"pool_max": 10,
|
||||
"concurrency": 16,
|
||||
"api_cpu_percent_avg": 78.25,
|
||||
"postgres_cpu_percent_avg": 26.06,
|
||||
"elapsed_seconds": 12.437,
|
||||
"ok": 705,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 56.686,
|
||||
"p50_ms": 234.0,
|
||||
"p95_ms": 891.0,
|
||||
"instances": {
|
||||
"3e9fcfcec734": 353,
|
||||
"d110678c8117": 352
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 705
|
||||
},
|
||||
"warmup_rps": 77.545
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="420">
|
||||
<rect width="100%" height="100%" fill="white"/>
|
||||
<text x="380" y="22" text-anchor="middle" font-size="16">Много CPU у API, разный лимит Postgres</text>
|
||||
<line x1="70" y1="30" x2="70" y2="370" stroke="#222"/>
|
||||
<line x1="70" y1="370" x2="740" y2="370" stroke="#222"/>
|
||||
<polyline fill="none" stroke="#1f4e79" stroke-width="2" points="70.0,74.3 400.0,139.2 730.0,89.5"/>
|
||||
<circle cx="70.0" cy="74.3" r="4" fill="#1f4e79"/><circle cx="400.0" cy="139.2" r="4" fill="#1f4e79"/><circle cx="730.0" cy="89.5" r="4" fill="#1f4e79"/>
|
||||
<text x="70.0" y="402" text-anchor="middle" font-size="13">2x / 0.35</text>
|
||||
<text x="70.0" y="66.3" text-anchor="middle" font-size="12">62.5</text>
|
||||
<text x="400.0" y="402" text-anchor="middle" font-size="13">4x / 0.35</text>
|
||||
<text x="400.0" y="131.2" text-anchor="middle" font-size="12">48.8</text>
|
||||
<text x="730.0" y="402" text-anchor="middle" font-size="13">2x / 1.50</text>
|
||||
<text x="730.0" y="81.5" text-anchor="middle" font-size="12">59.3</text>
|
||||
<text x="380" y="418" text-anchor="middle" font-size="13">реплики API / лимит CPU Postgres</text>
|
||||
<text x="18" y="220" font-size="13" transform="rotate(-90 18 220)">успешные RPS</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,14 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="420">
|
||||
<rect width="100%" height="100%" fill="white"/>
|
||||
<text x="380" y="22" text-anchor="middle" font-size="16">Размер пула соединений при concurrency 16</text>
|
||||
<line x1="70" y1="30" x2="70" y2="370" stroke="#222"/>
|
||||
<line x1="70" y1="370" x2="740" y2="370" stroke="#222"/>
|
||||
<polyline fill="none" stroke="#1f4e79" stroke-width="2" points="70.0,74.3 730.0,237.3"/>
|
||||
<circle cx="70.0" cy="74.3" r="4" fill="#1f4e79"/><circle cx="730.0" cy="237.3" r="4" fill="#1f4e79"/>
|
||||
<text x="70.0" y="402" text-anchor="middle" font-size="13">2</text>
|
||||
<text x="70.0" y="66.3" text-anchor="middle" font-size="12">42.4</text>
|
||||
<text x="730.0" y="402" text-anchor="middle" font-size="13">10</text>
|
||||
<text x="730.0" y="229.3" text-anchor="middle" font-size="12">19.0</text>
|
||||
<text x="380" y="418" text-anchor="middle" font-size="13">POOL_MAX на реплику</text>
|
||||
<text x="18" y="220" font-size="13" transform="rotate(-90 18 220)">успешные RPS</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="420">
|
||||
<rect width="100%" height="100%" fill="white"/>
|
||||
<text x="380" y="22" text-anchor="middle" font-size="16">Рост CPU Postgres при 2 API</text>
|
||||
<line x1="70" y1="30" x2="70" y2="370" stroke="#222"/>
|
||||
<line x1="70" y1="370" x2="740" y2="370" stroke="#222"/>
|
||||
<polyline fill="none" stroke="#1f4e79" stroke-width="2" points="70.0,92.5 400.0,131.2 730.0,74.3"/>
|
||||
<circle cx="70.0" cy="92.5" r="4" fill="#1f4e79"/><circle cx="400.0" cy="131.2" r="4" fill="#1f4e79"/><circle cx="730.0" cy="74.3" r="4" fill="#1f4e79"/>
|
||||
<text x="70.0" y="402" text-anchor="middle" font-size="13">0.30</text>
|
||||
<text x="70.0" y="84.5" text-anchor="middle" font-size="12">20.9</text>
|
||||
<text x="400.0" y="402" text-anchor="middle" font-size="13">0.60</text>
|
||||
<text x="400.0" y="123.2" text-anchor="middle" font-size="12">18.0</text>
|
||||
<text x="730.0" y="402" text-anchor="middle" font-size="13">1.20</text>
|
||||
<text x="730.0" y="66.3" text-anchor="middle" font-size="12">22.3</text>
|
||||
<text x="380" y="418" text-anchor="middle" font-size="13">лимит CPU Postgres</text>
|
||||
<text x="18" y="220" font-size="13" transform="rotate(-90 18 220)">успешные RPS</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="420">
|
||||
<rect width="100%" height="100%" fill="white"/>
|
||||
<text x="380" y="22" text-anchor="middle" font-size="16">Фиксированный бюджет API: 1 / 2 / 4 реплики</text>
|
||||
<line x1="70" y1="30" x2="70" y2="370" stroke="#222"/>
|
||||
<line x1="70" y1="370" x2="740" y2="370" stroke="#222"/>
|
||||
<polyline fill="none" stroke="#1f4e79" stroke-width="2" points="70.0,81.4 400.0,158.2 730.0,74.3"/>
|
||||
<circle cx="70.0" cy="81.4" r="4" fill="#1f4e79"/><circle cx="400.0" cy="158.2" r="4" fill="#1f4e79"/><circle cx="730.0" cy="74.3" r="4" fill="#1f4e79"/>
|
||||
<text x="70.0" y="402" text-anchor="middle" font-size="13">1</text>
|
||||
<text x="70.0" y="73.4" text-anchor="middle" font-size="12">23.1</text>
|
||||
<text x="400.0" y="402" text-anchor="middle" font-size="13">2</text>
|
||||
<text x="400.0" y="150.2" text-anchor="middle" font-size="12">17.0</text>
|
||||
<text x="730.0" y="402" text-anchor="middle" font-size="13">4</text>
|
||||
<text x="730.0" y="66.3" text-anchor="middle" font-size="12">23.7</text>
|
||||
<text x="380" y="418" text-anchor="middle" font-size="13">число реплик при суммарно 1.0 CPU и 1024 MiB</text>
|
||||
<text x="18" y="220" font-size="13" transform="rotate(-90 18 220)">успешные RPS</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,17 @@
|
||||
name,repeat,api_replicas,api_cpus_each,postgres_cpus,pool_max,concurrency,successful_rps,error_ratio,p50_ms,p95_ms,api_cpu_percent_avg,postgres_cpu_percent_avg
|
||||
fixed-1,1,1,1.0,1.0,10,8,23.947,0.0,328.0,672.0,103.56,15.87
|
||||
fixed-1,2,1,1.0,1.0,10,8,22.317,0.0,344.0,750.0,104.36,18.13
|
||||
fixed-2,1,2,0.5,1.0,10,8,17.402,0.0,219.0,1250.0,40.53,19.16
|
||||
fixed-2,2,2,0.5,1.0,10,8,16.56,0.0,219.0,1484.0,38.62,17.9
|
||||
fixed-4,1,4,0.25,1.0,10,8,25.164,0.0,94.0,1188.0,18.03,15.9
|
||||
fixed-4,2,4,0.25,1.0,10,8,22.235,0.0,110.0,1484.0,22.12,25.53
|
||||
pg-0.30,1,2,0.5,0.3,10,8,24.294,0.0,219.0,1079.0,42.1,17.8
|
||||
pg-0.30,2,2,0.5,0.3,10,8,17.483,0.0,281.0,1219.0,47.01,18.2
|
||||
pg-0.60,1,2,0.5,0.6,10,8,17.625,0.0,312.0,1422.0,39.66,17.52
|
||||
pg-0.60,2,2,0.5,0.6,10,8,18.331,0.0,234.0,1203.0,44.6,13.38
|
||||
pg-1.20,1,2,0.5,1.2,10,8,22.485,0.0,297.0,907.0,41.64,21.02
|
||||
pg-1.20,2,2,0.5,1.2,10,8,22.032,0.0,219.0,1172.0,47.22,14.82
|
||||
pool-2,1,2,0.5,1.0,2,16,48.0,0.0,281.0,922.0,44.11,20.69
|
||||
pool-2,2,2,0.5,1.0,2,16,36.709,0.0,453.0,1312.0,47.04,14.85
|
||||
pool-10,1,2,0.5,1.0,10,16,20.353,0.0,813.0,1718.0,46.07,24.71
|
||||
pool-10,2,2,0.5,1.0,10,16,17.657,0.0,563.0,2312.0,47.39,19.96
|
||||
|
@@ -0,0 +1,436 @@
|
||||
[
|
||||
{
|
||||
"name": "fixed-1",
|
||||
"repeat": 1,
|
||||
"api_replicas": 1,
|
||||
"api_cpus_each": 1.0,
|
||||
"api_memory_each": "1024m",
|
||||
"postgres_cpus": 1.0,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 103.56,
|
||||
"postgres_cpu_percent_avg": 15.87,
|
||||
"elapsed_seconds": 12.11,
|
||||
"ok": 290,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 23.947,
|
||||
"p50_ms": 328.0,
|
||||
"p95_ms": 672.0,
|
||||
"instances": {
|
||||
"0e2853f732e2": 290
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 290
|
||||
},
|
||||
"warmup_rps": 18.253
|
||||
},
|
||||
{
|
||||
"name": "fixed-1",
|
||||
"repeat": 2,
|
||||
"api_replicas": 1,
|
||||
"api_cpus_each": 1.0,
|
||||
"api_memory_each": "1024m",
|
||||
"postgres_cpus": 1.0,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 104.36,
|
||||
"postgres_cpu_percent_avg": 18.13,
|
||||
"elapsed_seconds": 12.188,
|
||||
"ok": 272,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 22.317,
|
||||
"p50_ms": 344.0,
|
||||
"p95_ms": 750.0,
|
||||
"instances": {
|
||||
"0e2853f732e2": 272
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 272
|
||||
},
|
||||
"warmup_rps": 13.902
|
||||
},
|
||||
{
|
||||
"name": "fixed-2",
|
||||
"repeat": 1,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 1.0,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 40.53,
|
||||
"postgres_cpu_percent_avg": 19.16,
|
||||
"elapsed_seconds": 12.125,
|
||||
"ok": 211,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 17.402,
|
||||
"p50_ms": 219.0,
|
||||
"p95_ms": 1250.0,
|
||||
"instances": {
|
||||
"5bebd8ab4f56": 105,
|
||||
"f1a5ba335e1e": 106
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 211
|
||||
},
|
||||
"warmup_rps": 10.629
|
||||
},
|
||||
{
|
||||
"name": "fixed-2",
|
||||
"repeat": 2,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 1.0,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 38.62,
|
||||
"postgres_cpu_percent_avg": 17.9,
|
||||
"elapsed_seconds": 12.5,
|
||||
"ok": 207,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 16.56,
|
||||
"p50_ms": 219.0,
|
||||
"p95_ms": 1484.0,
|
||||
"instances": {
|
||||
"5bebd8ab4f56": 104,
|
||||
"f1a5ba335e1e": 103
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 207
|
||||
},
|
||||
"warmup_rps": 15.443
|
||||
},
|
||||
{
|
||||
"name": "fixed-4",
|
||||
"repeat": 1,
|
||||
"api_replicas": 4,
|
||||
"api_cpus_each": 0.25,
|
||||
"api_memory_each": "256m",
|
||||
"postgres_cpus": 1.0,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 18.03,
|
||||
"postgres_cpu_percent_avg": 15.9,
|
||||
"elapsed_seconds": 12.359,
|
||||
"ok": 311,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 25.164,
|
||||
"p50_ms": 94.0,
|
||||
"p95_ms": 1188.0,
|
||||
"instances": {
|
||||
"329be75d4a30": 78,
|
||||
"c7e4f318a8a5": 78,
|
||||
"06cc7d7ee0fd": 78,
|
||||
"f0f75a31fff3": 77
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 311
|
||||
},
|
||||
"warmup_rps": 21.009
|
||||
},
|
||||
{
|
||||
"name": "fixed-4",
|
||||
"repeat": 2,
|
||||
"api_replicas": 4,
|
||||
"api_cpus_each": 0.25,
|
||||
"api_memory_each": "256m",
|
||||
"postgres_cpus": 1.0,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 22.12,
|
||||
"postgres_cpu_percent_avg": 25.53,
|
||||
"elapsed_seconds": 12.188,
|
||||
"ok": 271,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 22.235,
|
||||
"p50_ms": 110.0,
|
||||
"p95_ms": 1484.0,
|
||||
"instances": {
|
||||
"329be75d4a30": 72,
|
||||
"c7e4f318a8a5": 72,
|
||||
"06cc7d7ee0fd": 72,
|
||||
"f0f75a31fff3": 55
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 271
|
||||
},
|
||||
"warmup_rps": 12.577
|
||||
},
|
||||
{
|
||||
"name": "pg-0.30",
|
||||
"repeat": 1,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 0.3,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 42.1,
|
||||
"postgres_cpu_percent_avg": 17.8,
|
||||
"elapsed_seconds": 12.719,
|
||||
"ok": 309,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 24.294,
|
||||
"p50_ms": 219.0,
|
||||
"p95_ms": 1079.0,
|
||||
"instances": {
|
||||
"a0c6b859a0ae": 154,
|
||||
"dfa5caeae453": 155
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 309
|
||||
},
|
||||
"warmup_rps": 14.556
|
||||
},
|
||||
{
|
||||
"name": "pg-0.30",
|
||||
"repeat": 2,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 0.3,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 47.01,
|
||||
"postgres_cpu_percent_avg": 18.2,
|
||||
"elapsed_seconds": 12.469,
|
||||
"ok": 218,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 17.483,
|
||||
"p50_ms": 281.0,
|
||||
"p95_ms": 1219.0,
|
||||
"instances": {
|
||||
"a0c6b859a0ae": 109,
|
||||
"dfa5caeae453": 109
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 218
|
||||
},
|
||||
"warmup_rps": 26.065
|
||||
},
|
||||
{
|
||||
"name": "pg-0.60",
|
||||
"repeat": 1,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 0.6,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 39.66,
|
||||
"postgres_cpu_percent_avg": 17.52,
|
||||
"elapsed_seconds": 12.312,
|
||||
"ok": 217,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 17.625,
|
||||
"p50_ms": 312.0,
|
||||
"p95_ms": 1422.0,
|
||||
"instances": {
|
||||
"29bc337601db": 109,
|
||||
"d815cccbd156": 108
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 217
|
||||
},
|
||||
"warmup_rps": 7.111
|
||||
},
|
||||
{
|
||||
"name": "pg-0.60",
|
||||
"repeat": 2,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 0.6,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 44.6,
|
||||
"postgres_cpu_percent_avg": 13.38,
|
||||
"elapsed_seconds": 12.765,
|
||||
"ok": 234,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 18.331,
|
||||
"p50_ms": 234.0,
|
||||
"p95_ms": 1203.0,
|
||||
"instances": {
|
||||
"29bc337601db": 117,
|
||||
"d815cccbd156": 117
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 234
|
||||
},
|
||||
"warmup_rps": 21.556
|
||||
},
|
||||
{
|
||||
"name": "pg-1.20",
|
||||
"repeat": 1,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 1.2,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 41.64,
|
||||
"postgres_cpu_percent_avg": 21.02,
|
||||
"elapsed_seconds": 12.453,
|
||||
"ok": 280,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 22.485,
|
||||
"p50_ms": 297.0,
|
||||
"p95_ms": 907.0,
|
||||
"instances": {
|
||||
"829d3ebf1797": 140,
|
||||
"ecf3a641c98e": 140
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 280
|
||||
},
|
||||
"warmup_rps": 21.091
|
||||
},
|
||||
{
|
||||
"name": "pg-1.20",
|
||||
"repeat": 2,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 1.2,
|
||||
"pool_max": 10,
|
||||
"concurrency": 8,
|
||||
"api_cpu_percent_avg": 47.22,
|
||||
"postgres_cpu_percent_avg": 14.82,
|
||||
"elapsed_seconds": 12.391,
|
||||
"ok": 273,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 22.032,
|
||||
"p50_ms": 219.0,
|
||||
"p95_ms": 1172.0,
|
||||
"instances": {
|
||||
"ecf3a641c98e": 136,
|
||||
"829d3ebf1797": 137
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 273
|
||||
},
|
||||
"warmup_rps": 38.061
|
||||
},
|
||||
{
|
||||
"name": "pool-2",
|
||||
"repeat": 1,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 1.0,
|
||||
"pool_max": 2,
|
||||
"concurrency": 16,
|
||||
"api_cpu_percent_avg": 44.11,
|
||||
"postgres_cpu_percent_avg": 20.69,
|
||||
"elapsed_seconds": 12.25,
|
||||
"ok": 588,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 48.0,
|
||||
"p50_ms": 281.0,
|
||||
"p95_ms": 922.0,
|
||||
"instances": {
|
||||
"2a050c6c1a81": 294,
|
||||
"406ae8ebc74d": 294
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 588
|
||||
},
|
||||
"warmup_rps": 28.513
|
||||
},
|
||||
{
|
||||
"name": "pool-2",
|
||||
"repeat": 2,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 1.0,
|
||||
"pool_max": 2,
|
||||
"concurrency": 16,
|
||||
"api_cpu_percent_avg": 47.04,
|
||||
"postgres_cpu_percent_avg": 14.85,
|
||||
"elapsed_seconds": 12.531,
|
||||
"ok": 460,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 36.709,
|
||||
"p50_ms": 453.0,
|
||||
"p95_ms": 1312.0,
|
||||
"instances": {
|
||||
"406ae8ebc74d": 230,
|
||||
"2a050c6c1a81": 230
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 460
|
||||
},
|
||||
"warmup_rps": 60.297
|
||||
},
|
||||
{
|
||||
"name": "pool-10",
|
||||
"repeat": 1,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 1.0,
|
||||
"pool_max": 10,
|
||||
"concurrency": 16,
|
||||
"api_cpu_percent_avg": 46.07,
|
||||
"postgres_cpu_percent_avg": 24.71,
|
||||
"elapsed_seconds": 12.578,
|
||||
"ok": 256,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 20.353,
|
||||
"p50_ms": 813.0,
|
||||
"p95_ms": 1718.0,
|
||||
"instances": {
|
||||
"194c290719fa": 128,
|
||||
"8d9b89e30678": 128
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 256
|
||||
},
|
||||
"warmup_rps": 16.798
|
||||
},
|
||||
{
|
||||
"name": "pool-10",
|
||||
"repeat": 2,
|
||||
"api_replicas": 2,
|
||||
"api_cpus_each": 0.5,
|
||||
"api_memory_each": "512m",
|
||||
"postgres_cpus": 1.0,
|
||||
"pool_max": 10,
|
||||
"concurrency": 16,
|
||||
"api_cpu_percent_avg": 47.39,
|
||||
"postgres_cpu_percent_avg": 19.96,
|
||||
"elapsed_seconds": 12.969,
|
||||
"ok": 229,
|
||||
"errors": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 17.657,
|
||||
"p50_ms": 563.0,
|
||||
"p95_ms": 2312.0,
|
||||
"instances": {
|
||||
"194c290719fa": 96,
|
||||
"8d9b89e30678": 133
|
||||
},
|
||||
"status_codes": {
|
||||
"201": 229
|
||||
},
|
||||
"warmup_rps": 21.478
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"method": "closed-loop POST messages, unique Idempotency-Key, warmup 4s discarded, measure 12s, 2 repeats, fresh chat per repeat",
|
||||
"fixed_total_api_cpu": 1.0,
|
||||
"fixed_total_api_memory": "1024m",
|
||||
"mean_successful_rps": {
|
||||
"fixed-1": 23.132,
|
||||
"fixed-2": 16.981,
|
||||
"fixed-4": 23.7,
|
||||
"pg-0.30": 20.889,
|
||||
"pg-0.60": 17.978,
|
||||
"pg-1.20": 22.258,
|
||||
"pool-2": 42.355,
|
||||
"pool-10": 19.005
|
||||
}
|
||||
}
|
||||
@@ -5,3 +5,5 @@
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
|
||||
В этой работе балансировщик — HAProxy, конфиг `infra/haproxy.cfg`. Топология сервисов — корневой `compose.yaml`. Миграции выполняет одноразовый сервис `migrate`, не реплики API.
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
global
|
||||
maxconn 256
|
||||
tune.bufsize 65536
|
||||
tune.maxrewrite 8192
|
||||
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 500ms
|
||||
timeout client 15s
|
||||
timeout server 8s
|
||||
timeout http-request 10s
|
||||
timeout http-keep-alive 2s
|
||||
timeout queue 2s
|
||||
timeout check 800ms
|
||||
option http-buffer-request
|
||||
option redispatch
|
||||
option dontlognull
|
||||
retries 2
|
||||
retry-on conn-failure empty-response 502 503 504
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 1s
|
||||
hold other 1s
|
||||
hold refused 1s
|
||||
hold nx 1s
|
||||
hold timeout 1s
|
||||
hold obsolete 1s
|
||||
accepted_payload_size 8192
|
||||
|
||||
frontend web
|
||||
bind *:8080
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
|
||||
http-check expect status 200
|
||||
server-template api 8 api:8080 check inter 500ms fall 2 rise 2 resolvers docker init-addr none resolve-prefer ipv4 on-marked-down shutdown-sessions
|
||||
@@ -0,0 +1,48 @@
|
||||
-- Пользователи, чаты, участники и сообщения.
|
||||
-- Создание чата в приложении идёт одной транзакцией: строка chats и строки chat_members.
|
||||
-- Индекс messages_history_idx совпадает с keyset-запросом истории:
|
||||
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
-- ORDER BY created_at, id
|
||||
-- LIMIT $4
|
||||
|
||||
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,
|
||||
CONSTRAINT users_username_unique UNIQUE (username),
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_nonblank CHECK (btrim(display_name) <> ''),
|
||||
CONSTRAINT users_display_name_len 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,
|
||||
CONSTRAINT chats_title_nonblank CHECK (btrim(title) <> ''),
|
||||
CONSTRAINT chats_title_len 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),
|
||||
ordinal smallint NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
CONSTRAINT chat_members_ordinal_nonneg CHECK (ordinal >= 0)
|
||||
);
|
||||
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
sender_id uuid NOT NULL REFERENCES users (id),
|
||||
body text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT messages_body_nonblank CHECK (btrim(body) <> ''),
|
||||
CONSTRAINT messages_body_len CHECK (char_length(body) BETWEEN 1 AND 4000)
|
||||
);
|
||||
|
||||
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1,19 @@
|
||||
-- Результат успешного POST сообщения.
|
||||
-- Область ключа: пользователь + метод + путь чата + Idempotency-Key.
|
||||
-- Строка пишется в той же транзакции, что и messages, поэтому 5xx
|
||||
-- не оставляет «занятый» ключ. Другое тело при живом ключе — отказ
|
||||
-- на уровне приложения (хеш не совпал), без второй строки messages.
|
||||
|
||||
CREATE TABLE idempotency_keys (
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
http_method text NOT NULL,
|
||||
request_path text NOT NULL,
|
||||
idem_key text NOT NULL,
|
||||
request_hash text NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages (id),
|
||||
created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (user_id, http_method, request_path, idem_key),
|
||||
CONSTRAINT idempotency_method_post CHECK (http_method = 'POST'),
|
||||
CONSTRAINT idempotency_key_format CHECK (idem_key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
CONSTRAINT idempotency_hash_len CHECK (char_length(request_hash) = 64)
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
fastapi==0.115.12
|
||||
uvicorn[standard]==0.34.2
|
||||
pydantic==2.11.4
|
||||
psycopg[binary]==3.2.6
|
||||
psycopg-pool==3.2.4
|
||||
redis==5.2.1
|
||||
argon2-cffi==23.1.0
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Создать локальные .env и secrets для стенда. Пароль в консоль не печатается."""
|
||||
import secrets
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRET_DIR = ROOT / "secrets"
|
||||
PASSWORD_FILE = SECRET_DIR / "postgres_password"
|
||||
DATABASE_FILE = SECRET_DIR / "database_url"
|
||||
CACHE_FILE = SECRET_DIR / "cache_url"
|
||||
ENV_FILE = ROOT / ".env"
|
||||
ENV_EXAMPLE = ROOT / ".env.example"
|
||||
|
||||
|
||||
def main():
|
||||
files = (PASSWORD_FILE, DATABASE_FILE, CACHE_FILE)
|
||||
if any(path.exists() for path in files) and not all(path.exists() for path in files):
|
||||
print("secrets/ заполнены не полностью, ничего не перезаписываю", file=sys.stderr)
|
||||
return 1
|
||||
SECRET_DIR.mkdir(exist_ok=True)
|
||||
if all(path.exists() for path in files):
|
||||
print("secrets already exist")
|
||||
else:
|
||||
password = secrets.token_hex(24)
|
||||
PASSWORD_FILE.write_text(password + "\n", encoding="utf-8")
|
||||
DATABASE_FILE.write_text(
|
||||
"postgresql://messenger:{}@postgres:5432/messenger\n".format(password),
|
||||
encoding="utf-8",
|
||||
)
|
||||
CACHE_FILE.write_text("redis://redis:6379/0\n", encoding="utf-8")
|
||||
print("secrets created")
|
||||
if ENV_FILE.exists():
|
||||
print(".env already exists")
|
||||
else:
|
||||
ENV_FILE.write_text(ENV_EXAMPLE.read_text(encoding="utf-8"), encoding="utf-8")
|
||||
print(".env created")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
# Рестарт API и обоих хранилищ. Volume не удаляем, миграции и данные заново не заливаем.
|
||||
# Балансировщик без своего состояния не трогаем: он продолжает слушать тот же порт.
|
||||
docker compose --env-file .env restart postgres redis
|
||||
docker compose --env-file .env up -d --wait --no-deps postgres redis
|
||||
docker compose --env-file .env restart api
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Поочерёдный рестарт API-реплик. Следующую не трогаем, пока текущая снова healthy.
|
||||
ids=$(docker ps -q \
|
||||
--filter label=com.docker.compose.project=mtusi-lab3 \
|
||||
--filter label=com.docker.compose.service=api)
|
||||
if [ -z "$ids" ]; then
|
||||
echo "no api replicas" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for id in $ids; do
|
||||
docker restart --time 5 "$id" >/dev/null
|
||||
i=0
|
||||
while [ "$i" -lt 40 ]; do
|
||||
status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$id")
|
||||
if [ "$status" = "healthy" ]; then
|
||||
break
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 1
|
||||
done
|
||||
if [ "$i" -ge 40 ]; then
|
||||
echo "replica did not become healthy" >&2
|
||||
exit 1
|
||||
fi
|
||||
# rise 2 у HAProxy: дать балансировщику вернуть реплику в ротацию.
|
||||
sleep 2
|
||||
done
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?}"
|
||||
|
||||
found=""
|
||||
for id in $(docker ps -q \
|
||||
--filter label=com.docker.compose.project=mtusi-lab3 \
|
||||
--filter label=com.docker.compose.service=api); do
|
||||
host=$(docker inspect -f '{{.Config.Hostname}}' "$id")
|
||||
short=$(printf %s "$id" | cut -c1-12)
|
||||
if [ "$host" = "$TARGET_INSTANCE_ID" ] || [ "$short" = "$TARGET_INSTANCE_ID" ]; then
|
||||
found=$id
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$found" ]; then
|
||||
echo "api replica not found" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# SIGTERM, затем процесс остаётся остановленным (restart: unless-stopped).
|
||||
docker stop --time 5 "$found" >/dev/null
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ждать GET /health/ready через балансировщик. Без токенов и тел ошибок в выводе."""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") + "/health/ready"
|
||||
|
||||
|
||||
def main():
|
||||
deadline = time.monotonic() + 90
|
||||
last = "not-started"
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
response = urllib.request.urlopen(URL, timeout=2)
|
||||
if response.status == 200 and response.headers.get("X-Instance-Id"):
|
||||
print("ready")
|
||||
return 0
|
||||
last = str(response.status)
|
||||
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
||||
last = type(exc).__name__
|
||||
time.sleep(1)
|
||||
print("not ready: " + last, file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,24 @@
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status, code, message, headers=None):
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
class DependencyDown(Exception):
|
||||
"""Postgres или Redis не ответили. Наружу это 503 без имени хранилища."""
|
||||
|
||||
|
||||
class IdempotencyConflict(Exception):
|
||||
"""Тот же Idempotency-Key уже зафиксирован с другим телом."""
|
||||
|
||||
|
||||
def error_body(code, message, request_id):
|
||||
return {
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": request_id,
|
||||
}
|
||||
}
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import anyio
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from pydantic import ValidationError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from errors import ApiError, DependencyDown, IdempotencyConflict, error_body
|
||||
from schemas import CreateChat, CreateMessage, CreateUser
|
||||
from store import Store, instance_id
|
||||
|
||||
LOGGER = logging.getLogger("messenger")
|
||||
store = Store()
|
||||
INSTANCE_ID = instance_id()
|
||||
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
MAX_JSON_BYTES = 65536
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app):
|
||||
await anyio.to_thread.run_sync(store.startup)
|
||||
yield
|
||||
store.shutting_down = True
|
||||
await anyio.to_thread.run_sync(store.shutdown)
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="mtusi-messenger",
|
||||
version="lab3",
|
||||
lifespan=lifespan,
|
||||
redirect_slashes=False,
|
||||
docs_url="/docs",
|
||||
redoc_url=None,
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
|
||||
def request_id_of(request: Request):
|
||||
rid = getattr(request.state, "request_id", None)
|
||||
if rid:
|
||||
return rid
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def stamp(request: Request, response):
|
||||
response.headers["X-Request-Id"] = request_id_of(request)
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
def json_ok(request: Request, payload, status_code=200):
|
||||
return stamp(request, JSONResponse(payload, status_code=status_code))
|
||||
|
||||
|
||||
def json_error(request: Request, status, code, message, extra_headers=None):
|
||||
headers = {"X-Request-Id": request_id_of(request), "X-Instance-Id": INSTANCE_ID}
|
||||
if extra_headers:
|
||||
headers.update(extra_headers)
|
||||
return JSONResponse(error_body(code, message, request_id_of(request)), status_code=status, headers=headers)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def wrap_request(request: Request, call_next):
|
||||
incoming = request.headers.get("X-Request-Id", "")
|
||||
if incoming and len(incoming) <= 200 and incoming.isprintable() and incoming.strip():
|
||||
request.state.request_id = incoming.strip()
|
||||
else:
|
||||
request.state.request_id = str(uuid.uuid4())
|
||||
if store.shutting_down and request.url.path != "/health/live":
|
||||
return json_error(request, 503, "unavailable", "Сервис временно недоступен")
|
||||
response = await call_next(request)
|
||||
return stamp(request, response)
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError):
|
||||
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def request_validation_handler(request: Request, _exc: RequestValidationError):
|
||||
return json_error(request, 400, "invalid_request", "Некорректный запрос")
|
||||
|
||||
|
||||
@app.exception_handler(ValidationError)
|
||||
async def pydantic_handler(request: Request, _exc: ValidationError):
|
||||
return json_error(request, 400, "invalid_request", "Некорректный запрос")
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
if exc.status_code == 404:
|
||||
return json_error(request, 404, "not_found", "Объект не найден")
|
||||
return json_error(request, exc.status_code if exc.status_code < 500 else 500, "invalid_request", "Некорректный запрос")
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unexpected_handler(request: Request, exc: Exception):
|
||||
if isinstance(exc, ApiError):
|
||||
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
|
||||
LOGGER.exception("unhandled")
|
||||
return json_error(request, 500, "internal_error", "Внутренняя ошибка")
|
||||
|
||||
|
||||
def unavailable():
|
||||
raise ApiError(503, "unavailable", "Сервис временно недоступен")
|
||||
|
||||
|
||||
def bearer_unauthorized():
|
||||
raise ApiError(401, "unauthorized", "Требуется авторизация", {"WWW-Authenticate": BEARER_CHALLENGE})
|
||||
|
||||
|
||||
def basic_unauthorized():
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": BASIC_CHALLENGE})
|
||||
|
||||
|
||||
def invalid():
|
||||
raise ApiError(400, "invalid_request", "Некорректный запрос")
|
||||
|
||||
|
||||
async def call_store(func, *args):
|
||||
try:
|
||||
return await anyio.to_thread.run_sync(func, *args)
|
||||
except DependencyDown:
|
||||
unavailable()
|
||||
except IdempotencyConflict:
|
||||
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
|
||||
|
||||
|
||||
def parse_basic(request: Request):
|
||||
header = request.headers.get("Authorization", "")
|
||||
if not header.lower().startswith("basic "):
|
||||
basic_unauthorized()
|
||||
raw = header.split(" ", 1)[1].strip()
|
||||
try:
|
||||
import base64
|
||||
|
||||
decoded = base64.b64decode(raw, validate=True).decode("utf-8")
|
||||
except (ValueError, UnicodeError):
|
||||
basic_unauthorized()
|
||||
if ":" not in decoded:
|
||||
basic_unauthorized()
|
||||
username, password = decoded.split(":", 1)
|
||||
return username, password
|
||||
|
||||
|
||||
def parse_bearer(request: Request):
|
||||
header = request.headers.get("Authorization", "")
|
||||
# Basic на бизнес-методе не открывает сессию. X-User-Id не смотрим.
|
||||
if not header.lower().startswith("bearer "):
|
||||
bearer_unauthorized()
|
||||
token = header.split(" ", 1)[1].strip()
|
||||
if len(token) < 32 or len(token) > 512 or any(ch.isspace() for ch in token):
|
||||
bearer_unauthorized()
|
||||
return token
|
||||
|
||||
|
||||
async def current_user(request: Request):
|
||||
token = parse_bearer(request)
|
||||
user = await call_store(store.user_for_token, token)
|
||||
if user is None:
|
||||
bearer_unauthorized()
|
||||
request.state.user_id = user["id"]
|
||||
request.state.token = token
|
||||
return user
|
||||
|
||||
|
||||
def parse_chat_id(chat_id):
|
||||
try:
|
||||
return str(uuid.UUID(chat_id))
|
||||
except ValueError:
|
||||
invalid()
|
||||
|
||||
|
||||
def parse_limit(raw):
|
||||
if raw is None:
|
||||
return 50
|
||||
if not isinstance(raw, str) or len(raw) > 3 or not raw.isdigit():
|
||||
invalid()
|
||||
value = int(raw)
|
||||
if value < 1 or value > 100:
|
||||
invalid()
|
||||
return value
|
||||
|
||||
|
||||
async def read_json(request: Request):
|
||||
ctype = request.headers.get("content-type", "")
|
||||
if "application/json" not in ctype.lower():
|
||||
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
|
||||
length = request.headers.get("content-length")
|
||||
if length is not None and (not length.isdigit() or int(length) > MAX_JSON_BYTES):
|
||||
raise ApiError(413, "payload_too_large", "Слишком большое тело")
|
||||
raw = await request.body()
|
||||
if len(raw) > MAX_JSON_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "Слишком большое тело")
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except (ValueError, UnicodeError):
|
||||
invalid()
|
||||
if not isinstance(payload, dict):
|
||||
invalid()
|
||||
return payload
|
||||
|
||||
|
||||
def parse_idempotency_key(request: Request):
|
||||
key = request.headers.get("Idempotency-Key")
|
||||
if key is None or not IDEMPOTENCY_RE.fullmatch(key):
|
||||
invalid()
|
||||
return key
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
async def liveness(request: Request):
|
||||
return json_ok(request, {"status": "ok"})
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def readiness(request: Request):
|
||||
if store.shutting_down:
|
||||
raise ApiError(503, "unavailable", "Сервис временно недоступен")
|
||||
ok = await call_store(store.ready)
|
||||
if not ok:
|
||||
unavailable()
|
||||
return json_ok(request, {"status": "ok"})
|
||||
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
async def register_user(request: Request, body: CreateUser):
|
||||
user = await call_store(store.create_user, body.username, body.display_name, body.password)
|
||||
if user is None:
|
||||
raise ApiError(409, "conflict", "Имя пользователя занято")
|
||||
return json_ok(request, user, 201)
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
async def create_session(request: Request):
|
||||
username, password = parse_basic(request)
|
||||
session = await call_store(store.login, username, password)
|
||||
if session is None:
|
||||
basic_unauthorized()
|
||||
request.state.user_id = session["user"]["id"]
|
||||
return json_ok(request, session, 201)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
async def revoke_session(request: Request):
|
||||
user = await current_user(request)
|
||||
request.state.user_id = user["id"]
|
||||
removed = await call_store(store.revoke, request.state.token)
|
||||
if not removed:
|
||||
bearer_unauthorized()
|
||||
return stamp(request, Response(status_code=204))
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
async def me(request: Request):
|
||||
user = await current_user(request)
|
||||
return json_ok(request, user)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
async def create_chat(request: Request):
|
||||
user = await current_user(request)
|
||||
payload = await read_json(request)
|
||||
try:
|
||||
body = CreateChat.model_validate(payload)
|
||||
except ValidationError:
|
||||
invalid()
|
||||
try:
|
||||
chat = await call_store(store.create_chat, body.title, body.member_ids, user["id"])
|
||||
except ValueError:
|
||||
invalid()
|
||||
return json_ok(request, chat, 201)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(request: Request):
|
||||
user = await current_user(request)
|
||||
limit = parse_limit(request.query_params.get("limit"))
|
||||
cursor = request.query_params.get("cursor")
|
||||
if cursor is not None and (not cursor or len(cursor) > 512):
|
||||
invalid()
|
||||
try:
|
||||
items, next_cursor = await call_store(store.list_chats, user["id"], limit, cursor)
|
||||
except ValueError:
|
||||
invalid()
|
||||
return json_ok(request, {"items": items, "next_cursor": next_cursor})
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(request: Request, chat_id: str):
|
||||
user = await current_user(request)
|
||||
chat = await call_store(store.get_chat, parse_chat_id(chat_id), user["id"])
|
||||
if chat is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
return json_ok(request, chat)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
async def create_message(request: Request, chat_id: str):
|
||||
user = await current_user(request)
|
||||
canonical = parse_chat_id(chat_id)
|
||||
payload = await read_json(request)
|
||||
key = parse_idempotency_key(request)
|
||||
try:
|
||||
body = CreateMessage.model_validate(payload)
|
||||
except ValidationError:
|
||||
invalid()
|
||||
message = await call_store(store.add_message, canonical, user["id"], body.text, key)
|
||||
if message is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
return json_ok(request, message, 201)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(request: Request, chat_id: str):
|
||||
user = await current_user(request)
|
||||
canonical = parse_chat_id(chat_id)
|
||||
limit = parse_limit(request.query_params.get("limit"))
|
||||
cursor = request.query_params.get("cursor")
|
||||
if cursor is not None and (not cursor or len(cursor) > 512):
|
||||
invalid()
|
||||
try:
|
||||
result = await call_store(store.list_messages, canonical, user["id"], limit, cursor)
|
||||
except ValueError:
|
||||
invalid()
|
||||
if result is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
items, next_cursor = result
|
||||
return json_ok(request, {"items": items, "next_cursor": next_cursor})
|
||||
|
||||
|
||||
def setup_logging():
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
setup_logging()
|
||||
host = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
port = int(os.environ.get("APP_PORT", "8080"))
|
||||
uvicorn.run(
|
||||
app,
|
||||
host=host,
|
||||
port=port,
|
||||
timeout_graceful_shutdown=5,
|
||||
timeout_keep_alive=2,
|
||||
access_log=False,
|
||||
)
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
"""Однократные миграции. Запускается отдельным контейнером, не каждой репликой API."""
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
LOGGER = logging.getLogger("migrate")
|
||||
MIGRATION_LOCK = 421003
|
||||
CONNECT_TIMEOUT = 3
|
||||
|
||||
|
||||
def read_secret_file(path):
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
return handle.read().strip()
|
||||
|
||||
|
||||
def database_url():
|
||||
path = os.environ.get("DATABASE_URL_FILE")
|
||||
if path:
|
||||
return read_secret_file(path)
|
||||
url = os.environ.get("DATABASE_URL", "").strip()
|
||||
if not url:
|
||||
raise RuntimeError("DATABASE_URL_FILE")
|
||||
return url
|
||||
|
||||
|
||||
def split_sql(script):
|
||||
parts = []
|
||||
buf = []
|
||||
for line in script.splitlines():
|
||||
if line.strip().startswith("--"):
|
||||
continue
|
||||
buf.append(line)
|
||||
if line.strip().endswith(";"):
|
||||
statement = "\n".join(buf).strip()
|
||||
if statement.endswith(";"):
|
||||
statement = statement[:-1].strip()
|
||||
if statement:
|
||||
parts.append(statement)
|
||||
buf = []
|
||||
tail = "\n".join(buf).strip().rstrip(";").strip()
|
||||
if tail:
|
||||
parts.append(tail)
|
||||
return parts
|
||||
|
||||
|
||||
def wait_postgres(conninfo):
|
||||
last = None
|
||||
for _ in range(60):
|
||||
try:
|
||||
with psycopg.connect(conninfo, connect_timeout=CONNECT_TIMEOUT) as conn:
|
||||
conn.execute("SELECT 1")
|
||||
return
|
||||
except psycopg.OperationalError as exc:
|
||||
last = type(exc).__name__
|
||||
time.sleep(1)
|
||||
LOGGER.error("postgres not ready: %s", last)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def apply(conninfo):
|
||||
directory = Path(__file__).resolve().parents[1] / "migrations"
|
||||
with psycopg.connect(conninfo, connect_timeout=CONNECT_TIMEOUT, row_factory=dict_row) as conn:
|
||||
conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATION_LOCK,))
|
||||
conn.commit()
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.commit()
|
||||
for path in sorted(directory.glob("*.sql")):
|
||||
version = path.stem
|
||||
found = conn.execute(
|
||||
"SELECT 1 FROM schema_migrations WHERE version = %s",
|
||||
(version,),
|
||||
).fetchone()
|
||||
conn.rollback()
|
||||
if found:
|
||||
LOGGER.info("migration %s already applied", version)
|
||||
continue
|
||||
with conn.transaction():
|
||||
for statement in split_sql(path.read_text(encoding="utf-8")):
|
||||
conn.execute(statement)
|
||||
conn.execute(
|
||||
"INSERT INTO schema_migrations (version) VALUES (%s)",
|
||||
(version,),
|
||||
)
|
||||
LOGGER.info("migration %s applied", version)
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATION_LOCK,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
conninfo = database_url()
|
||||
wait_postgres(conninfo)
|
||||
apply(conninfo)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,26 @@
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHash, VerificationError, VerifyMismatchError
|
||||
|
||||
# Параметры ближе к учебному стенду, чем к максимальным: time=2, 19 MiB, Argon2id.
|
||||
# Хеш всё равно медленный password KDF, не SHA-256 и не открытый текст.
|
||||
hasher = PasswordHasher(
|
||||
time_cost=2,
|
||||
memory_cost=19456,
|
||||
parallelism=1,
|
||||
hash_len=32,
|
||||
salt_len=16,
|
||||
)
|
||||
|
||||
# Чтобы неизвестный username не отвечал заметно быстрее известного.
|
||||
DUMMY_HASH = hasher.hash("dummy-password-not-a-user")
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
return hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password, encoded):
|
||||
try:
|
||||
return hasher.verify(encoded, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHash):
|
||||
return False
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, field_validator, model_validator
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
def _visible(value, limit):
|
||||
if not isinstance(value, str) or not value.strip() or len(value) > limit:
|
||||
raise ValueError("text")
|
||||
return value
|
||||
|
||||
|
||||
class CreateUser(StrictModel):
|
||||
username: str
|
||||
display_name: str
|
||||
password: str
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def username_ok(cls, value):
|
||||
if not isinstance(value, str) or not USERNAME_RE.fullmatch(value):
|
||||
raise ValueError("username")
|
||||
return value
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def display_name_ok(cls, value):
|
||||
return _visible(value, 100)
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def password_ok(cls, value):
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValueError("password")
|
||||
# Длина в code points, не в байтах: bcrypt тут не подходит из-за усечения UTF-8.
|
||||
if len(value) < 12 or len(value) > 128:
|
||||
raise ValueError("password")
|
||||
return value
|
||||
|
||||
|
||||
class CreateChat(StrictModel):
|
||||
title: str
|
||||
member_ids: list
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def title_ok(cls, value):
|
||||
return _visible(value, 100)
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def member_ids_ok(cls, value):
|
||||
if not isinstance(value, list) or not (1 <= len(value) <= 100):
|
||||
raise ValueError("member_ids")
|
||||
# Канонический UUID (нижний регистр). Иначе один и тот же id
|
||||
# в разном регистре выглядит как два участника и упирается в PK.
|
||||
normalized = []
|
||||
seen = set()
|
||||
for item in value:
|
||||
if not isinstance(item, str):
|
||||
raise ValueError("member_ids")
|
||||
try:
|
||||
canonical = str(uuid.UUID(item))
|
||||
except ValueError as exc:
|
||||
raise ValueError("member_ids") from exc
|
||||
if canonical in seen:
|
||||
raise ValueError("member_ids")
|
||||
seen.add(canonical)
|
||||
normalized.append(canonical)
|
||||
return normalized
|
||||
|
||||
|
||||
class CreateMessage(StrictModel):
|
||||
text: str
|
||||
attachment_ids: list = []
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def fill_attachments(cls, value):
|
||||
# Нет поля и явный [] — одно и то же тело для Idempotency-Key.
|
||||
if not isinstance(value, dict):
|
||||
return value
|
||||
data = dict(value)
|
||||
data.setdefault("attachment_ids", [])
|
||||
return data
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def text_ok(cls, value):
|
||||
return _visible(value, 4000)
|
||||
|
||||
@field_validator("attachment_ids")
|
||||
@classmethod
|
||||
def attachments_ok(cls, value):
|
||||
# Вложения появляются в lab4. Пустой список равен пропуску поля.
|
||||
# Непустой список здесь отклоняем: хранилища файлов ещё нет.
|
||||
if not isinstance(value, list) or len(value) != 0:
|
||||
raise ValueError("attachment_ids")
|
||||
return []
|
||||
+601
@@ -0,0 +1,601 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import socket
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import psycopg
|
||||
import redis
|
||||
from psycopg.errors import ForeignKeyViolation, UniqueViolation
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool, PoolTimeout
|
||||
|
||||
from errors import DependencyDown, IdempotencyConflict
|
||||
from passwords import DUMMY_HASH, hash_password, verify_password
|
||||
|
||||
LOGGER = logging.getLogger("messenger")
|
||||
|
||||
POOL_TIMEOUT_SECONDS = 3
|
||||
STATEMENT_TIMEOUT_MS = 5000
|
||||
LOCK_TIMEOUT_MS = 3000
|
||||
REDIS_MAX_CONNECTIONS = 16
|
||||
REDIS_SOCKET_TIMEOUT = 2
|
||||
SCHEMA_VERSION = "002_idempotency"
|
||||
|
||||
SQL_MESSAGES_FIRST = """
|
||||
SELECT id, chat_id, sender_id, body AS text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = %s
|
||||
ORDER BY created_at, id
|
||||
LIMIT %s
|
||||
"""
|
||||
|
||||
SQL_MESSAGES_AFTER = """
|
||||
SELECT id, chat_id, sender_id, body AS text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = %s
|
||||
AND (created_at, id) > (%s, %s)
|
||||
ORDER BY created_at, id
|
||||
LIMIT %s
|
||||
"""
|
||||
|
||||
SQL_MESSAGE_BY_ID = """
|
||||
SELECT id, chat_id, sender_id, body AS text, created_at
|
||||
FROM messages
|
||||
WHERE id = %s
|
||||
"""
|
||||
|
||||
|
||||
def instance_id():
|
||||
# Docker без hostname: в контейнере это id контейнера, он не меняется,
|
||||
# пока живёт этот контейнер. stop-one.sh находит контейнер по этому значению.
|
||||
return socket.gethostname()
|
||||
|
||||
|
||||
def pool_max():
|
||||
raw = os.environ.get("POOL_MAX", "10")
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError as exc:
|
||||
raise RuntimeError("POOL_MAX") from exc
|
||||
if not 1 <= value <= 32:
|
||||
raise RuntimeError("POOL_MAX")
|
||||
return value
|
||||
|
||||
|
||||
def utc_now():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def dump_time(value):
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
text = value.astimezone(timezone.utc).isoformat(timespec="microseconds")
|
||||
if text.endswith("+00:00"):
|
||||
text = text[:-6] + "Z"
|
||||
return text
|
||||
|
||||
|
||||
def parse_time(value):
|
||||
if not isinstance(value, str) or not value.endswith("Z"):
|
||||
raise ValueError("time")
|
||||
return datetime.fromisoformat(value[:-1] + "+00:00")
|
||||
|
||||
|
||||
def encode_cursor(scope, created_at, item_id):
|
||||
raw = "{}|{}|{}".format(scope, created_at, item_id).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor, expected_scope):
|
||||
if not isinstance(cursor, str) or not cursor or len(cursor) > 512:
|
||||
raise ValueError("cursor")
|
||||
pad = "=" * (-len(cursor) % 4)
|
||||
try:
|
||||
decoded = base64.urlsafe_b64decode(cursor + pad).decode("utf-8")
|
||||
except (ValueError, UnicodeError) as exc:
|
||||
raise ValueError("cursor") from exc
|
||||
parts = decoded.split("|")
|
||||
if len(parts) != 3:
|
||||
raise ValueError("cursor")
|
||||
scope, created_at, item_id = parts
|
||||
if scope != expected_scope:
|
||||
raise ValueError("cursor")
|
||||
parse_time(created_at)
|
||||
try:
|
||||
uuid.UUID(item_id)
|
||||
except ValueError as exc:
|
||||
raise ValueError("cursor") from exc
|
||||
return created_at, item_id
|
||||
|
||||
|
||||
def session_key(token):
|
||||
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
return "sess:" + digest
|
||||
|
||||
|
||||
def message_fingerprint(text):
|
||||
# Канонический JSON: порядок ключей не важен, пропущенный attachment_ids равен [].
|
||||
canonical = json.dumps(
|
||||
{"attachment_ids": [], "text": text},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def advisory_key(user_id, path, idem_key):
|
||||
raw = "\0".join((user_id, "POST", path, idem_key)).encode("utf-8")
|
||||
digest = hashlib.sha256(raw).digest()
|
||||
return int.from_bytes(digest[:8], "big", signed=True)
|
||||
|
||||
|
||||
def chat_path(chat_id):
|
||||
return "/api/v1/chats/" + chat_id + "/messages"
|
||||
|
||||
|
||||
def public_user(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": dump_time(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def public_message(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": dump_time(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def public_chat(row, member_ids=None):
|
||||
members = member_ids if member_ids is not None else row["member_ids"]
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(item) for item in members],
|
||||
"created_at": dump_time(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def read_secret_file(path):
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
return handle.read().strip()
|
||||
|
||||
|
||||
def _db_down(exc):
|
||||
raise DependencyDown() from exc
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self):
|
||||
self.pool = None
|
||||
self.redis = None
|
||||
self.ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
self.idem_ttl = int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||
self.pool_size = pool_max()
|
||||
self.shutting_down = False
|
||||
if self.ttl < 1 or self.idem_ttl < 1:
|
||||
raise RuntimeError("TTL")
|
||||
kind = os.environ.get("SESSION_STORE", "redis").strip().lower()
|
||||
if kind != "redis":
|
||||
raise RuntimeError("SESSION_STORE")
|
||||
|
||||
def database_url(self):
|
||||
path = os.environ.get("DATABASE_URL_FILE")
|
||||
if path:
|
||||
return read_secret_file(path)
|
||||
url = os.environ.get("DATABASE_URL", "").strip()
|
||||
if not url:
|
||||
raise RuntimeError("DATABASE_URL_FILE")
|
||||
return url
|
||||
|
||||
def redis_url(self):
|
||||
path = os.environ.get("CACHE_URL_FILE")
|
||||
if path:
|
||||
return read_secret_file(path)
|
||||
url = os.environ.get("CACHE_URL", "").strip()
|
||||
if not url:
|
||||
raise RuntimeError("CACHE_URL_FILE")
|
||||
return url
|
||||
|
||||
def startup(self):
|
||||
conninfo = self.database_url()
|
||||
self._wait_schema(conninfo)
|
||||
self.pool = ConnectionPool(
|
||||
conninfo,
|
||||
min_size=1,
|
||||
max_size=self.pool_size,
|
||||
timeout=POOL_TIMEOUT_SECONDS,
|
||||
max_waiting=64,
|
||||
max_lifetime=300,
|
||||
kwargs={
|
||||
"connect_timeout": POOL_TIMEOUT_SECONDS,
|
||||
"row_factory": dict_row,
|
||||
"application_name": "mtusi-lab3-" + instance_id(),
|
||||
"options": "-c statement_timeout={} -c lock_timeout={} -c idle_in_transaction_session_timeout=15000".format(
|
||||
STATEMENT_TIMEOUT_MS,
|
||||
LOCK_TIMEOUT_MS,
|
||||
),
|
||||
},
|
||||
open=True,
|
||||
)
|
||||
pool = redis.ConnectionPool.from_url(
|
||||
self.redis_url(),
|
||||
max_connections=REDIS_MAX_CONNECTIONS,
|
||||
socket_timeout=REDIS_SOCKET_TIMEOUT,
|
||||
socket_connect_timeout=REDIS_SOCKET_TIMEOUT,
|
||||
health_check_interval=30,
|
||||
decode_responses=True,
|
||||
)
|
||||
self.redis = redis.Redis(connection_pool=pool)
|
||||
self._wait_redis()
|
||||
LOGGER.info("ready instance=%s ttl=%s pool_max=%s", instance_id(), self.ttl, self.pool_size)
|
||||
|
||||
def shutdown(self):
|
||||
self.shutting_down = True
|
||||
if self.pool is not None:
|
||||
self.pool.close()
|
||||
if self.redis is not None:
|
||||
self.redis.close()
|
||||
|
||||
def ready(self):
|
||||
if self.shutting_down or self.pool is None or self.redis is None:
|
||||
return False
|
||||
try:
|
||||
with self.pool.connection(timeout=POOL_TIMEOUT_SECONDS) as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM schema_migrations WHERE version = %s",
|
||||
(SCHEMA_VERSION,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
self.redis.ping()
|
||||
except Exception:
|
||||
LOGGER.warning("ready check failed")
|
||||
return False
|
||||
return True
|
||||
|
||||
def _wait_redis(self):
|
||||
last = None
|
||||
for _ in range(60):
|
||||
try:
|
||||
self.redis.ping()
|
||||
return
|
||||
except redis.RedisError as exc:
|
||||
last = type(exc).__name__
|
||||
time.sleep(1)
|
||||
LOGGER.error("redis not ready: %s", last)
|
||||
raise SystemExit(1)
|
||||
|
||||
def _wait_schema(self, conninfo):
|
||||
# Схему накатывает сервис migrate. Реплики только ждут её, не применяют сами.
|
||||
last = None
|
||||
for _ in range(90):
|
||||
try:
|
||||
with psycopg.connect(conninfo, connect_timeout=POOL_TIMEOUT_SECONDS, row_factory=dict_row) as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM schema_migrations WHERE version = %s",
|
||||
(SCHEMA_VERSION,),
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
return
|
||||
last = "migration missing"
|
||||
except psycopg.Error as exc:
|
||||
last = type(exc).__name__
|
||||
time.sleep(1)
|
||||
LOGGER.error("schema not ready: %s", last)
|
||||
raise SystemExit(1)
|
||||
|
||||
def _connect(self):
|
||||
try:
|
||||
return self.pool.connection(timeout=POOL_TIMEOUT_SECONDS)
|
||||
except PoolTimeout as exc:
|
||||
_db_down(exc)
|
||||
|
||||
def create_user(self, username, display_name, password):
|
||||
password_hash = hash_password(password)
|
||||
user_id = uuid.uuid4()
|
||||
created = utc_now()
|
||||
try:
|
||||
with self._connect() as conn:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
ON CONFLICT (username) DO NOTHING
|
||||
RETURNING id, username, display_name, created_at
|
||||
""",
|
||||
(user_id, username, display_name, password_hash, created),
|
||||
).fetchone()
|
||||
except psycopg.OperationalError as exc:
|
||||
_db_down(exc)
|
||||
if row is None:
|
||||
return None
|
||||
return public_user(row)
|
||||
|
||||
def login(self, username, password):
|
||||
try:
|
||||
with self._connect() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = %s
|
||||
""",
|
||||
(username,),
|
||||
).fetchone()
|
||||
except psycopg.OperationalError as exc:
|
||||
_db_down(exc)
|
||||
if row is None:
|
||||
verify_password(password, DUMMY_HASH)
|
||||
return None
|
||||
if not verify_password(password, row["password_hash"]):
|
||||
return None
|
||||
return self._issue(public_user(row))
|
||||
|
||||
def _issue(self, user):
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires = utc_now() + timedelta(seconds=self.ttl)
|
||||
payload = json.dumps(
|
||||
{"user_id": user["id"], "expires_at": dump_time(expires)},
|
||||
separators=(",", ":"),
|
||||
)
|
||||
# pxat — абсолютное время. Рестарт Redis не сдвигает срок.
|
||||
# В значении тоже лежит expires_at: даже если TTL ключа разъедется, сессия кончится вовремя.
|
||||
try:
|
||||
self.redis.set(session_key(token), payload, pxat=int(expires.timestamp() * 1000))
|
||||
except redis.RedisError as exc:
|
||||
raise DependencyDown() from exc
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": dump_time(expires),
|
||||
"user": user,
|
||||
}
|
||||
|
||||
def user_for_token(self, token):
|
||||
key = session_key(token)
|
||||
try:
|
||||
raw = self.redis.get(key)
|
||||
except redis.RedisError as exc:
|
||||
raise DependencyDown() from exc
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
expires = parse_time(payload["expires_at"])
|
||||
user_id = payload["user_id"]
|
||||
uuid.UUID(user_id)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return None
|
||||
if utc_now() >= expires:
|
||||
try:
|
||||
self.redis.delete(key)
|
||||
except redis.RedisError as exc:
|
||||
raise DependencyDown() from exc
|
||||
return None
|
||||
try:
|
||||
with self._connect() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = %s
|
||||
""",
|
||||
(user_id,),
|
||||
).fetchone()
|
||||
except psycopg.OperationalError as exc:
|
||||
_db_down(exc)
|
||||
if row is None:
|
||||
return None
|
||||
return public_user(row)
|
||||
|
||||
def revoke(self, token):
|
||||
try:
|
||||
deleted = self.redis.delete(session_key(token))
|
||||
except redis.RedisError as exc:
|
||||
raise DependencyDown() from exc
|
||||
return deleted == 1
|
||||
|
||||
def create_chat(self, title, member_ids, caller_id):
|
||||
try:
|
||||
caller_uuid = uuid.UUID(str(caller_id))
|
||||
member_uuids = []
|
||||
seen = set()
|
||||
for item in member_ids:
|
||||
member_uuid = uuid.UUID(str(item))
|
||||
if member_uuid in seen:
|
||||
raise ValueError("members")
|
||||
seen.add(member_uuid)
|
||||
member_uuids.append(member_uuid)
|
||||
except ValueError as exc:
|
||||
raise ValueError("members") from exc
|
||||
if caller_uuid not in seen:
|
||||
raise ValueError("members")
|
||||
chat_id = uuid.uuid4()
|
||||
created = utc_now()
|
||||
canonical_members = [str(item) for item in member_uuids]
|
||||
try:
|
||||
with self._connect() as conn:
|
||||
try:
|
||||
with conn.transaction():
|
||||
conn.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||
(chat_id, title, created),
|
||||
)
|
||||
for ordinal, member_id in enumerate(member_uuids):
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO chat_members (chat_id, user_id, ordinal)
|
||||
VALUES (%s, %s, %s)
|
||||
""",
|
||||
(chat_id, member_id, ordinal),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT id, title, created_at FROM chats WHERE id = %s",
|
||||
(chat_id,),
|
||||
).fetchone()
|
||||
except ForeignKeyViolation as exc:
|
||||
raise ValueError("members") from exc
|
||||
except UniqueViolation as exc:
|
||||
raise ValueError("members") from exc
|
||||
except psycopg.OperationalError as exc:
|
||||
_db_down(exc)
|
||||
return public_chat(row, canonical_members)
|
||||
|
||||
def _member(self, conn, chat_id, user_id):
|
||||
return conn.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id),
|
||||
).fetchone()
|
||||
|
||||
def get_chat(self, chat_id, user_id):
|
||||
try:
|
||||
with self._connect() as conn:
|
||||
if self._member(conn, chat_id, user_id) is None:
|
||||
return None
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(m.user_id ORDER BY m.ordinal) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE c.id = %s
|
||||
GROUP BY c.id
|
||||
""",
|
||||
(chat_id,),
|
||||
).fetchone()
|
||||
except psycopg.OperationalError as exc:
|
||||
_db_down(exc)
|
||||
if row is None:
|
||||
return None
|
||||
return public_chat(row)
|
||||
|
||||
def list_chats(self, user_id, limit, cursor):
|
||||
after = None
|
||||
if cursor is not None:
|
||||
created_at, item_id = decode_cursor(cursor, "chats:" + user_id)
|
||||
after = (parse_time(created_at), uuid.UUID(item_id))
|
||||
sql = """
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(m.user_id ORDER BY m.ordinal) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = %s
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
"""
|
||||
params = [user_id]
|
||||
if after is not None:
|
||||
sql += " WHERE (c.created_at, c.id) > (%s, %s)"
|
||||
params.extend(after)
|
||||
sql += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
try:
|
||||
with self._connect() as conn:
|
||||
rows = conn.execute(sql, params).fetchall()
|
||||
except psycopg.OperationalError as exc:
|
||||
_db_down(exc)
|
||||
page = [public_chat(row) for row in rows[:limit]]
|
||||
if len(rows) > limit and page:
|
||||
last = page[-1]
|
||||
return page, encode_cursor("chats:" + user_id, last["created_at"], last["id"])
|
||||
return page, None
|
||||
|
||||
def add_message(self, chat_id, sender_id, text, idem_key):
|
||||
# Один ключ сериализуется между репликами через advisory lock в той же
|
||||
# транзакции, где INSERT сообщения. Откат не оставляет ключ занятым.
|
||||
path = chat_path(chat_id)
|
||||
digest = message_fingerprint(text)
|
||||
lock_key = advisory_key(sender_id, path, idem_key)
|
||||
message_id = uuid.uuid4()
|
||||
try:
|
||||
with self._connect() as conn:
|
||||
with conn.transaction():
|
||||
# Иначе lock_timeout сессии (3 с) оборвёт очередь одинаковых ключей.
|
||||
conn.execute("SET LOCAL lock_timeout = '15s'")
|
||||
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_key,))
|
||||
if self._member(conn, chat_id, sender_id) is None:
|
||||
return None
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT request_hash, message_id,
|
||||
created_at >= now() - make_interval(secs => %s) AS fresh
|
||||
FROM idempotency_keys
|
||||
WHERE user_id = %s AND http_method = 'POST'
|
||||
AND request_path = %s AND idem_key = %s
|
||||
""",
|
||||
(self.idem_ttl, sender_id, path, idem_key),
|
||||
).fetchone()
|
||||
if existing is not None and existing["fresh"]:
|
||||
if existing["request_hash"] != digest:
|
||||
raise IdempotencyConflict()
|
||||
row = conn.execute(SQL_MESSAGE_BY_ID, (existing["message_id"],)).fetchone()
|
||||
if row is None:
|
||||
raise RuntimeError("idempotency target missing")
|
||||
return public_message(row)
|
||||
if existing is not None:
|
||||
conn.execute(
|
||||
"""
|
||||
DELETE FROM idempotency_keys
|
||||
WHERE user_id = %s AND http_method = 'POST'
|
||||
AND request_path = %s AND idem_key = %s
|
||||
""",
|
||||
(sender_id, path, idem_key),
|
||||
)
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, body, created_at)
|
||||
VALUES (%s, %s, %s, %s, clock_timestamp())
|
||||
RETURNING id, chat_id, sender_id, body AS text, created_at
|
||||
""",
|
||||
(message_id, chat_id, sender_id, text),
|
||||
).fetchone()
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO idempotency_keys (
|
||||
user_id, http_method, request_path, idem_key,
|
||||
request_hash, message_id, created_at
|
||||
)
|
||||
VALUES (%s, 'POST', %s, %s, %s, %s, clock_timestamp())
|
||||
""",
|
||||
(sender_id, path, idem_key, digest, row["id"]),
|
||||
)
|
||||
return public_message(row)
|
||||
except psycopg.OperationalError as exc:
|
||||
_db_down(exc)
|
||||
|
||||
def list_messages(self, chat_id, user_id, limit, cursor):
|
||||
after = None
|
||||
if cursor is not None:
|
||||
created_at, item_id = decode_cursor(cursor, chat_id)
|
||||
after = (parse_time(created_at), uuid.UUID(item_id))
|
||||
try:
|
||||
with self._connect() as conn:
|
||||
if self._member(conn, chat_id, user_id) is None:
|
||||
return None
|
||||
if after is None:
|
||||
rows = conn.execute(SQL_MESSAGES_FIRST, (chat_id, limit + 1)).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
SQL_MESSAGES_AFTER,
|
||||
(chat_id, after[0], after[1], limit + 1),
|
||||
).fetchall()
|
||||
except psycopg.OperationalError as exc:
|
||||
_db_down(exc)
|
||||
page = [public_message(row) for row in rows[:limit]]
|
||||
if len(rows) > limit and page:
|
||||
last = page[-1]
|
||||
return page, encode_cursor(chat_id, last["created_at"], last["id"])
|
||||
return page, None
|
||||
@@ -0,0 +1,36 @@
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
BASE = "http://127.0.0.1:8080"
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None, timeout=30, raw=None):
|
||||
hdrs = {"Accept": "application/json"}
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
hdrs["Content-Type"] = "application/json"
|
||||
if headers:
|
||||
hdrs.update(headers)
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=hdrs, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(req, timeout=timeout)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
payload_bytes = response.read()
|
||||
payload = None
|
||||
if payload_bytes:
|
||||
payload = json.loads(payload_bytes.decode("utf-8"))
|
||||
return response.status, response.headers, payload
|
||||
|
||||
|
||||
def bearer(token):
|
||||
return {"Authorization": "Bearer " + token}
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
import base64
|
||||
|
||||
raw = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
|
||||
return {"Authorization": "Basic " + raw}
|
||||
@@ -0,0 +1,200 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Контракт lab3 без остановки стенда: сессия, UUID, идемпотентность, две реплики."""
|
||||
import json
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
from httpapi import basic, bearer, call
|
||||
from sql import compose, psql
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EVIDENCE = ROOT / "evidence" / "student_checks.txt"
|
||||
LINES = []
|
||||
|
||||
|
||||
def log(text):
|
||||
print(text)
|
||||
LINES.append(text)
|
||||
|
||||
|
||||
def check(cond, message):
|
||||
if not cond:
|
||||
log("FAIL: " + message)
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def register(username, display_name, password):
|
||||
status, _, payload = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": username, "display_name": display_name, "password": password},
|
||||
)
|
||||
check(status == 201, "register {} -> {}".format(username, status))
|
||||
check("password" not in payload and "password_hash" not in payload, "password leaked")
|
||||
return payload
|
||||
|
||||
|
||||
def login(username, password):
|
||||
status, headers, payload = call("POST", "/api/v1/auth/sessions", headers=basic(username, password))
|
||||
check(status == 201, "login -> {}".format(status))
|
||||
check(headers.get("X-Instance-Id"), "login without instance")
|
||||
check(payload["token_type"] == "Bearer", "token type")
|
||||
check(len(payload["token"]) >= 43, "token length")
|
||||
check(username not in payload["token"], "token contains username")
|
||||
return payload
|
||||
|
||||
|
||||
def main():
|
||||
suffix = uuid.uuid4().hex[:10]
|
||||
alice = register("a_" + suffix, "Алиса", "long-enough-pw-1")
|
||||
bob = register("b_" + suffix, "Боб", "long-enough-pw-2")
|
||||
session = login("a_" + suffix, "long-enough-pw-1")
|
||||
token = session["token"]
|
||||
auth = bearer(token)
|
||||
|
||||
status, _, _ = call("GET", "/api/v1/users/me")
|
||||
check(status == 401, "anon me {}".format(status))
|
||||
status, headers, me = call("GET", "/api/v1/users/me", headers={**auth, "X-User-Id": bob["id"]})
|
||||
check(status == 200 and me["id"] == alice["id"], "X-User-Id overrode session")
|
||||
check(headers.get("X-Instance-Id"), "me without instance")
|
||||
|
||||
before = int(psql("SELECT count(*) FROM chats;"))
|
||||
status, _, body = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "Дубликат UUID", "member_ids": [alice["id"], alice["id"].upper()]},
|
||||
headers=auth,
|
||||
)
|
||||
after = int(psql("SELECT count(*) FROM chats;"))
|
||||
check(status == 400 and before == after, "case-duplicate members {} chats {}->{}".format(status, before, after))
|
||||
check(body.get("error", {}).get("code") == "invalid_request", "case-duplicate code")
|
||||
|
||||
status, _, chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "Лаба 3", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers=auth,
|
||||
)
|
||||
check(status == 201, "create chat {}".format(status))
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
upper_path = "/api/v1/chats/" + chat["id"].upper() + "/messages"
|
||||
|
||||
seen = set()
|
||||
for _ in range(30):
|
||||
status, headers, _ = call("GET", "/api/v1/users/me", headers=auth)
|
||||
check(status == 200, "spread {}".format(status))
|
||||
seen.add(headers["X-Instance-Id"])
|
||||
check(len(seen) >= 2, "observed instances {}".format(len(seen)))
|
||||
log("instances {}".format(len(seen)))
|
||||
|
||||
key = "idem-" + uuid.uuid4().hex
|
||||
raw_a = json.dumps({"text": "Одинаково"}, ensure_ascii=False).encode("utf-8")
|
||||
raw_b = json.dumps({"attachment_ids": [], "text": "Одинаково"}, ensure_ascii=False).encode("utf-8")
|
||||
status, _, first = call(
|
||||
"POST",
|
||||
path,
|
||||
headers={**auth, "Content-Type": "application/json", "Idempotency-Key": key},
|
||||
raw=raw_a,
|
||||
)
|
||||
check(status == 201, "first message {}".format(status))
|
||||
status, _, replay = call(
|
||||
"POST",
|
||||
upper_path,
|
||||
headers={**auth, "Content-Type": "application/json", "Idempotency-Key": key},
|
||||
raw=raw_b,
|
||||
)
|
||||
check(status == 201 and replay == first, "replay differs")
|
||||
status, _, conflict = call(
|
||||
"POST",
|
||||
path,
|
||||
{"text": "другое тело"},
|
||||
headers={**auth, "Idempotency-Key": key},
|
||||
)
|
||||
check(status == 409 and conflict["error"]["code"] == "conflict", "different body {}".format(status))
|
||||
rows = int(psql("SELECT count(*) FROM messages WHERE id = '{}';".format(first["id"])))
|
||||
check(rows == 1, "message rows {}".format(rows))
|
||||
|
||||
status, _, _ = call("POST", path, {"text": "без ключа"}, headers=auth)
|
||||
check(status == 400, "missing key {}".format(status))
|
||||
status, _, _ = call(
|
||||
"POST",
|
||||
path,
|
||||
{"text": "плохой ключ"},
|
||||
headers={**auth, "Idempotency-Key": "bad key"},
|
||||
)
|
||||
check(status == 400, "bad key {}".format(status))
|
||||
status, _, _ = call(
|
||||
"POST",
|
||||
path,
|
||||
{"text": " "},
|
||||
headers={**auth, "Idempotency-Key": "blank-" + suffix},
|
||||
)
|
||||
check(status == 400, "blank text {}".format(status))
|
||||
|
||||
parallel_key = "par-" + uuid.uuid4().hex
|
||||
text = "Параллельно " + parallel_key
|
||||
|
||||
def once(_n):
|
||||
return call(
|
||||
"POST",
|
||||
path,
|
||||
{"text": text},
|
||||
headers={**auth, "Idempotency-Key": parallel_key},
|
||||
timeout=20,
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = list(pool.map(once, range(8)))
|
||||
codes = sorted(item[0] for item in results)
|
||||
bodies = [item[2] for item in results if item[0] == 201]
|
||||
check(codes == [201] * 8, "parallel codes {}".format(codes))
|
||||
check(all(item == bodies[0] for item in bodies), "parallel bodies differ")
|
||||
count = int(
|
||||
psql(
|
||||
"SELECT count(*) FROM messages WHERE chat_id = '{}' AND body = '{}';".format(chat["id"], text)
|
||||
)
|
||||
)
|
||||
check(count == 1, "parallel rows {}".format(count))
|
||||
log("parallel same key: 8x201, 1 row")
|
||||
|
||||
psql(
|
||||
"UPDATE idempotency_keys SET created_at = now() - interval '25 hours' WHERE idem_key = '{}';".format(key)
|
||||
)
|
||||
status, _, renewed = call(
|
||||
"POST",
|
||||
path,
|
||||
{"text": "Одинаково"},
|
||||
headers={**auth, "Idempotency-Key": key},
|
||||
)
|
||||
check(status == 201 and renewed["id"] != first["id"], "expired key did not create a new message")
|
||||
log("expired key created a new message")
|
||||
|
||||
versions = psql("SELECT version FROM schema_migrations ORDER BY 1;")
|
||||
check(versions == "001_init\n002_idempotency", "migrations [{}]".format(versions))
|
||||
log("migrations " + versions.replace("\n", ","))
|
||||
|
||||
inspected = compose("ps", "-q", "api")
|
||||
api_ids = [line.strip() for line in inspected.stdout.decode().splitlines() if line.strip()]
|
||||
check(len(api_ids) >= 2, "running api replicas {}".format(len(api_ids)))
|
||||
for api_id in api_ids:
|
||||
info = __import__("subprocess").run(
|
||||
["docker", "inspect", api_id],
|
||||
stdout=__import__("subprocess").PIPE,
|
||||
check=True,
|
||||
)
|
||||
data = json.loads(info.stdout.decode())[0]
|
||||
ports = data["HostConfig"].get("PortBindings") or {}
|
||||
check(not ports, "api publishes ports")
|
||||
check(data["HostConfig"]["NanoCpus"] > 0, "api cpu limit missing")
|
||||
check(data["HostConfig"]["Memory"] > 0, "api memory limit missing")
|
||||
log("api replicas {} have cpu/memory limits and no published ports".format(len(api_ids)))
|
||||
|
||||
EVIDENCE.parent.mkdir(exist_ok=True)
|
||||
EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8")
|
||||
log("PASS student checks")
|
||||
EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,219 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Поочерёдный отказ каждой реплики и rolling restart под нагрузкой."""
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from httpapi import basic, bearer, call
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence" / "grade4.txt"
|
||||
LINES = []
|
||||
|
||||
|
||||
def log(text):
|
||||
print(text)
|
||||
LINES.append(text)
|
||||
|
||||
|
||||
def save():
|
||||
OUT.parent.mkdir(exist_ok=True)
|
||||
OUT.write_text("\n".join(LINES) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def docker(*args, check=True):
|
||||
proc = subprocess.run(["docker", *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
|
||||
if check and proc.returncode != 0:
|
||||
raise RuntimeError(proc.stderr.decode("utf-8", "replace")[-500:])
|
||||
return proc
|
||||
|
||||
|
||||
def api_ids():
|
||||
proc = docker(
|
||||
"ps",
|
||||
"-q",
|
||||
"--filter",
|
||||
"label=com.docker.compose.project=mtusi-lab3",
|
||||
"--filter",
|
||||
"label=com.docker.compose.service=api",
|
||||
)
|
||||
return [line.strip() for line in proc.stdout.decode().splitlines() if line.strip()]
|
||||
|
||||
|
||||
def hostname(container_id):
|
||||
proc = docker("inspect", "-f", "{{.Config.Hostname}}", container_id)
|
||||
return proc.stdout.decode().strip()
|
||||
|
||||
|
||||
def wait_instances(token, expect, timeout=40):
|
||||
auth = bearer(token)
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
seen = set()
|
||||
ok = True
|
||||
for _ in range(12):
|
||||
try:
|
||||
status, headers, _ = call("GET", "/api/v1/users/me", headers=auth, timeout=3)
|
||||
except Exception:
|
||||
ok = False
|
||||
break
|
||||
if status != 200 or not headers.get("X-Instance-Id"):
|
||||
ok = False
|
||||
break
|
||||
seen.add(headers["X-Instance-Id"])
|
||||
if ok and len(seen) >= expect:
|
||||
return seen
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("instances did not return to {}".format(expect))
|
||||
|
||||
|
||||
def load_loop(auth, path, seconds, bucket):
|
||||
deadline = time.monotonic() + seconds
|
||||
n = 0
|
||||
while time.monotonic() < deadline:
|
||||
key = uuid.uuid4().hex
|
||||
started = time.monotonic()
|
||||
try:
|
||||
status, headers, _ = call(
|
||||
"POST",
|
||||
path,
|
||||
{"text": "load-" + key},
|
||||
headers={**auth, "Idempotency-Key": key},
|
||||
timeout=5,
|
||||
)
|
||||
bucket.append(
|
||||
{
|
||||
"ok": status == 201,
|
||||
"status": status,
|
||||
"instance": headers.get("X-Instance-Id", ""),
|
||||
"at": round(started, 3),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
bucket.append({"ok": False, "status": 0, "instance": "", "at": round(started, 3)})
|
||||
n += 1
|
||||
|
||||
|
||||
def summarize(bucket, mark):
|
||||
total = len(bucket)
|
||||
ok = [item for item in bucket if item["ok"]]
|
||||
bad = total - len(ok)
|
||||
after = [item for item in ok if item["at"] >= mark] if mark is not None else ok
|
||||
instances = sorted({item["instance"] for item in after if item["instance"]})
|
||||
elapsed = (bucket[-1]["at"] - bucket[0]["at"]) if len(bucket) > 1 else 0
|
||||
rps = round(len(ok) / elapsed, 3) if elapsed else None
|
||||
return {
|
||||
"requests": total,
|
||||
"ok": len(ok),
|
||||
"errors": bad,
|
||||
"error_ratio": round(bad / total, 4) if total else None,
|
||||
"successful_rps": rps,
|
||||
"instances_after_mark": instances,
|
||||
}
|
||||
|
||||
|
||||
def register_and_chat():
|
||||
suffix = uuid.uuid4().hex[:10]
|
||||
password = "grade4-password-1"
|
||||
status, _, alice = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": "g4_" + suffix, "display_name": "Нагрузка", "password": password},
|
||||
)
|
||||
if status != 201:
|
||||
raise RuntimeError("register {}".format(status))
|
||||
status, _, session = call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
headers=basic("g4_" + suffix, password),
|
||||
)
|
||||
if status != 201:
|
||||
raise RuntimeError("login {}".format(status))
|
||||
status, _, chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "Отказы", "member_ids": [alice["id"]]},
|
||||
headers=bearer(session["token"]),
|
||||
)
|
||||
if status != 201:
|
||||
raise RuntimeError("chat {}".format(status))
|
||||
return session["token"], "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
|
||||
|
||||
def failover_one(token, path, container_id):
|
||||
target = hostname(container_id)
|
||||
auth = bearer(token)
|
||||
bucket = []
|
||||
thread = threading.Thread(target=load_loop, args=(auth, path, 15, bucket))
|
||||
thread.start()
|
||||
time.sleep(2)
|
||||
stopped_at = time.monotonic()
|
||||
docker("stop", "--time", "5", container_id)
|
||||
thread.join()
|
||||
started_ids = set(hostname(item) for item in api_ids())
|
||||
summary = summarize(bucket, stopped_at)
|
||||
summary["stopped"] = target
|
||||
summary["stopped_still_running"] = target in started_ids
|
||||
summary["served_by_stopped_after"] = target in summary["instances_after_mark"]
|
||||
log("failover " + json.dumps(summary, ensure_ascii=False))
|
||||
docker("start", container_id)
|
||||
seen = wait_instances(token, 2)
|
||||
log("restored instances {}".format(len(seen)))
|
||||
return summary
|
||||
|
||||
|
||||
def rolling(token, path):
|
||||
auth = bearer(token)
|
||||
before = {item: docker("inspect", "-f", "{{.State.StartedAt}}", item).stdout.decode().strip() for item in api_ids()}
|
||||
bucket = []
|
||||
thread = threading.Thread(target=load_loop, args=(auth, path, 28, bucket))
|
||||
thread.start()
|
||||
time.sleep(2)
|
||||
mark = time.monotonic()
|
||||
for container_id in list(before):
|
||||
docker("restart", "--time", "5", container_id)
|
||||
deadline = time.monotonic() + 40
|
||||
while time.monotonic() < deadline:
|
||||
status = docker(
|
||||
"inspect",
|
||||
"-f",
|
||||
"{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}",
|
||||
container_id,
|
||||
).stdout.decode().strip()
|
||||
if status == "healthy":
|
||||
break
|
||||
time.sleep(1)
|
||||
time.sleep(2)
|
||||
thread.join()
|
||||
after = {item: docker("inspect", "-f", "{{.State.StartedAt}}", item).stdout.decode().strip() for item in api_ids()}
|
||||
changed = sorted(item[:12] for item in before if before.get(item) != after.get(item))
|
||||
summary = summarize(bucket, mark)
|
||||
summary["restarted"] = len(changed)
|
||||
log("rolling " + json.dumps(summary, ensure_ascii=False))
|
||||
wait_instances(token, 2)
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
token, path = register_and_chat()
|
||||
ids = api_ids()
|
||||
if len(ids) < 2:
|
||||
raise SystemExit("need 2 api replicas, have {}".format(len(ids)))
|
||||
rolling(token, path)
|
||||
# Снимок id заново: rolling не меняет container id, но список перечитываем.
|
||||
for container_id in api_ids():
|
||||
failover_one(token, path, container_id)
|
||||
save()
|
||||
print("PASS grade4")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as exc:
|
||||
log("FAIL: " + type(exc).__name__ + " " + str(exc)[:300])
|
||||
save()
|
||||
raise
|
||||
@@ -0,0 +1,465 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 1. Фиксированный бюджет API 1/2/4, затем рост CPU Postgres и размера пула.
|
||||
|
||||
Числа пишет в evidence/. Это closed-loop POST, не открытый генератор и не пиковая мощность стенда.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from httpapi import basic, bearer, call
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EVIDENCE = ROOT / "evidence"
|
||||
PROJECT = "mtusi-lab3"
|
||||
|
||||
|
||||
def docker(*args, check=True):
|
||||
proc = subprocess.run(["docker", *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
|
||||
if check and proc.returncode != 0:
|
||||
raise RuntimeError(args[0] + " failed: " + proc.stderr.decode("utf-8", "replace")[-400:])
|
||||
return proc
|
||||
|
||||
|
||||
def compose(*args, env=None, check=True):
|
||||
merged = os.environ.copy()
|
||||
if env:
|
||||
merged.update(env)
|
||||
proc = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT,
|
||||
env=merged,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
)
|
||||
if check and proc.returncode != 0:
|
||||
raise RuntimeError(proc.stderr.decode("utf-8", "replace")[-500:])
|
||||
return proc
|
||||
|
||||
|
||||
def api_ids():
|
||||
proc = docker(
|
||||
"ps",
|
||||
"-q",
|
||||
"--filter",
|
||||
"label=com.docker.compose.project=" + PROJECT,
|
||||
"--filter",
|
||||
"label=com.docker.compose.service=api",
|
||||
)
|
||||
return [line.strip() for line in proc.stdout.decode().splitlines() if line.strip()]
|
||||
|
||||
|
||||
def service_id(service):
|
||||
proc = docker(
|
||||
"ps",
|
||||
"-q",
|
||||
"--filter",
|
||||
"label=com.docker.compose.project=" + PROJECT,
|
||||
"--filter",
|
||||
"label=com.docker.compose.service=" + service,
|
||||
)
|
||||
ids = [line.strip() for line in proc.stdout.decode().splitlines() if line.strip()]
|
||||
if len(ids) != 1:
|
||||
raise RuntimeError("{} containers: {}".format(service, len(ids)))
|
||||
return ids[0]
|
||||
|
||||
|
||||
def apply(replicas, api_cpus, api_memory, pg_cpus, pool_max):
|
||||
compose(
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--force-recreate",
|
||||
"--scale",
|
||||
"api={}".format(replicas),
|
||||
"api",
|
||||
env={"POOL_MAX": str(pool_max)},
|
||||
)
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
if len(api_ids()) == replicas:
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError("scale api={} failed".format(replicas))
|
||||
for container_id in api_ids():
|
||||
docker(
|
||||
"update",
|
||||
"--cpus",
|
||||
str(api_cpus),
|
||||
"--memory",
|
||||
api_memory,
|
||||
"--memory-swap",
|
||||
api_memory,
|
||||
container_id,
|
||||
)
|
||||
docker("update", "--cpus", str(pg_cpus), service_id("postgres"))
|
||||
wait_ready(replicas)
|
||||
|
||||
|
||||
def wait_ready(replicas):
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
status, headers, _ = call("GET", "/health/ready", timeout=2)
|
||||
if status == 200 and headers.get("X-Instance-Id"):
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError("ready timeout")
|
||||
# Дождаться, что HAProxy видит все текущие реплики.
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
seen = set()
|
||||
for _ in range(max(20, replicas * 8)):
|
||||
status, headers, _ = call("GET", "/health/ready", timeout=2)
|
||||
if status == 200:
|
||||
seen.add(headers.get("X-Instance-Id"))
|
||||
if len(seen) >= replicas:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError("lb did not observe {} replicas".format(replicas))
|
||||
|
||||
|
||||
def stats_sample(ids):
|
||||
if not ids:
|
||||
return {}
|
||||
proc = docker("stats", "--no-stream", "--format", "{{.ID}} {{.CPUPerc}} {{.MemUsage}}", *ids)
|
||||
out = {}
|
||||
for line in proc.stdout.decode().splitlines():
|
||||
parts = line.split(None, 2)
|
||||
if len(parts) < 3:
|
||||
continue
|
||||
cpu = parts[1].replace("%", "")
|
||||
try:
|
||||
cpu_value = float(cpu)
|
||||
except ValueError:
|
||||
cpu_value = None
|
||||
out[parts[0][:12]] = {"cpu_percent": cpu_value, "mem": parts[2]}
|
||||
return out
|
||||
|
||||
|
||||
def prepare_actor():
|
||||
suffix = uuid.uuid4().hex[:10]
|
||||
password = "track1-password-1"
|
||||
status, _, user = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": "t1_" + suffix, "display_name": "Трек", "password": password},
|
||||
)
|
||||
if status != 201:
|
||||
raise RuntimeError("register {}".format(status))
|
||||
status, _, session = call("POST", "/api/v1/auth/sessions", headers=basic("t1_" + suffix, password))
|
||||
if status != 201:
|
||||
raise RuntimeError("login {}".format(status))
|
||||
return session["token"], user["id"]
|
||||
|
||||
|
||||
def new_chat(token, user_id):
|
||||
status, _, chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "Трек " + uuid.uuid4().hex[:6], "member_ids": [user_id]},
|
||||
headers=bearer(token),
|
||||
)
|
||||
if status != 201:
|
||||
raise RuntimeError("chat {}".format(status))
|
||||
return "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
|
||||
|
||||
def run_load(token, path, concurrency, seconds):
|
||||
auth = bearer(token)
|
||||
bucket = []
|
||||
barrier = threading.Barrier(concurrency)
|
||||
|
||||
def worker(worker_id):
|
||||
barrier.wait()
|
||||
deadline = time.monotonic() + seconds
|
||||
index = 0
|
||||
local = []
|
||||
while time.monotonic() < deadline:
|
||||
key = uuid.uuid4().hex
|
||||
started = time.monotonic()
|
||||
try:
|
||||
status, headers, _ = call(
|
||||
"POST",
|
||||
path,
|
||||
{"text": "t-{}-{}".format(worker_id, index)},
|
||||
headers={**auth, "Idempotency-Key": key},
|
||||
timeout=5,
|
||||
)
|
||||
local.append(
|
||||
{
|
||||
"ok": status == 201,
|
||||
"status": status,
|
||||
"seconds": time.monotonic() - started,
|
||||
"instance": headers.get("X-Instance-Id", ""),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
local.append({"ok": False, "status": 0, "seconds": time.monotonic() - started, "instance": ""})
|
||||
index += 1
|
||||
bucket.extend(local)
|
||||
|
||||
started = time.monotonic()
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(concurrency)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
elapsed = time.monotonic() - started
|
||||
ok = [item for item in bucket if item["ok"]]
|
||||
lat = sorted(item["seconds"] for item in ok)
|
||||
|
||||
def pct(p):
|
||||
if not lat:
|
||||
return None
|
||||
index = min(len(lat) - 1, max(0, int(round(p * (len(lat) - 1)))))
|
||||
return round(lat[index] * 1000, 1)
|
||||
|
||||
instances = {}
|
||||
for item in ok:
|
||||
instances[item["instance"]] = instances.get(item["instance"], 0) + 1
|
||||
codes = {}
|
||||
for item in bucket:
|
||||
codes[str(item["status"])] = codes.get(str(item["status"]), 0) + 1
|
||||
return {
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"ok": len(ok),
|
||||
"errors": len(bucket) - len(ok),
|
||||
"error_ratio": round((len(bucket) - len(ok)) / len(bucket), 4) if bucket else None,
|
||||
"successful_rps": round(len(ok) / elapsed, 3) if elapsed else None,
|
||||
"p50_ms": pct(0.50),
|
||||
"p95_ms": pct(0.95),
|
||||
"instances": instances,
|
||||
"status_codes": codes,
|
||||
}
|
||||
|
||||
|
||||
def sample_during(ids, seconds):
|
||||
samples = []
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
samples.append(stats_sample(ids))
|
||||
time.sleep(2)
|
||||
return samples
|
||||
|
||||
|
||||
def average_cpu(samples, prefix_ids):
|
||||
wanted = {item[:12] for item in prefix_ids}
|
||||
values = []
|
||||
for sample in samples:
|
||||
for key, payload in sample.items():
|
||||
if key in wanted and payload["cpu_percent"] is not None:
|
||||
values.append(payload["cpu_percent"])
|
||||
if not values:
|
||||
return None
|
||||
return round(statistics.fmean(values), 2)
|
||||
|
||||
|
||||
def scenario_row(name, spec, repeat, result, api_cpu, pg_cpu):
|
||||
return {
|
||||
"name": name,
|
||||
"repeat": repeat,
|
||||
"api_replicas": spec["replicas"],
|
||||
"api_cpus_each": spec["api_cpus"],
|
||||
"api_memory_each": spec["api_memory"],
|
||||
"postgres_cpus": spec["pg_cpus"],
|
||||
"pool_max": spec["pool"],
|
||||
"concurrency": spec["concurrency"],
|
||||
"api_cpu_percent_avg": api_cpu,
|
||||
"postgres_cpu_percent_avg": pg_cpu,
|
||||
**result,
|
||||
}
|
||||
|
||||
|
||||
def measure(name, spec, token, user_id):
|
||||
apply(spec["replicas"], spec["api_cpus"], spec["api_memory"], spec["pg_cpus"], spec["pool"])
|
||||
rows = []
|
||||
for repeat in (1, 2):
|
||||
path = new_chat(token, user_id)
|
||||
warmup = run_load(token, path, spec["concurrency"], 4)
|
||||
ids = api_ids() + [service_id("postgres"), service_id("lb")]
|
||||
holder = {}
|
||||
|
||||
def collect():
|
||||
holder["samples"] = sample_during(ids, 12)
|
||||
|
||||
thread = threading.Thread(target=collect)
|
||||
thread.start()
|
||||
result = run_load(token, path, spec["concurrency"], 12)
|
||||
thread.join()
|
||||
samples = holder.get("samples", [])
|
||||
row = scenario_row(
|
||||
name,
|
||||
spec,
|
||||
repeat,
|
||||
result,
|
||||
average_cpu(samples, api_ids()),
|
||||
average_cpu(samples, [service_id("postgres")]),
|
||||
)
|
||||
row["warmup_rps"] = warmup["successful_rps"]
|
||||
rows.append(row)
|
||||
print(json.dumps({k: row[k] for k in ("name", "repeat", "successful_rps", "error_ratio", "p95_ms", "postgres_cpu_percent_avg")}, ensure_ascii=False))
|
||||
return rows
|
||||
|
||||
|
||||
def svg(points, title, xlabel, path):
|
||||
width, height, left, bottom = 760, 420, 70, 50
|
||||
xs = [item[0] for item in points]
|
||||
ys = [item[1] for item in points]
|
||||
max_y = max(ys) if ys else 1
|
||||
max_y = max_y * 1.15 if max_y else 1
|
||||
|
||||
def px(index):
|
||||
return left + (width - left - 30) * (index / max(1, len(points) - 1))
|
||||
|
||||
def py(value):
|
||||
return 30 + (height - bottom - 30) * (1 - value / max_y)
|
||||
|
||||
polyline = " ".join("{:.1f},{:.1f}".format(px(i), py(y)) for i, y in enumerate(ys))
|
||||
labels = []
|
||||
for i, (x, y) in enumerate(points):
|
||||
labels.append(
|
||||
'<text x="{:.1f}" y="{}" text-anchor="middle" font-size="13">{}</text>'.format(px(i), height - 18, x)
|
||||
)
|
||||
labels.append(
|
||||
'<text x="{:.1f}" y="{:.1f}" text-anchor="middle" font-size="12">{:.1f}</text>'.format(px(i), py(y) - 8, y)
|
||||
)
|
||||
body = """<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}">
|
||||
<rect width="100%" height="100%" fill="white"/>
|
||||
<text x="{w2}" y="22" text-anchor="middle" font-size="16">{title}</text>
|
||||
<line x1="{left}" y1="30" x2="{left}" y2="{axis}" stroke="#222"/>
|
||||
<line x1="{left}" y1="{axis}" x2="{right}" y2="{axis}" stroke="#222"/>
|
||||
<polyline fill="none" stroke="#1f4e79" stroke-width="2" points="{poly}"/>
|
||||
{dots}
|
||||
{labels}
|
||||
<text x="{w2}" y="{hbot}" text-anchor="middle" font-size="13">{xlabel}</text>
|
||||
<text x="18" y="220" font-size="13" transform="rotate(-90 18 220)">успешные RPS</text>
|
||||
</svg>
|
||||
""".format(
|
||||
w=width,
|
||||
h=height,
|
||||
w2=width // 2,
|
||||
title=title,
|
||||
left=left,
|
||||
axis=height - bottom,
|
||||
right=width - 20,
|
||||
poly=polyline,
|
||||
dots="".join(
|
||||
'<circle cx="{:.1f}" cy="{:.1f}" r="4" fill="#1f4e79"/>'.format(px(i), py(y)) for i, y in enumerate(ys)
|
||||
),
|
||||
labels="\n".join(labels),
|
||||
hbot=height - 2,
|
||||
xlabel=xlabel,
|
||||
)
|
||||
path.write_text(body, encoding="utf-8")
|
||||
|
||||
|
||||
def mean_rps(rows, name):
|
||||
values = [row["successful_rps"] for row in rows if row["name"] == name and row["successful_rps"] is not None]
|
||||
if not values:
|
||||
return None
|
||||
return round(statistics.fmean(values), 3)
|
||||
|
||||
|
||||
def restore():
|
||||
compose(
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--force-recreate",
|
||||
"--scale",
|
||||
"api=2",
|
||||
"api",
|
||||
env={"POOL_MAX": "10"},
|
||||
)
|
||||
for container_id in api_ids():
|
||||
docker("update", "--cpus", "0.50", "--memory", "256m", "--memory-swap", "256m", container_id)
|
||||
docker("update", "--cpus", "1.00", service_id("postgres"))
|
||||
wait_ready(2)
|
||||
|
||||
|
||||
def main():
|
||||
fixed = {"api_cpus": None, "api_memory": None, "pg_cpus": 1.0, "pool": 10, "concurrency": 8}
|
||||
# Суммарно 1.0 CPU и 1024 MiB на все API.
|
||||
budgets = {
|
||||
"fixed-1": {**fixed, "replicas": 1, "api_cpus": 1.0, "api_memory": "1024m"},
|
||||
"fixed-2": {**fixed, "replicas": 2, "api_cpus": 0.5, "api_memory": "512m"},
|
||||
"fixed-4": {**fixed, "replicas": 4, "api_cpus": 0.25, "api_memory": "256m"},
|
||||
}
|
||||
growth = {
|
||||
"pg-0.30": {"replicas": 2, "api_cpus": 0.5, "api_memory": "512m", "pg_cpus": 0.30, "pool": 10, "concurrency": 8},
|
||||
"pg-0.60": {"replicas": 2, "api_cpus": 0.5, "api_memory": "512m", "pg_cpus": 0.60, "pool": 10, "concurrency": 8},
|
||||
"pg-1.20": {"replicas": 2, "api_cpus": 0.5, "api_memory": "512m", "pg_cpus": 1.20, "pool": 10, "concurrency": 8},
|
||||
}
|
||||
pools = {
|
||||
"pool-2": {"replicas": 2, "api_cpus": 0.5, "api_memory": "512m", "pg_cpus": 1.0, "pool": 2, "concurrency": 16},
|
||||
"pool-10": {"replicas": 2, "api_cpus": 0.5, "api_memory": "512m", "pg_cpus": 1.0, "pool": 10, "concurrency": 16},
|
||||
}
|
||||
token, user_id = prepare_actor()
|
||||
# Прогрев планировщика и кэша Postgres вне таблицы результатов.
|
||||
apply(2, 0.5, "512m", 1.0, 10)
|
||||
run_load(token, new_chat(token, user_id), 4, 8)
|
||||
rows = []
|
||||
try:
|
||||
for name, spec in {**budgets, **growth, **pools}.items():
|
||||
rows.extend(measure(name, spec, token, user_id))
|
||||
finally:
|
||||
EVIDENCE.mkdir(exist_ok=True)
|
||||
(EVIDENCE / "track1_runs.json").write_text(json.dumps(rows, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
header = [
|
||||
"name",
|
||||
"repeat",
|
||||
"api_replicas",
|
||||
"api_cpus_each",
|
||||
"postgres_cpus",
|
||||
"pool_max",
|
||||
"concurrency",
|
||||
"successful_rps",
|
||||
"error_ratio",
|
||||
"p50_ms",
|
||||
"p95_ms",
|
||||
"api_cpu_percent_avg",
|
||||
"postgres_cpu_percent_avg",
|
||||
]
|
||||
lines = [",".join(header)]
|
||||
for row in rows:
|
||||
lines.append(",".join("" if row.get(key) is None else str(row.get(key)) for key in header))
|
||||
(EVIDENCE / "track1_runs.csv").write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
restore()
|
||||
summary = {
|
||||
"method": "closed-loop POST messages, unique Idempotency-Key, warmup 4s discarded, measure 12s, 2 repeats, fresh chat per repeat",
|
||||
"fixed_total_api_cpu": 1.0,
|
||||
"fixed_total_api_memory": "1024m",
|
||||
"mean_successful_rps": {name: mean_rps(rows, name) for name in list(budgets) + list(growth) + list(pools)},
|
||||
}
|
||||
(EVIDENCE / "track1_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
def points(names):
|
||||
rows = []
|
||||
for name in names:
|
||||
value = summary["mean_successful_rps"].get(name)
|
||||
if value is None:
|
||||
continue
|
||||
rows.append((name.split("-", 1)[1], value))
|
||||
return rows
|
||||
|
||||
if points(budgets):
|
||||
svg(points(budgets), "Фиксированный бюджет API: 1 / 2 / 4 реплики", "число реплик при суммарно 1.0 CPU и 1024 MiB", EVIDENCE / "track1_replicas.svg")
|
||||
if points(growth):
|
||||
svg(points(growth), "Рост CPU Postgres при 2 API", "лимит CPU Postgres", EVIDENCE / "track1_postgres.svg")
|
||||
if points(pools):
|
||||
svg(points(pools), "Размер пула соединений при concurrency 16", "POOL_MAX на реплику", EVIDENCE / "track1_pool.svg")
|
||||
print(json.dumps(summary["mean_successful_rps"], ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Дополнительная серия трека 1: много CPU у API, узкий Postgres, затем больше CPU у Postgres."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import run_track1 as track
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence" / "track1_db.json"
|
||||
|
||||
SPECS = {
|
||||
"api2-pg0.35": {
|
||||
"replicas": 2,
|
||||
"api_cpus": 1.0,
|
||||
"api_memory": "512m",
|
||||
"pg_cpus": 0.35,
|
||||
"pool": 10,
|
||||
"concurrency": 16,
|
||||
},
|
||||
"api4-pg0.35": {
|
||||
"replicas": 4,
|
||||
"api_cpus": 1.0,
|
||||
"api_memory": "512m",
|
||||
"pg_cpus": 0.35,
|
||||
"pool": 10,
|
||||
"concurrency": 16,
|
||||
},
|
||||
"api2-pg1.50": {
|
||||
"replicas": 2,
|
||||
"api_cpus": 1.0,
|
||||
"api_memory": "512m",
|
||||
"pg_cpus": 1.5,
|
||||
"pool": 10,
|
||||
"concurrency": 16,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
token, user_id = track.prepare_actor()
|
||||
rows = []
|
||||
try:
|
||||
for name, spec in SPECS.items():
|
||||
rows.extend(track.measure(name, spec, token, user_id))
|
||||
finally:
|
||||
OUT.write_text(json.dumps(rows, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
track.restore()
|
||||
summary = {name: track.mean_rps(rows, name) for name in SPECS}
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,41 @@
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, check=True, input_bytes=None, timeout=180):
|
||||
proc = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT,
|
||||
input=input_bytes,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
if check and proc.returncode != 0:
|
||||
err = proc.stderr.decode("utf-8", "replace")[-800:]
|
||||
raise RuntimeError(err or "docker compose failed")
|
||||
return proc
|
||||
|
||||
|
||||
def psql(sql, timeout=180):
|
||||
proc = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-q",
|
||||
"-t",
|
||||
"-A",
|
||||
input_bytes=sql.encode("utf-8"),
|
||||
timeout=timeout,
|
||||
)
|
||||
return proc.stdout.decode("utf-8").strip()
|
||||
Reference in New Issue
Block a user