commit 176b9de2de4c36f677843eaafea8edd69973dead Author: kaktuz20000 <149298757+kaktuz20000@users.noreply.github.com> Date: Wed Oct 21 09:44:11 2026 +0300 выполнение лабы на 5 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..bc16e55 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,20 @@ +.git +.github +.env +.env.* +!.env.example +secrets +certs +volumes +data +backups +*.key +*.pem +*.p12 +*.pfx +*.jks +.venv +__pycache__ +node_modules +evidence +.DS_Store diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..7cecca5 --- /dev/null +++ b/.env.example @@ -0,0 +1,7 @@ +# Copy to .env for your LOCAL synthetic test environment; never commit .env. +APP_PORT=8080 +SESSION_TTL_SECONDS=3600 +IDEMPOTENCY_TTL_SECONDS=86400 +# Per-replica limits; adjust for the fixed-budget track 1 experiment. +API_CPU_LIMIT=1.0 +API_MEMORY_LIMIT=512M diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..e6e63eb --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,18 @@ +## Лабораторная 3 + +Автор / группа: TODO +Целевая оценка (3/4/5): TODO +Трек 5, если заявлен: TODO + +Что реализовано и что перенесено: TODO +Команды запуска из чистого clone: TODO +Результаты проверок и ссылка на REPORT.md: TODO +Ограничения / известные ошибки: TODO +Источники и использование ИИ: TODO + +- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. +- [ ] Контракт и публичные тесты не ослаблены. +- [ ] make check и make test выполнены; приложен реальный вывод. +- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. +- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. +- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. diff --git a/.github/workflows/application.yml b/.github/workflows/application.yml new file mode 100644 index 0000000..2c47301 --- /dev/null +++ b/.github/workflows/application.yml @@ -0,0 +1,34 @@ +name: Application checks +on: [push, pull_request] +permissions: + contents: read +jobs: + compose-tests: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: python -m pip install -r requirements-dev.txt + - name: Create local test credentials + run: | + cp .env.example .env + ./scripts/bootstrap-secrets.sh + - name: Validate and start the application + run: | + make check validate PYTHON=python + docker compose --env-file .env config --quiet + docker compose --env-file .env up -d --build --scale api=2 --wait --wait-timeout 180 + - name: Run API and concurrency tests + run: | + make test + make test-idempotency + - name: Verify persistence and failover + run: | + make test-persistence ACTION_SCRIPT=scripts/restart.sh + make test-failover ACTION_SCRIPT=scripts/stop-one.sh + - name: Stop test stack + if: always() + run: docker compose --env-file .env down -v diff --git a/.github/workflows/contracts.yml b/.github/workflows/contracts.yml new file mode 100644 index 0000000..11cf289 --- /dev/null +++ b/.github/workflows/contracts.yml @@ -0,0 +1,16 @@ +name: Skeleton contracts +on: [push, pull_request] +permissions: + contents: read +jobs: + contracts: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -r requirements-dev.txt + - run: make check validate PYTHON=python +# This job validates the skeleton, not a student solution. +# Add build, readiness and make test in a separate application job. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b5a7189 --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +# Local/private state +.env +.env.* +!.env.example +secrets/ +certs/private/ +*.key +*.p12 +*.pfx +*.jks +*.pem +*.tfstate* +volumes/ +data/ +backups/ +# Runtime/build artifacts +.venv/ +__pycache__/ +*.py[cod] +node_modules/ +dist/ +build/ +target/ +bin/ +obj/ +coverage/ +*.log +.DS_Store +.idea/ +.vscode/ +# Keep small, sanitized evidence summaries in evidence/ under version control. +# Inspect git diff --cached: ignore rules are not a secret scanner. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..ee5533d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# Работа через fork и pull request + +1. После публикации преподавателем сделайте fork репозитория **текущей** лабораторной в своём аккаунте и clone своего fork. URL преподаватель выдаёт отдельно. +2. Создайте ветку `solution/-` от исходной ветки skeleton. Ветка преподавателя и файлы контракта остаются основой проверки. +3. Для lab2–7 перенесите из своей предыдущей лабы только исходники, миграции, собственные тесты, Dockerfile и нужные конфигурации. Не копируйте `.git`, `.env`, credentials, volumes, `README.md`, `COURSE.md`, публичные `tests/` и `contracts/` поверх новой версии. Сначала сравните изменения API в `COURSE.md`. +4. Реализуйте задание, добавьте свою инструкцию запуска и заполните `REPORT.md`. Публичные проверки дополняйте отдельными тестами, не ослабляйте assertions. +5. Выполните `make check`, запустите свой стенд, затем `make test`. Выполните сценарии отказов текущей лабы. Их запуск всегда явный: scaffold сам не останавливает контейнеры. +6. Commit и push делайте в свой fork. Откройте PR в исходный репозиторий преподавателя, заголовок: `ЛР N — Группа — Фамилия — на 3/4/5`. Выберите правильную базовую ветку и заполните шаблон. +7. После замечаний обновляйте тот же PR. Чужие решения не переносите без указания источника и согласованных правил курса. + +Платформа может называть PR «merge request» — процесс тот же. `.github/` содержит необязательные удобства для GitHub; проверки локально от платформы не зависят. Инициализация и публикация исходных Git-репозиториев выполняются преподавателем отдельно. + +## Правила изменения skeleton + +Не удаляйте обязательные endpoint, поля, рубрику и публичные проверки. Изменение контракта согласуйте отдельным комментарием/PR; обход тестов не является решением. Код приложения размещайте в `src/` либо в принятой для языка структуре. Собственные тесты — `student-tests/` или штатный каталог фреймворка. Ссылки на результаты проверки и команды запуска должны переживать clone на другой машине. + +## CI + +Готовый GitHub workflow проверяет целостность контракта и синтаксис Python-проверок. Он **не запускает отсутствующее приложение** и **не подтверждает оценку**. Студент добавляет сборку своего приложения, запуск/готовность стенда и `make test` в отдельный job. Не используйте `pull_request_target` для запуска кода из fork, не выдавайте CI секреты или доступ к общему Docker-host. diff --git a/COURSE.md b/COURSE.md new file mode 100644 index 0000000..b02172b --- /dev/null +++ b/COURSE.md @@ -0,0 +1,53 @@ +# Сквозной проект: мессенджер под нагрузкой + +Семь самостоятельных репозиториев содержат задания и проверяемые контракты одной системы. Вы переносите собственную реализацию между лабораторными. Язык, фреймворк и библиотеки выбираете сами. Web UI, WebSocket, редактирование/удаление сообщений, публичный поиск пользователей и Kubernetes не входят в обязательный минимум: достаточно REST API. + +| Лаба | Новая инженерная задача | Что появляется в системе | +| --- | --- | --- | +| 1 | Контракт, процессы и контейнер | In-memory API, Dockerfile, HTTP smoke | +| 2 | Сохранность и идентификация | PostgreSQL, Basic → сессия; Redis/Valkey на 4 | +| 3 | Горизонтальное масштабирование | Балансировщик, ≥2 API-реплики, общие сессии, идемпотентность | +| 4 | Бинарные данные | Приватное S3-совместимое хранилище и вложения | +| 5 | Фоновая работа | Брокер, worker, состояния вложений и преобразование изображений | +| 6 | Диагностика | OTel Collector, хранилища сигналов, Grafana | +| 7 | Защита и эксплуатация | Argon2id, TLS/mTLS, OpenBao, минимальные привилегии | + +## Как оценивать + +Оценки накопительные **внутри лабораторной**: 4 = весь уровень 3 + весь уровень 4; 5 = весь уровень 4 + **один** полностью выполненный трек 5 на выбор. Несколько недоделанных треков не заменяют один завершённый. Условие «весь уровень» включает реализацию, проверку и объяснение на защите. Красивые схемы и дополнительные технологии не компенсируют неработающий обязательный сценарий. + +Для начала следующей лабы достаточно обязательного минимума предыдущей. Сохраняются предыдущие обязательные возможности, с явно описанными переходами API ниже. Не требуется сначала получить 5 за все ранние лабы. Можно исправлять свою базу по ходу курса; такие исправления выделяйте в PR. Реализация на 3 работоспособна, но не претендует на промышленную готовность. Даже 5 в lab7 — учебная доказанная защита в заявленной модели угроз, а не сертификат полной безопасности. + +На 3 студент самостоятельно собирает рабочую систему. На 4 показывает практики, ожидаемые от стажёра/джуна в команде: воспроизводимость, диагностику, обработку ошибок и проверки отказов. На 5 формулирует гипотезу, ставит эксперимент, приводит измерения и обсуждает границы решения — это предмет конкретной похвалы магистранту. + +## Контракт и совместимость + +`contracts/openapi.json` — OpenAPI 3.1.0, `contracts/README.md` — нормативная семантика. Контракт каждого репозитория самодостаточен; соседние папки на машине преподавателя не нужны. `tests/` — публичные проверки, а не эталонное решение. Контракт, рубрика и публичные тесты имеют приоритет над случайным поведением библиотек. При противоречии создайте вопрос преподавателю; не подгоняйте тест под приложение. + +Три объявленных изменения обязательного API: + +1. **1 → 2:** регистрация требует `password`; `X-User-Id` заменяется Bearer. Basic используется только при создании сессии. +2. **2 → 3:** `Idempotency-Key` обязателен для отправки сообщения; ответы API содержат `X-Instance-Id`. +3. **4 → 5:** загрузка вложения возвращает `202` вместо `201`, состояние становится асинхронным. Клиент опрашивает метаданные. Старое текстовое сообщение остаётся валидным: `attachment_ids` по умолчанию `[]`. + +У lab7 меняется транспорт на HTTPS, бизнес-эндпоинты остаются прежними. Внутреннее mTLS не заменяет пользовательскую сессию. Новые возможности на 4/5 добавляйте обратно совместимо, в отдельном `contracts/extensions.openapi.json` или документе; обязательный контракт сохраняйте. + +## Общая предметная модель + +Пользователь (`username`, `display_name`) состоит в чатах. Список участников задаётся при создании чата и в обязательном API не изменяется. В чате отправляются сообщения, с lab4 — со ссылками на вложения этого чата. Сервер назначает UUID и время. Порядок истории — `(created_at, id)` по возрастанию. Для защиты достаточно показать взаимодействие нескольких API-клиентов; фронтенд не требуется. + +С lab2 данные PostgreSQL — источник истины. Сессии могут храниться в PostgreSQL или Redis/Valkey, если выполняют контракт срока жизни и перезапуска. Файлы с lab4 живут в S3, метаданные — в PostgreSQL. Redis и Valkey — альтернативы: оба одновременно не нужны. Аналогично выбирается одно S3-хранилище, один брокер и один основной путь оркестрации. + +## Воспроизводимость и честные измерения + +- Укажите версии runtime и контейнерных образов, аппаратную конфигурацию, CPU/RAM-лимиты, команду запуска и время прогрева. Для образов используйте явный тег версии или digest, не `latest`. +- Все тестовые пользователи и изображения синтетические. `make test` создаёт данные: запускайте его на учебном стенде. Не публикуйте пароли, токены, приватные ключи, персональные данные или подписанные URL. +- Минимальный отчёт о нагрузке: длительность, конкуренция/интенсивность, успешные RPS, доля ошибок, p50/p95/p99, CPU/RAM, размер набора данных. Универсального проходного RPS для разных ноутбуков нет. +- Сравнивайте одинаковые запросы при одинаковых ресурсах. Успешный `/health/live` не доказывает сохранность сообщений, а HTTP `202` — окончание обработки. +- Один Docker-host не обеспечивает отказоустойчивость к потере этого host. Несколько API-процессов не делают единственную БД или LB высокодоступными. Отдельно называйте, какие отказы выдерживает эксперимент. + +## Что сдавать + +Исходники, Dockerfile, нужные манифесты и конфигурации, миграции, собственные тесты, заполненный `REPORT.md`, сведения об использовании внешнего кода и ИИ. Уметь объяснить и изменить своё решение на защите обязательно. Приложите команды и текстовые результаты; скриншоты — дополнение, а не единственное доказательство. + +PR должен собираться из чистого clone по инструкции автора. Секреты создаются отдельно; тестовые fixtures и открытые конфигурации хранятся в репозитории. Перенос кода между лабами описан в [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..83823c8 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM python:3.12.7-slim + +WORKDIR /app + +ENV APP_HOST=0.0.0.0 \ + APP_PORT=8080 \ + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +RUN groupadd --system app && useradd --system --gid app --create-home --home-dir /home/app app + +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt + +COPY . /app +RUN chown -R app:app /app + +USER app + +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/live', timeout=2).read()" || exit 1 + +CMD ["python3", "src/server.py"] diff --git a/Dockerfile.example b/Dockerfile.example new file mode 100644 index 0000000..e333a12 --- /dev/null +++ b/Dockerfile.example @@ -0,0 +1,8 @@ +# Teaching outline, not a runnable Dockerfile. Implement your own Dockerfile. +# 1. Choose a runtime/toolchain version and pin the base image tag/digest. +# 2. Copy dependency manifests first; install from the language lockfile. +# 3. Copy source and build. For compiled languages use a separate runtime stage. +# 4. Run the HTTP process as PID 1; listen on 0.0.0.0:8080. +# 5. Add non-root, signals and healthcheck according to the current rubric. +# 6. Pass runtime config/secrets at startup, never COPY .env or secret files. +# This file deliberately has no FROM/CMD: selecting/implementing them is the task. diff --git a/MAINTAINERS.md b/MAINTAINERS.md new file mode 100644 index 0000000..3015743 --- /dev/null +++ b/MAINTAINERS.md @@ -0,0 +1,38 @@ +# Памятка преподавателю — лабораторная 3 + +## Что подготовлено + +Язык реализации не задан. README содержит накопительные уровни 3/4/5, сценарий защиты и вопросы. В каждой лабе собственная полная версия OpenAPI, поэтому fork не зависит от соседних каталогов. Публичный HTTP smoke не содержит реализации сервера; Dockerfile.example и compose.example.yaml (если есть) — задания/ориентиры, не готовый deployment. + +## Перед публикацией + +1. Выберите GitHub/GitLab и организацию, опубликуйте каждый каталог как отдельный template/skeleton repository, сообщите студентам URL и правила именования PR/MR. Эти материалы не публикуют репозитории автоматически. +2. Задайте default branch, защиту исходных материалов и правила приёма. `.github/` уже содержит шаблон PR и CI контракта; в GitLab перенесите эквивалентные настройки, локальные Makefile-команды одинаковы. +3. Сообщите, индивидуальная работа или командная, сроки, правила использования стороннего кода/ИИ и ресурсы демонстрационного стенда. Эти организационные решения намеренно не выдуманы в задании. +4. Уточните ограничения площадки (например доступна ли виртуализация/несколько узлов). Для 5 предусмотрено по два трека: один можно выполнить без настоящего multi-node cloud. Универсальный проходной RPS не установлен. + +## Что проверять + +| Проверка | Что подтверждает | Чего не подтверждает | +| --- | --- | --- | +| make check | Структура файлов, JSON, локальные refs, синтаксис Python | Реализация/запуск API | +| make validate | Полная OpenAPI 3.1, JSON Schema и примеры | Поведение сервера | +| make test | Один сквозной контрактный сценарий текущей лабы | Все ошибки, persistence, HA, security | +| test-persistence (lab2+) | Данные/прежний токен после вызова restart hook | Реальный перезапуск, если hook — no-op | +| test-failover (lab3+) | Смена обслуживающей реплики, сохранность, retry без дубля | Несколько физических узлов, HA DB/LB | +| test-security (lab7) | Доверенный HTTPS и отказ недоверенного CA | Внутреннее mTLS/identity/ACL/OpenBao | +| Защита и тесты студента | Реальность инфраструктуры и критерии выбранного уровня | Неограниченная промышленная безопасность | + +Проверяйте реальные контейнеры/логи процессов и данные до/после отказа: одного X-Instance-Id недостаточно. Для 4 требуются все пункты 3+4, для 5 — все пункты 3+4 и один **завершённый** трек 5. Сравнивайте подтверждённые результаты со сформулированными критериями, а не количество установленных сервисов. + +## Приём PR + +Проверка запускается на изолированном учебном окружении с синтетическими secrets, не на общей production БД. Студенческие Dockerfile/hooks/CI — выполняемый код: обычный fork workflow без секретов и без доступа к общему Docker socket. Не запускайте PR через pull_request_target с привилегиями преподавателя. + +Исходные README/контракт/публичные tests сохраняются, реализация переносится студентом между лабами через собственные исходники и миграции. Исправление общей спецификации публикуйте отдельным изменением, объясняя влияние на все затронутые лабораторные. + +## Проверка этой версии skeleton + +На 2026-09-10 выполнены структурные проверки и полная валидация всех семи OpenAPI/JSON Schema, проверка локальных Markdown-ссылок/YAML и декодирование PNG fixture. HTTP-клиенты проверены на временном изолированном тестовом стенде: позитивный smoke 1–7, отрицательные варианты неправильного sender, pagination, ACL, logout, bytes и пустого API; также пути persistence/failover/load и внешнего TLS. + +Временный стенд не включён в студенческие каталоги и не является эталонным решением. Реальное приложение, Compose, PostgreSQL/S3/broker и mTLS/OpenBao в skeleton отсутствуют: их работоспособность не заявляется. Docker CLI в среде подготовки не был доступен. Это проверка материалов и тестовых драйверов, не приёмка будущих решений студентов. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..505a6c1 --- /dev/null +++ b/Makefile @@ -0,0 +1,36 @@ +PYTHON ?= python3 +BASE_URL ?= http://127.0.0.1:8080 +CA_FILE ?= +ACTION_SCRIPT ?= +TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) + +.PHONY: help check validate test load test-persistence test-failover test-idempotency track1 + +help: + @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + +check: + $(PYTHON) scripts/check_contract.py + +validate: + $(PYTHON) scripts/validate_openapi.py + +test: + $(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +load: + $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-persistence: + @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) + $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-failover: + @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) + $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-idempotency: + $(PYTHON) student-tests/test_idempotency_race.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +track1: + $(PYTHON) student-tests/track1_benchmark.py diff --git a/README.md b/README.md new file mode 100644 index 0000000..29627f7 --- /dev/null +++ b/README.md @@ -0,0 +1,132 @@ +# Лабораторная 3. Балансировка и отказ API-реплики + +Запустить несколько взаимозаменяемых экземпляров API за единой точкой входа и сохранить корректность при остановке одного из них. + +В репозитории реализован стенд лабораторной: контракт и публичные проверки дополнены приложением, Docker-инфраструктурой, сценариями отказов и исследовательским экспериментом. Критерии задания и выбранные решения описаны ниже и в [отчёте](REPORT.md). + +[Карта курса](COURSE.md) · [Процесс fork/PR](CONTRIBUTING.md) · [OpenAPI](contracts/openapi.json) · [Семантика API](contracts/README.md) · [Проверки](tests/README.md) · [Отчёт](REPORT.md) · [Примеры JSON](contracts/examples.json) · [Памятка преподавателю](MAINTAINERS.md) + +## Откуда начинаем + +Нужен минимум lab2: PostgreSQL, общие действующие сессии, миграции. Добавляются X-Instance-Id и обязательный Idempotency-Key при отправке сообщения. + +**Архитектура:** Клиент → LB → API × 2+ → общие PostgreSQL и хранилище сессий. Compose или Swarm — на выбор. + +## Реализация этого решения + +Используется Docker Compose: HAProxy с активной проверкой `GET /health/ready` и DNS-resolver Docker, два и более одинаковых API-контейнера, одна PostgreSQL. Публичный порт публикуется только у HAProxy на loopback. Сессии и идемпотентность находятся в PostgreSQL; локального состояния сессий у реплик нет. Миграции выполняет отдельный одноразовый сервис до старта API. + +```sh +cp .env.example .env +./scripts/bootstrap-secrets.sh +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build --scale api=2 --wait --wait-timeout 120 +make check +make test +make test-idempotency +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +# Полная матрица трека 1: 1/2/4 реплики при фиксированном бюджете и 1/2/4/8 при росте. +make track1 +``` + +Локальные секреты хранятся в игнорируемой папке `secrets/`; скрипт их не выводит. API использует имя контейнера как стабильный на время жизни процесса `X-Instance-Id`. Для намеренного удаления учебной БД после проверки выполните `docker compose --env-file .env down -v`; эта команда необратимо удаляет volume и не используется сценариями restart/failover. + +Перед завершением работы восстановите остановленную реплику командой `docker compose --env-file .env up -d --scale api=2 --wait`. Подробные методика, ограничения и доказательства указаны в `REPORT.md`. + +Для проверки поочерёдной замены экземпляров под нагрузкой запустите в одном терминале `python3 tests/load.py --duration 30 --concurrency 8 --output evidence/rolling-restart-load.json`, а пока она работает — в другом `scripts/rolling-restart.sh`. Скрипт перезапускает по одному контейнеру, не останавливая вторую реплику, и ждёт readiness обоих экземпляров. + +Перед `make track1` запустите Compose-стенд и не допускайте параллельных записей в БД: скрипт останавливает API, создаёт временный custom-format snapshot PostgreSQL, а затем восстанавливает его перед каждым прогревом и каждым измерением. В `finally` скрипт возвращает исходную БД и 2 API-реплики, поэтому все benchmark-записи удаляются, а данные, бывшие в volume до эксперимента, сохраняются. Все семь случаев (1/2/4 фиксированный бюджет; 1/2/4/8 рост) используют один и тот же snapshot. + +CI workflow `.github/workflows/application.yml` отдельно проверяет сборку Compose-стенда, публичный smoke, конкурентную идемпотентность, persistence и отказ одной реплики. CI использует только временные синтетические credentials и удаляет собственный тестовый volume после завершения job. + +## Что сделать + +1. Выберите Compose + Nginx/HAProxy/Traefik либо Docker Swarm. Для выбранного варианта дайте одну последовательность запуска. +2. Уберите локальные сессии/другие данные, от которых зависит корректность, из API. Миграции выполняйте отдельно и согласованно, а не гонкой всех реплик. +3. Настройте балансировщик, проверки готовности, DNS/обновление backend-адресов и graceful shutdown. Не закрепляйте клиента sticky session как способ исправить раздельное состояние. +4. Реализуйте общую идемпотентность отправки сообщения. Проверьте одинаковый ключ одновременно через разные реплики. +5. Подготовьте явный action script, останавливающий одну выбранную API-реплику, и продемонстрируйте чтение/запись во время отказа. + +## Оценка «3»: работающий минимум + +- Весь стенд описан в compose.yaml или stack.yaml, запускается документированной командой. Не менее двух API-реплик, одна публичная точка входа, одна общая БД и общее хранилище сессий. +- Разные запросы одного пользователя обслуживаются разными репликами без повторного входа. Это видно по X-Instance-Id. Доступ через LB — основной проверяемый маршрут. +- Можно остановить любую одну API-реплику при работающей другой: не позднее 10 секунд продолжаются новые чтения/записи, подтверждённые сообщения доступны. Краткие ошибки/оборванные запросы во время обнаружения отказа измеряются и допустимы. +- Повтор POST сообщения с тем же Idempotency-Key не создаёт дубль, включая конкурентный повтор и переключение реплики. Неподтверждённую запись клиент может безопасно повторить с тем же ключом. +- make test, persistence и failover-сценарий проходят; для failover проверяется наличие ≥2 наблюдаемых реплик. Для Swarm сборка образа и его доступность узлам описаны отдельно. + +## Оценка «4»: уровень стажёра/джуна + +Весь уровень 3 **и все** пункты ниже: + +- Health/readiness, timeouts и прекращение приёма при SIGTERM настроены согласованно; LB исключает недоступный backend. Укажите период проверок и максимальное время обнаружения отказа. +- Последовательно остановите каждую API-реплику (восстанавливая предыдущую); соберите RPS, ошибки и время восстановления. Общая идемпотентность проверяется параллельными запросами с одним ключом. +- Контейнеры имеют CPU/RAM-лимиты, API не публикуют порты наружу в обход LB; секреты и хранилища общие только там, где нужно. Нет container_name, мешающего масштабированию одного Compose-service. +- Rolling update или эквивалентная поочерёдная замена проверена под нагрузкой. Миграции запускаются однократно и совместимы с работающей версией либо ограничение честно описано. + +## Оценка «5»: исследование и доказанный результат + +Весь уровень 4 **и один законченный трек на выбор**. Приведите гипотезу, повторяемую методику, результаты и ограничения. + +**Трек 1. Цена масштабирования.** При фиксированном суммарном CPU/RAM сравните 1/2/4 API-реплики на одном профиле нагрузки; затем проведите серию с ростом ресурсов. Найдите saturation point БД/LB/пула и покажите, почему рост реплик перестаёт помогать. Дайте исходные данные, графики и одно подтверждённое улучшение. + +**Трек 2. Отказ узла.** Расширьте стенд до нескольких узлов, покажите перенос API при потере узла и разберите оставшиеся SPOF (LB, DB, storage). Для заявленной защищённой зависимости покажите реальный failover и сохранность данных. Если DB не реплицирована, не заявляйте выживание её узла. + +## Как начать и проверить + +```sh +# Работает прямо в skeleton, Python 3.9+; приложение не запускается: +make check + +# После реализации запустите свой сервер/стенд по REPORT.md. +# По умолчанию тест использует http://localhost:8080. +make test +``` + +`.env.example`, `compose.example.yaml` и `contracts/infrastructure.json` описывают настройки и роли компонентов. **compose.example.yaml — список ролей с пустым services, не запускаемый стенд.** Реализуйте свой `compose.yaml`/`stack.yaml`, закрепите версии образов, заполните локальный `.env` и опишите bootstrap/миграции. Все зависимости поднимаются из этого репозитория; ссылка «у меня БД уже установлена» не заменяет воспроизводимость. + +```sh +# Compose-вариант после реализации: +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build +# Дождитесь /health/ready; затем make test. +# Для Swarm укажите эквивалентные build/push/deploy-команды в REPORT.md. +``` + + +Примеры запросов доступны в `examples/requests.http`, примеры JSON — в `contracts/examples.json`. Для полной проверки схемы (по желанию локально; CI делает её автоматически): + +```sh +python3 -m venv .venv +.venv/bin/python -m pip install -r requirements-dev.txt +make validate PYTHON=.venv/bin/python +``` + +Smoke не выставляет оценку автоматически. Проверку сохранности/отказов запускайте явно по [tests/README.md](tests/README.md), остальные доказательства приведите в отчёте. + +## Сценарий защиты + +1. Запустить стенд и показать ≥2 разных X-Instance-Id через LB с одной сессией. +2. Запустить make test-failover ACTION_SCRIPT=scripts/stop-one.sh. Скрипт теста выполняет запросы во время action, учитывает ошибки и повторяет сообщения с исходным ключом. +3. Показать, какой контейнер действительно остановлен; заголовок сам по себе не доказательство разных процессов. Повторить для второй реплики после восстановления первой. +4. Проверить restart всего стенда с сохранением volumes и неизменным токеном. Для 4/5 — соответствующие эксперименты. + +## Что должно быть в PR + +compose.yaml или stack.yaml, конфигурация LB, scripts/restart.sh, scripts/stop-one.sh, Dockerfile, миграции, результаты отказов. + +Заполните `REPORT.md` и [шаблон PR](.github/pull_request_template.md), укажите целевую оценку/трек. Не меняйте обязательный контракт и публичные tests ради зелёного результата. Сохраняйте возможности предыдущих лабораторных в пределах [объявленных переходов](COURSE.md). + +## Вопросы на защите + +- Чем отказ процесса отличается от отказа узла? +- Почему depends_on/healthcheck сами по себе не являются балансировщиком? +- Какие POST можно повторять после timeout и что защищает Idempotency-Key? +- Что сломается при увеличении числа API, если сессии находятся в локальной памяти? + +## Первичные материалы + +- [Compose services](https://docs.docker.com/reference/compose-file/services/) +- [Swarm routing mesh](https://docs.docker.com/engine/swarm/ingress/) +- [Swarm services](https://docs.docker.com/engine/swarm/services/) diff --git a/REPORT.md b/REPORT.md new file mode 100644 index 0000000..2b2b7ab --- /dev/null +++ b/REPORT.md @@ -0,0 +1,113 @@ +# Отчёт — лабораторная 3 + +- Автор, группа: Аккуратов Тимофей, бвт2304 +- Целевая оценка: 5; выбран трек 1 — цена масштабирования +- Commit/PR: ещё не созданы; изменения находятся в локальном рабочем каталоге +- Источники, библиотеки и помощь ИИ: перенесена собственная реализация из mtusi2026lab2; Python stdlib, psycopg 3.2.10 и psycopg-pool 3.3.3; официальные образы PostgreSQL и HAProxy. При разработке использовалась помощь Copilot в VS Code; код и результаты проверены локально. Чужие исходники не переносились. + +## Запуск из чистого clone + +Требуются Docker Desktop с Compose v2, `openssl`, `make` и Python 3.9+ для локальных проверок. API работает в образе Python 3.12.7; клиентские тесты используют только стандартную библиотеку. + +```sh +cp .env.example .env +./scripts/bootstrap-secrets.sh +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build --scale api=2 --wait --wait-timeout 120 + +make check +make test +make test-idempotency +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +``` + +Для полной OpenAPI-валидации: + +```sh +python3 -m venv .venv +.venv/bin/python -m pip install -r requirements-dev.txt +make validate PYTHON=.venv/bin/python +``` + +`bootstrap-secrets.sh` создаёт локальные `secrets/postgres_password` и `secrets/database_url`, не печатая их. `.env` и `secrets/` игнорируются Git. Миграции применяются одноразовым сервисом `migrate`; дождитесь состояния `healthy` у PostgreSQL и API. По умолчанию тесты обращаются к `http://127.0.0.1:8080`; при изменении `APP_PORT` задайте, например, `make test BASE_URL=http://127.0.0.1:8081`. + +Безопасная остановка с сохранением данных: `docker compose --env-file .env down`. **Намеренное удаление всех учебных данных** — только отдельной командой `docker compose --env-file .env down -v`; эта команда не используется проверками restart/failover. + +Исследовательский эксперимент целиком повторяется одной командой после запуска Compose-стенда: + +```sh +make track1 +``` + +Команда запускает все семь случаев матрицы: 1/2/4 реплики при фиксированном бюджете и 1/2/4/8 при росте ресурсов. Для сопоставимости используйте тот же Docker host, порт, число клиентов и длительность. Экспериментальные записи удаляются при восстановлении сохранённого baseline. + +## Архитектура и решения + +**Клиент → HAProxy → API × 2+ → общая PostgreSQL.** В Compose нет `container_name`; API-порты не опубликованы на хост. Единственный внешний порт — `127.0.0.1:${APP_PORT}:8080` у HAProxy. Реплики не используют sticky sessions. Сессии, сообщения и результаты идемпотентности хранятся в PostgreSQL; это единственный источник истины. Redis из предыдущей реализации остаётся необязательной возможностью в коде, но в этом стенде не развёрнут и для корректности не нужен. + +Из lab2 перенесены `src/`, `migrations/001_initial.sql`, Dockerfile и зависимости. Изменения этой работы: + +- API больше не запускает миграции при старте. Сервис `migrate` применяет версионированные SQL-файлы до запуска реплик; таблица `schema_migrations` и advisory transaction lock защищают от повторного применения. +- `migrations/002_idempotency.sql` добавляет общую таблицу ключей. Ключ уникален в области user + POST + chat + key; хранится SHA-256 канонического JSON и исходный ответ. Проверка повтора, создание сообщения и сохранение ответа выполняются в одной транзакции PostgreSQL. Transaction-level advisory lock сериализует конкурентные запросы с тем же ключом на разных репликах. Конфликтующий body возвращает 409, успешный повтор — исходное сообщение; срок хранения не меньше 24 часов. +- `X-Instance-Id` берётся из hostname контейнера и неизменен в пределах процесса. `scripts/stop-one.sh` сопоставляет его с конкретным контейнером. +- HAProxy обнаруживает backend через DNS Docker (`127.0.0.11`, `hold valid 2s`) и проверяет `GET /health/ready` каждую секунду; backend считается недоступным после двух неудач. С учётом DNS TTL и таймаута проверки консервативный бюджет обнаружения — до 5s, что ниже лимита 10s; connect timeout — 2s, client/server timeout — 15s. У API есть readiness healthcheck, лимиты БД: statement 5s, lock 2s, pool wait 3s. При SIGTERM сервер прекращает приём и завершает активные запросы; `stop_grace_period` — 20s. +- Все контейнерные образы закреплены тегами: Python 3.12.7-slim, PostgreSQL 16.4-alpine, HAProxy 3.0.7-alpine. PostgreSQL использует именованный `postgres_data`. API по умолчанию ограничен 1 CPU/512 MiB на реплику; PostgreSQL — 1 CPU/1 GiB, HAProxy — 0.5 CPU/128 MiB. В переменных `.env.example` настраиваются host port, TTL и per-replica лимиты API. + +Миграция 002 аддитивна и не меняет существующие таблицы lab2, поэтому старый API не использует новую таблицу. CI workflow `.github/workflows/application.yml` собирает Compose-стенд, запускает публичные и конкурентные тесты, persistence и отказ API-реплики; он не тестирует обновление приложения на новую версию бизнес-кода. Локально проверен поочерёдный restart одинакового образа под нагрузкой. + +## Доказательства критериев + +| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | +| --- | --- | --- | --- | +| Контракт и OpenAPI | `make check`; `make validate PYTHON=.venv/bin/python` | PASS для структуры, синтаксиса и полной OpenAPI 3.1/JSON Schema валидации; контракт и публичные проверки не менялись | `evidence/openapi-validation.txt` | +| Стенд и миграции | `docker compose ... up --scale api=2`; SQL `schema_migrations` | 2 API healthy, PostgreSQL и HAProxy healthy; применены ровно `001_initial.sql`, `002_idempotency.sql`; API опубликованных host ports не имеет | `evidence/deployment-checks.txt` | +| Smoke и общая сессия | `make test` через HAProxy | PASS: полный публичный сценарий lab3 | `evidence/public-tests.txt` | +| Общая идемпотентность | `make test-idempotency` | 12 конкурентных запросов с одинаковым ключом прошли через 2 наблюдаемые реплики, вернули одно сообщение; в истории ровно одна запись. Публичный smoke также проверяет повтор и 409 при другом body | `evidence/public-tests.txt` | +| Persistence lab2 | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS: после перезапуска PostgreSQL, API и LB подтверждённые данные доступны, прежняя сессия действительна; volumes сохранены | `evidence/persistence.txt` | +| Failover первой и второй API | Дважды `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`, восстановление между прогонами | Проверки увидели ≥2 экземпляра. Для первого: 108 успешных записей, 2 неуспешные попытки, восстановление за 2.684s. Для второго: 109 успешных, 1 неуспешная, восстановление за 2.566s. Подтверждённые сообщения и сессия сохранились | `evidence/failover-1.txt`, `evidence/failover-2.txt`, `evidence/failover-targets.txt` | +| Readiness, timeouts, SIGTERM | HAProxy health checks и `scripts/rolling-restart.sh` | Backend исключается после 2 проверок с интервалом 1s; отказная проверка восстановила записи за 2.566–2.684s. Поочерёдный restart обоих контейнеров завершился `healthy` | `haproxy.cfg`, `compose.yaml`, `evidence/failover-1.txt`, `evidence/failover-2.txt`, `evidence/rolling-restart-actions.txt` | +| Лимиты и отсутствие обходного API-порта | `docker compose config`; `docker inspect` | Реально установлены API 1 CPU/512 MiB, PostgreSQL 1 CPU/1 GiB, HAProxy 0.5 CPU/128 MiB. На хост опубликован только loopback-порт LB; в `ps` у API показан только внутренний `8080/tcp` | `evidence/deployment-checks.txt` | +| Rolling restart под нагрузкой | `tests/load.py --duration 35 --concurrency 8` одновременно с `scripts/rolling-restart.sh` | 19,968 успешных POST, 6 ошибок переходного периода; successful RPS 570.303, p50/p95/p99 8.385/45.880/73.085 ms. Оба API контейнера были поочерёдно перезапущены и стали healthy | `evidence/rolling-restart-load.json`, `evidence/rolling-restart-actions.txt` | +| Трек 5 — цена масштабирования | `make track1` | Матрица 1/2/4 при фиксированных ресурсах, затем рост до 1/2/4/8; одна исходная custom-format копия PostgreSQL восстанавливается до каждого прогрева и измерения; три повтора на случай; исходная БД восстанавливается в `finally` | `evidence/track1/results.json`, `evidence/track1/throughput.svg` | +| CI сборка и проверка приложения | `.github/workflows/application.yml` (`push`, `pull_request`) | Отдельный job устанавливает requirements-dev, собирает/ожидает Compose, выполняет `make check validate`, smoke, параллельную идемпотентность, persistence и failover. Workflow добавлен; выполнение на GitHub Actions ожидает push/PR | `.github/workflows/application.yml` | + +## Эксперименты и отказы + +### Трек 1: цена масштабирования + +**Гипотеза:** при фиксированном суммарном бюджете API увеличение числа реплик само по себе не даст прироста; при добавлении ресурсов оно ускорит запись до насыщения общей PostgreSQL, после чего новые API-процессы почти не помогут. + +Одна машина macOS 27.0.1 arm64, физически 10 CPU и 16 GiB RAM; Docker Desktop 28.0.4 / Compose 2.34.0-desktop.1 предоставлял контейнерам 10 vCPU и около 7.65 GiB. API: Python 3.12.7; фиксированные ресурсы PostgreSQL 1 CPU/1 GiB и HAProxy 0.5 CPU/128 MiB. На каждый случай — прогрев 5s и три измеряемых прогона по 30s, 16 параллельных клиентов. Генератор — штатный closed-loop `tests/load.py`, только POST сообщений через LB; прозрачных retry нет. Перед каждым прогревом и измеряемым прогоном API остановлен, PostgreSQL восстановлена из одного custom-format snapshot, проверены контрольные количества строк, затем запускается выбранное число реплик. После всей матрицы в `finally` возвращается исходная БД и две реплики; синтетические benchmark-записи не остаются в volume. Во время запуска исключены внешние записи в БД. В таблице latency — среднее p50/p95/p99 по успешным запросам, RPS — среднее ± стандартное отклонение между тремя прогонами. CPU — максимальная 1-секундная выборка Docker stats; 100% соответствует примерно одному CPU. + +| Профиль | API | Суммарный лимит API | Успешные RPS, среднее ± σ | p50 / p95 / p99, ms | Ошибки | Peak PostgreSQL CPU | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Фиксированный бюджет | 1 | 1 CPU / 512 MiB | 212.54 ± 1.34 | 79.36 / 115.01 / 181.42 | 0 | 28.22% | +| Фиксированный бюджет | 2 | 1 CPU / 512 MiB | 212.71 ± 10.81 | 83.45 / 166.94 / 224.07 | 0 | 40.58% | +| Фиксированный бюджет | 4 | 1 CPU / 512 MiB | 156.34 ± 17.60 | 92.69 / 260.44 / 663.89 | 0 | 46.22% | +| Рост ресурсов | 1 | 1 CPU / 512 MiB | 211.67 ± 1.56 | 79.53 / 115.35 / 182.46 | 0 | 26.54% | +| Рост ресурсов | 2 | 2 CPU / 1 GiB | 604.95 ± 6.29 | 19.72 / 60.32 / 79.17 | 0 | 62.93% | +| Рост ресурсов | 4 | 4 CPU / 2 GiB | 1,099.73 ± 11.87 | 11.01 / 29.91 / 51.29 | 0 | 108.47% | +| Рост ресурсов | 8 | 8 CPU / 4 GiB | 1,159.95 ± 16.88 | 11.75 / 27.90 / 37.07 | 0 | 105.96% | + +При фиксированном бюджете переход к 4 маленьким репликам снизил успешный throughput на 26.4% относительно одной реплики и увеличил p95 с 115.01 до 260.44 ms: дробление CPU между процессами не дало выигрыша. При росте бюджета до четырёх API CPU/2 GiB throughput вырос в 5.19 раза относительно одной реплики при том же per-instance лимите, а p95 уменьшился примерно в 3.86 раза — подтверждённое улучшение для этого стенда. Дальнейшее удвоение API до 8, CPU до 8 и памяти до 4 GiB увеличило throughput на 5.48%; одновременно PostgreSQL достигла выборки 105.96–108.47% одного CPU. Это указывает на насыщение общей БД и уменьшающуюся отдачу от добавления API-ресурсов; это наблюдение относится только к данному профилю, а не универсальная характеристика PostgreSQL. + +Все данные синтетические. До матрицы был зафиксирован baseline snapshot; каждое измерение стартовало с одного и того же состояния БД и создавало свой тестовый набор в новом уникальном чате. Row counts после завершения совпали с baseline: users=156, chats=52, messages=445522, sessions=154, idempotency_records=445522. Пиковая выборка памяти за benchmark: PostgreSQL 252.6 MiB, API 73.1 MiB на контейнер, HAProxy 21.1 MiB. Подробные исходные метрики и выборки CPU/RAM, единый SHA-256 snapshot и контрольные количества строк сохранены в JSON. + +### Отказы + +| Воздействие | Ожидание | Наблюдение | Восстановление / потеря данных | +| --- | --- | --- | --- | +| Остановка первой API-реплики | LB продолжает читать/писать через оставшуюся реплику; повтор сообщения не создаёт дубль | 108 успешных записей, 2 переходные ошибки; readiness восстановилась за 2.684s | Данные и сессия сохранены; потеря подтверждённых сообщений — 0 | +| Остановка второй API-реплики | Те же гарантии для другой реплики | 109 успешных записей, 1 переходная ошибка; readiness восстановилась за 2.566s | Данные и сессия сохранены; потеря подтверждённых сообщений — 0 | +| Поочерёдный SIGTERM/restart двух API под нагрузкой | Вторая реплика остаётся доступной, остановленная возвращается healthy | 19,968 успешных POST, 6 ошибок за 35s; оба экземпляра перезапущены последовательно | Контейнеры вернулись в healthy; подтверждённые записи остаются в PostgreSQL | +| Restart PostgreSQL + API + LB | Сохранить существующую сессию и сообщения на named volume | Persistence-тест PASS с прежним токеном | Потеря данных — 0; volumes не удалялись | + +## Ограничения и следующие шаги + +- Эксперимент закрытый (closed-loop), проводится на одном Mac и одним клиентским процессом; он подвержен coordinated omission и не задаёт независимый arrival rate. Процентили считаются только по успешным ответам, а выборка CPU/RAM снимается раз в секунду. +- Сценарий проверяет отказ API-процесса, не отказ Docker-host, HAProxy, PostgreSQL или диска. PostgreSQL и единственный LB — SPOF; отказ узла не исследовался, multi-node failover не заявляется. +- Порт HTTP открыт только на loopback для синтетического локального стенда. Для удалённой демонстрации необходим TLS. Секреты Compose — локальные bind-mounted файлы, не production secret manager. +- Идемпотентность ограничена текстовым контрактом lab3 и 24-часовым минимумом; транзакция держит PostgreSQL advisory lock. HAProxy `server-template` настроен максимум на 10 адресов — при масштабировании выше нужно расширить диапазон и повторить проверки. +- Rolling-сценарий проверяет поочерёдный restart текущего образа, не обновление на новую версию приложения. Миграции аддитивны, но совместимость произвольной смены версий приложения не проверялась. +- Результаты относятся только к указанным лимитам, размеру данных и клиентской интенсивности. Snapshot теперь одинаков перед каждым прогоном, но нагрузка остаётся closed-loop, на одном ноутбуке, без открытого arrival-rate профиля. diff --git a/compose.example.yaml b/compose.example.yaml new file mode 100644 index 0000000..dd4d387 --- /dev/null +++ b/compose.example.yaml @@ -0,0 +1,11 @@ +# Topology worksheet, deliberately NOT a runnable stack (no application supplied). +# Implement compose.yaml or stack.yaml; do not submit this empty file as deployment. +# Service names below are logical roles, not imposed container names. +x-lab-number: 3 +x-required-roles: + - api + - postgres + - load_balancer +# TODO: implement real images/builds, network wiring, volumes, healthchecks, +# credentials and bootstrap. Details: contracts/infrastructure.json and README.md. +services: {} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..0ceb424 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,105 @@ +services: + postgres: + image: postgres:16.4-alpine + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 2s + timeout: 2s + retries: 20 + start_period: 5s + deploy: + resources: + limits: + cpus: "1.0" + memory: 1G + restart: unless-stopped + + migrate: + build: + context: . + dockerfile: Dockerfile + command: ["python3", "src/migrate.py"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + DB_POOL_MAX_SIZE: "2" + secrets: + - database_url + depends_on: + postgres: + condition: service_healthy + restart: "no" + + api: + build: + context: . + dockerfile: Dockerfile + environment: + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + DATABASE_URL_FILE: /run/secrets/database_url + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + DB_POOL_MAX_SIZE: "8" + DB_POOL_TIMEOUT_SECONDS: "3" + DB_STATEMENT_TIMEOUT_MS: "5000" + DB_LOCK_TIMEOUT_MS: "2000" + secrets: + - database_url + depends_on: + migrate: + condition: service_completed_successfully + healthcheck: + test: + - CMD + - python3 + - -c + - "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=1).read()" + interval: 2s + timeout: 2s + retries: 3 + start_period: 10s + deploy: + resources: + limits: + cpus: "${API_CPU_LIMIT:-1.0}" + memory: "${API_MEMORY_LIMIT:-512M}" + stop_grace_period: 20s + restart: unless-stopped + + load_balancer: + image: haproxy:3.0.7-alpine + ports: + - "127.0.0.1:${APP_PORT:-8080}:8080" + volumes: + - ./haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + depends_on: + api: + condition: service_healthy + healthcheck: + test: ["CMD-SHELL", "haproxy -c -f /usr/local/etc/haproxy/haproxy.cfg"] + interval: 10s + timeout: 3s + retries: 3 + deploy: + resources: + limits: + cpus: "0.5" + memory: 128M + restart: unless-stopped + +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + +volumes: + postgres_data: diff --git a/contracts/README.md b/contracts/README.md new file mode 100644 index 0000000..8c58b32 --- /dev/null +++ b/contracts/README.md @@ -0,0 +1,61 @@ +# Семантика API + +Этот текст дополняет [openapi.json](openapi.json). Обязательный API соответствует уровню 3 текущей лабораторной. Факультативный crop или rate limiting не становятся обязательными только из-за наличия допустимого имени варианта или кода ошибки в схеме. + +## Формат и ошибки + +- JSON — UTF-8, `Content-Type: application/json`. UUID — строка; время — RFC 3339 UTC с `Z`, назначается сервером. Часы не считаются уникальным ID. +- Каждый ответ API, включая ошибки и health, содержит непустой `X-Request-Id`. Тело ошибки: `{"error":{"code":"invalid_request","message":"...","request_id":"..."}}`; `request_id` совпадает с заголовком. Сообщение ошибки не раскрывает stack trace, SQL, credentials или наличие чужого объекта. +- Обязательные строки не состоят только из пробельных символов. `username` строго `[a-z0-9_]{3,32}`, уникален; `display_name` — 1–100 Unicode code points. JSON с лишними полями или неверными типами — `400`; malformed JSON также `400`. +- `400 invalid_request` — неверные поля, UUID, cursor, limit; `401 unauthorized` — нет действительной идентификации/сессии; `404 not_found` — объекта нет или он чужой; `409 conflict` — username занят, повторный ключ с другим сообщением, объект ещё не готов; `413 payload_too_large`; `415 unsupported_media_type`; `429 rate_limited`; `503 unavailable`. Неожиданное исключение — `500 internal_error` без внутренних деталей. +- Сначала аутентификация, затем доступ к конкретному ресурсу. Любой аутентифицированный участник чата может читать его историю и вложения и писать в него; посторонний получает `404`. Списки содержат только доступные объекты. Не используйте `403` для раскрытия существования чужого чата. +- `GET /health/live` проверяет только жизнь процесса, возвращает `200 {"status":"ok"}`. `GET /health/ready` возвращает 200, если приложение может безопасно обслуживать обязательный синхронный путь; иначе 503 в общем формате ошибки. Какие зависимости критичны, зафиксируйте в отчёте; недоступность Grafana не должна останавливать API. + +## Пользователи, чаты и сообщения + +- `POST /users` публичен; возвращает `201 User`. Пароль/его hash и сессионные данные никогда не входят в User. +- `POST /chats` принимает title и явный список существующих `member_ids`, включая вызывающего. Дубликаты, неизвестные участники и отсутствие вызывающего — 400. Чат создаётся атомарно. GET списка чатов сортируется по `(created_at, id)` по возрастанию. +- Отправитель сообщения выводится из текущей идентификации, поле `sender_id` в запросе не принимается. Текст — до 4000 Unicode code points. Нельзя отправить пустой/пробельный текст без вложений. +- История использует keyset cursor: `(created_at, id)`, по возрастанию; `limit` — целое 1–100, по умолчанию 50. Ответ `{"items":[...],"next_cursor":null}`. Непустой cursor — непрозрачная для клиента строка; последний элемент предыдущей страницы не повторяется. Cursor привязан к ресурсу/запросу: от другого чата — 400. Изменять `limit` при продолжении можно. +- `next_cursor` равен null, если на момент чтения следующей записи нет. Гарантируется отсутствие повторов при обходе неизменной истории; snapshot изоляция между несколькими HTTP-запросами не требуется. При конкурентных вставках опишите выбранную семантику и ограничения часов. +- Подтверждённое сообщение видно следующему чтению через любую API-реплику. Допускается кэш, но он не должен возвращать устаревшую историю после успешной записи. Удаление и изменение участников в обязательный API не входят. + +## Идентификация и сессии + +**Lab1:** защищённые endpoint требуют `X-User-Id: `; отсутствие/неизвестный ID — 401. Это учебный выбор пользователя: любой клиент может выдать себя за другого. + +**Lab2–7:** `POST /auth/sessions` принимает только `Authorization: Basic `, без JSON body. Username ограничен ASCII; пароль кодируется UTF-8, 12–128 code points, двоеточие в пароле допустимо. Неверные credentials — одинаковый 401 и `WWW-Authenticate: Basic realm="messenger", charset="UTF-8"`. + +Вход возвращает `201 {"token":"...","token_type":"Bearer","expires_at":"...Z","user":{...}}`. Токен — непрозрачное случайное значение, не username/UUID и не обязательный JWT; энтропия не менее 256 бит. Храните серверную сессию с expiry; TTL задаётся `SESSION_TTL_SECONDS`, по умолчанию 3600 (в тесте истечения можно 2). В обычном smoke TTL должен быть не менее 300. + +Все защищённые endpoint принимают только `Authorization: Bearer `. Истёкший/отозванный/неизвестный токен — 401 с `WWW-Authenticate: Bearer realm="messenger"`. Basic на бизнес-endpoint — 401. `X-User-Id` с lab2 игнорируется: он не меняет владельца сессии и сам по себе не даёт доступ. `DELETE /auth/sessions/current` отзывает текущий токен и возвращает 204 без тела; повтор с отозванным токеном — 401. + +Пользователи, чаты, сообщения и ещё действительные сессии переживают перезапуск приложения и используемых хранилищ с сохранёнными volumes. TTL не продлевается из-за рестарта. Пароли уже с lab2 хешируются библиотечным password KDF (Argon2id, scrypt или bcrypt с учётом ограничений библиотеки), не SHA-256 и не plaintext. Если bcrypt не поддерживает весь диапазон UTF-8 паролей без усечения, выберите другую библиотечную схему. В lab7 обязателен Argon2id. + +Basic — это кодирование, не шифрование. HTTP lab1–6 допускается только для локального изолированного стенда с синтетическими данными; для удалённой демонстрации нужен TLS. Lab7 использует HTTPS обязательно. См. [RFC 7617](https://www.rfc-editor.org/info/rfc7617/). + +## Балансировка и повторная отправка (с lab3) + +- Каждый ответ, созданный API, содержит `X-Instance-Id`; значение стабильно для жизни процесса. Ошибки соединения, созданные самим LB, могут не иметь этого заголовка. В lab7 используйте случайный alias реплики без раскрытия hostname/IP. +- Для POST сообщения обязателен `Idempotency-Key` (ASCII `[A-Za-z0-9._:-]{1,128}`). Нет/неверный ключ — 400. Область уникальности: текущий пользователь + HTTP-метод + путь чата + ключ. +- При повторе того же валидного JSON в течение 24 часов сервер возвращает тот же код 201 и то же Message. Порядок ключей JSON и отсутствующий `attachment_ids` вместо `[]` семантически равны. Другой body при том же ключе — 409. Разные пользователи/чаты могут использовать одинаковый ключ независимо. +- Одновременные повторы через разные реплики создают ровно одно сообщение. Повтор снова проверяет действительность сессии и доступ. Транзиентные 5xx не фиксируются как окончательный результат; побочный эффект и запись результата должны быть атомарны. +- Ключ обязателен только для сообщений. Самостоятельный retry загрузки файла или создания чата может создать ещё один объект; не добавляйте прозрачные повторы этих POST без расширения контракта. + +## Вложения (с lab4) + +- `POST /chats/{chat_id}/attachments?filename=photo.png`: сырые bytes одного PNG/JPEG; `Content-Type: image/png` или `image/jpeg`. Не multipart. Максимум **10 MiB = 10 485 760 байт**. MIME проверяется по содержимому; заведомо повреждённые/чужие форматы — 415, превышение bytes — 413. Не более 40 миллионов декодированных пикселей (превышение — 413). Устанавливайте лимит до полной распаковки изображения. +- `filename` — отображаемое имя (1–255 code points). Не используйте его как путь/ключ S3. Имя с `/`, `\`, NUL или управляющими символами — 400. Bucket приватен; object key генерирует сервер. Оригинал возвращается побайтно, его lowercase SHA-256 и размер соответствуют исходному файлу. +- Lab4 возвращает `201 Attachment` со `status=ready`, `variants=[]`, `error_code=null` только после сохранения оригинала и метаданных. Lab5–7 возвращают `202 Attachment` со снимком `status=queued`; готовность определяется последующим GET метаданных. Быстрый worker может закончить до первого GET — это нормально. +- Файл заранее привязан к чату. В POST сообщения добавляется `attachment_ids` (0–10 уникальных ID, по умолчанию []). Можно отправить `text=""` с хотя бы одним вложением. Все вложения должны принадлежать этому чату; чужое/неизвестное — 404. Любой участник может ссылаться на доступное вложение чата. Failed-вложение прикреплять нельзя (409); queued/processing с lab5 можно. +- `GET /attachments/{id}` и `/content` доступны только участникам чата. Download возвращает байты с истинным Content-Type, через авторизованный API, **без redirect** в обязательном контракте. Приватный bucket сам по себе не заменяет эту проверку. `variant` по умолчанию original. Для queued/processing content — 409; для failed — 409. Отсутствующий вариант ready-объекта — 404. +- В ready-метаданных `error_code=null`. В failed — краткий машинный код (например `invalid_image`, `processing_failed`, `retry_exhausted`), без stack trace. `size_bytes`, `sha256`, `content_type` всегда описывают оригинал; у вариантов отдельные поля. Публичный API не раскрывает ключи бакета, внутренние адреса и credentials. +- Прямой upload/download по временной подписи — факультативное расширение. Его дополняют ограничение срока/размера, уникальный ключ и подтверждение реально загруженного объекта; он не заменяет стандартный endpoint. Особенности подписанных URL: [S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html). + +## Фоновая обработка (с lab5) + +До 202 все байты приняты в **устойчивый staging**, а намерение обработать файл надёжно сохранено. HTTP-передача клиента не исчезает и не становится мгновенной. Staging — приватный S3-prefix либо общий persistent volume, доступный worker; локальная память/API ephemeral disk не подходит. Worker асинхронно переносит/публикует оригинал в конечный S3-prefix и создаёт варианты; если staging уже в S3, опишите эту границу честно. + +Обязательный thumbnail: JPEG, изображение вписано в 256×256 с сохранением пропорций, без увеличения маленьких исходников, EXIF orientation применяется; alpha компонуется на белый. Размеры округляются вниз, минимум 1 px. Fixture 320×200 должен дать 256×160. Статус ready ставится после сохранения оригинала и thumbnail. Crop на 4: JPEG, центрированный квадрат 128×128 (для маленьких исходников допускается увеличение). Optimized на 4: WebP, вписан в 1280×1280 без увеличения, параметры качества и удаления EXIF документируются; не обещайте уменьшение каждого маленького файла. + +Допустимые состояния и события описаны в `jobs.schema.json` и `attachment-states.md`. Доставка — at least once; обработка идемпотентна, повторы не размножают варианты. Финальные ошибки наблюдаемы, бесконечный немой retry недопустим. Обязательный smoke ждёт ready до 60 секунд; это бюджет локального smoke для одного файла при свободном worker, не универсальный production SLA. В очередь идут ссылки/ID, не бинарное содержимое. diff --git a/contracts/examples.json b/contracts/examples.json new file mode 100644 index 0000000..eaa4fcd --- /dev/null +++ b/contracts/examples.json @@ -0,0 +1,58 @@ +{ + "CreateUser": { + "username": "alice", + "display_name": "Алиса", + "password": "Example-only-not-a-real-secret-123" + }, + "User": { + "id": "11111111-1111-4111-8111-111111111111", + "username": "alice", + "display_name": "Алиса", + "created_at": "2026-09-01T12:00:00Z" + }, + "CreateChat": { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ] + }, + "Chat": { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ], + "id": "33333333-3333-4333-8333-333333333333", + "created_at": "2026-09-01T12:00:00Z" + }, + "CreateMessage": { + "text": "Привет, Боб!" + }, + "Message": { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z" + }, + "MessagePage": { + "items": [ + { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z" + } + ], + "next_cursor": null + }, + "Error": { + "error": { + "code": "not_found", + "message": "Объект не найден", + "request_id": "example-request-id" + } + } +} diff --git a/contracts/infrastructure.json b/contracts/infrastructure.json new file mode 100644 index 0000000..28439b8 --- /dev/null +++ b/contracts/infrastructure.json @@ -0,0 +1,36 @@ +{ + "lab": 3, + "kind": "requirements, not runnable deployment", + "required_for_grade_3": [ + { + "role": "api", + "count_min": 2, + "student_implements": true, + "persistent_local_state": false + }, + { + "role": "postgres", + "purpose": "users/chats/membership/messages/metadata", + "persistent_volume": true + }, + { + "role": "load_balancer", + "public_entrypoint": true, + "backend_readiness": true + } + ], + "optional_components": [ + { + "role": "redis_or_valkey", + "required_for_lab2_grade4": true, + "note": "Choose one; if only store of sessions, configure durable persistence." + } + ], + "rules": [ + "Choose Compose or Swarm for lab3+; do not need both.", + "Never publish internal API replica ports in bypass of LB from lab3.", + "Versions/digests must be fixed in implementation.", + "Do not remove volumes in restart/failover checks.", + "Document service names, healthchecks, bootstrap/migrations and credentials." + ] +} diff --git a/contracts/openapi.json b/contracts/openapi.json new file mode 100644 index 0000000..da4d1cc --- /dev/null +++ b/contracts/openapi.json @@ -0,0 +1,2528 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "MTUSI Messenger — лабораторная 3", + "version": "1.3.0", + "description": "Нормативный минимум на 3. Семантика: contracts/README.md. Расширения на 4/5 не должны менять этот API. Наличие кода ошибки в схеме не требует реализовать факультативную причину его выдачи." + }, + "servers": [ + { + "url": "http://localhost:8080", + "description": "Локальный учебный стенд" + } + ], + "security": [ + { + "bearerAuth": [] + } + ], + "paths": { + "/health/live": { + "get": { + "operationId": "liveness", + "summary": "Процесс жив", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [] + } + }, + "/health/ready": { + "get": { + "operationId": "readiness", + "summary": "Готов принимать трафик", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [] + } + }, + "/api/v1/users": { + "post": { + "operationId": "registerUser", + "summary": "Создать пользователя", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateUser" + } + } + } + } + } + }, + "/api/v1/users/me": { + "get": { + "operationId": "currentUser", + "summary": "Текущий пользователь", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/v1/chats": { + "post": { + "operationId": "createChat", + "summary": "Создать чат; вызывающий должен входить в member_ids", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Chat" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateChat" + } + } + } + } + }, + "get": { + "operationId": "listChats", + "summary": "Чаты текущего пользователя", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatPage" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 50 + } + }, + { + "name": "cursor", + "in": "query", + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + } + }, + "/api/v1/chats/{chat_id}": { + "get": { + "operationId": "getChat", + "summary": "Получить доступный чат", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Chat" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "chat_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ] + } + }, + "/api/v1/chats/{chat_id}/messages": { + "post": { + "operationId": "createMessage", + "summary": "Отправить сообщение", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "chat_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "Idempotency-Key", + "in": "header", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z0-9._:-]+$" + }, + "description": "Обязателен с lab3. Область: пользователь + метод + путь + ключ; хранить результат не менее 24 ч. Повтор того же JSON возвращает исходный 201 и то же сообщение, другой JSON — 409." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateMessage" + } + } + } + } + }, + "get": { + "operationId": "listMessages", + "summary": "Сообщения по (created_at, id) по возрастанию", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessagePage" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "chat_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 50 + } + }, + { + "name": "cursor", + "in": "query", + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + } + }, + "/api/v1/auth/sessions": { + "post": { + "operationId": "createSession", + "summary": "Вход: Basic username:password; выдаёт сессию", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Session" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [ + { + "basicAuth": [] + } + ] + } + }, + "/api/v1/auth/sessions/current": { + "delete": { + "operationId": "revokeSession", + "summary": "Отозвать текущую сессию", + "responses": { + "204": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + } + }, + "components": { + "securitySchemes": { + "basicAuth": { + "type": "http", + "scheme": "basic" + }, + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "opaque session token" + } + }, + "schemas": { + "Error": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "invalid_request", + "unauthorized", + "not_found", + "conflict", + "payload_too_large", + "unsupported_media_type", + "rate_limited", + "unavailable", + "internal_error" + ] + }, + "message": { + "type": "string", + "minLength": 1 + }, + "request_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "code", + "message", + "request_id" + ], + "additionalProperties": false + } + }, + "required": [ + "error" + ], + "additionalProperties": false, + "examples": [ + { + "error": { + "code": "not_found", + "message": "Объект не найден", + "request_id": "example-request-id" + } + } + ] + }, + "Health": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "ok" + ] + } + }, + "required": [ + "status" + ], + "additionalProperties": false + }, + "User": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "username": { + "type": "string", + "pattern": "^[a-z0-9_]{3,32}$" + }, + "display_name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "created_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "username", + "display_name", + "created_at" + ], + "additionalProperties": false, + "examples": [ + { + "id": "11111111-1111-4111-8111-111111111111", + "username": "alice", + "display_name": "Алиса", + "created_at": "2026-09-01T12:00:00Z" + } + ] + }, + "CreateUser": { + "type": "object", + "properties": { + "username": { + "type": "string", + "pattern": "^[a-z0-9_]{3,32}$" + }, + "display_name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "password": { + "type": "string", + "minLength": 12, + "maxLength": 128, + "writeOnly": true + } + }, + "required": [ + "username", + "display_name", + "password" + ], + "additionalProperties": false, + "examples": [ + { + "username": "alice", + "display_name": "Алиса", + "password": "Example-only-not-a-real-secret-123" + } + ] + }, + "Chat": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "member_ids": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "minItems": 1, + "maxItems": 100, + "uniqueItems": true + }, + "created_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "title", + "member_ids", + "created_at" + ], + "additionalProperties": false, + "examples": [ + { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ], + "id": "33333333-3333-4333-8333-333333333333", + "created_at": "2026-09-01T12:00:00Z" + } + ] + }, + "CreateChat": { + "type": "object", + "properties": { + "title": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "member_ids": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "minItems": 1, + "maxItems": 100, + "uniqueItems": true + } + }, + "required": [ + "title", + "member_ids" + ], + "additionalProperties": false, + "examples": [ + { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ] + } + ] + }, + "Message": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "chat_id": { + "type": "string", + "format": "uuid" + }, + "sender_id": { + "type": "string", + "format": "uuid" + }, + "text": { + "type": "string", + "minLength": 1, + "maxLength": 4000 + }, + "created_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "chat_id", + "sender_id", + "text", + "created_at" + ], + "additionalProperties": false, + "examples": [ + { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z" + } + ] + }, + "CreateMessage": { + "type": "object", + "properties": { + "text": { + "type": "string", + "minLength": 1, + "maxLength": 4000 + } + }, + "required": [ + "text" + ], + "additionalProperties": false, + "examples": [ + { + "text": "Привет, Боб!" + } + ] + }, + "ChatPage": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Chat" + } + }, + "next_cursor": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "items", + "next_cursor" + ], + "additionalProperties": false + }, + "MessagePage": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Message" + } + }, + "next_cursor": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "items", + "next_cursor" + ], + "additionalProperties": false, + "examples": [ + { + "items": [ + { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z" + } + ], + "next_cursor": null + } + ] + }, + "Session": { + "type": "object", + "properties": { + "token": { + "type": "string", + "minLength": 32 + }, + "token_type": { + "type": "string", + "const": "Bearer" + }, + "expires_at": { + "type": "string", + "format": "date-time" + }, + "user": { + "$ref": "#/components/schemas/User" + } + }, + "required": [ + "token", + "token_type", + "expires_at", + "user" + ], + "additionalProperties": false + } + } + } +} diff --git a/evidence/README.md b/evidence/README.md new file mode 100644 index 0000000..8df7001 --- /dev/null +++ b/evidence/README.md @@ -0,0 +1,5 @@ +# Доказательства + +Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки. + +Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно. diff --git a/evidence/deployment-checks.txt b/evidence/deployment-checks.txt new file mode 100644 index 0000000..0d8da87 --- /dev/null +++ b/evidence/deployment-checks.txt @@ -0,0 +1,16 @@ +Capture time: 2026-10-21T05:57:02Z +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab3-api-5 mtusi2026lab3-api "python3 src/server.…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp +mtusi2026lab3-api-6 mtusi2026lab3-api "python3 src/server.…" api 2 minutes ago Up 2 minutes (healthy) 8080/tcp +mtusi2026lab3-load_balancer-1 haproxy:3.0.7-alpine "docker-entrypoint.s…" load_balancer 29 minutes ago Up 17 minutes (healthy) 127.0.0.1:8080->8080/tcp +mtusi2026lab3-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 29 minutes ago Up 17 minutes (healthy) 5432/tcp + +Migration versions: +001_initial.sql +002_idempotency.sql + +Container limits: +/mtusi2026lab3-api-5 NanoCPUs=1000000000 MemoryBytes=536870912 +/mtusi2026lab3-api-6 NanoCPUs=1000000000 MemoryBytes=536870912 +/mtusi2026lab3-postgres-1 NanoCPUs=1000000000 MemoryBytes=1073741824 +/mtusi2026lab3-load_balancer-1 NanoCPUs=500000000 MemoryBytes=134217728 diff --git a/evidence/failover-1.txt b/evidence/failover-1.txt new file mode 100644 index 0000000..4fc2f9b --- /dev/null +++ b/evidence/failover-1.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:8080" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 108, "failed_attempts": 2, "first_recovery_seconds": 2.684} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/failover-2.txt b/evidence/failover-2.txt new file mode 100644 index 0000000..fe57793 --- /dev/null +++ b/evidence/failover-2.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:8080" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 109, "failed_attempts": 1, "first_recovery_seconds": 2.566} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/failover-targets.txt b/evidence/failover-targets.txt new file mode 100644 index 0000000..55e111c --- /dev/null +++ b/evidence/failover-targets.txt @@ -0,0 +1,2 @@ +2026-10-21T05:39:45Z target_instance=498a08cd2b5c container=498a08cd2b5cf94be02873ea9eb0c9c5f6b79133ddfd50b44aff134f86222b71 +2026-10-21T05:40:39Z target_instance=137c7f092d63 container=137c7f092d63cd2e0d8d2b71ceecd67860c35ba79709df56831bba3a967629ba diff --git a/evidence/openapi-validation.txt b/evidence/openapi-validation.txt new file mode 100644 index 0000000..f75669b --- /dev/null +++ b/evidence/openapi-validation.txt @@ -0,0 +1,4 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +.venv/bin/python scripts/validate_openapi.py +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 0000000..90ac266 --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/public-tests.txt b/evidence/public-tests.txt new file mode 100644 index 0000000..8219a37 --- /dev/null +++ b/evidence/public-tests.txt @@ -0,0 +1,6 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +python3 tests/smoke.py --base-url "http://127.0.0.1:8080" +PASS: lab3 public API scenario; infrastructure and grading evidence remain separate. +python3 student-tests/test_idempotency_race.py --base-url "http://127.0.0.1:8080" +PASS: 12 concurrent same-key requests on 2 replicas returned one message diff --git a/evidence/rolling-restart-actions.txt b/evidence/rolling-restart-actions.txt new file mode 100644 index 0000000..ac97f60 --- /dev/null +++ b/evidence/rolling-restart-actions.txt @@ -0,0 +1,29 @@ + Container mtusi2026lab3-postgres-1 Running + Container mtusi2026lab3-migrate-1 Created + Container mtusi2026lab3-api-3 Running + Container mtusi2026lab3-api-4 Created + Container mtusi2026lab3-load_balancer-1 Running + Container mtusi2026lab3-postgres-1 Waiting + Container mtusi2026lab3-postgres-1 Healthy + Container mtusi2026lab3-migrate-1 Starting + Container mtusi2026lab3-migrate-1 Started + Container mtusi2026lab3-migrate-1 Waiting + Container mtusi2026lab3-migrate-1 Exited + Container mtusi2026lab3-api-4 Starting + Container mtusi2026lab3-api-4 Started + Container mtusi2026lab3-api-4 Waiting + Container mtusi2026lab3-api-3 Waiting + Container mtusi2026lab3-api-4 Healthy + Container mtusi2026lab3-api-3 Healthy + Container mtusi2026lab3-api-4 Waiting + Container mtusi2026lab3-api-3 Waiting + Container mtusi2026lab3-load_balancer-1 Waiting + Container mtusi2026lab3-postgres-1 Waiting + Container mtusi2026lab3-migrate-1 Waiting + Container mtusi2026lab3-load_balancer-1 Healthy + Container mtusi2026lab3-migrate-1 Exited + Container mtusi2026lab3-postgres-1 Healthy + Container mtusi2026lab3-api-4 Healthy + Container mtusi2026lab3-api-3 Healthy +PASS: API container 498a08cd2b5cf94be02873ea9eb0c9c5f6b79133ddfd50b44aff134f86222b71 restarted and is healthy +PASS: API container 137c7f092d63cd2e0d8d2b71ceecd67860c35ba79709df56831bba3a967629ba restarted and is healthy diff --git a/evidence/rolling-restart-load.json b/evidence/rolling-restart-load.json new file mode 100644 index 0000000..92f641e --- /dev/null +++ b/evidence/rolling-restart-load.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 35.0, + "elapsed_seconds": 35.013, + "concurrency": 8, + "successful_requests": 19968, + "failed_requests": 6, + "error_ratio": 0.0003, + "successful_rps": 570.303, + "successful_latency_ms": { + "p50": 8.385, + "p95": 45.88, + "p99": 73.085 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-1-run-1.json b/evidence/track1/fixed-1-run-1.json new file mode 100644 index 0000000..9e8f630 --- /dev/null +++ b/evidence/track1/fixed-1-run-1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.046, + "concurrency": 16, + "successful_requests": 6346, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 211.212, + "successful_latency_ms": { + "p50": 80.264, + "p95": 114.896, + "p99": 182.694 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-1-run-2.json b/evidence/track1/fixed-1-run-2.json new file mode 100644 index 0000000..b271d8b --- /dev/null +++ b/evidence/track1/fixed-1-run-2.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.064, + "concurrency": 16, + "successful_requests": 6445, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 214.379, + "successful_latency_ms": { + "p50": 78.662, + "p95": 115.143, + "p99": 181.9 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-1-run-3.json b/evidence/track1/fixed-1-run-3.json new file mode 100644 index 0000000..cda8700 --- /dev/null +++ b/evidence/track1/fixed-1-run-3.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.056, + "concurrency": 16, + "successful_requests": 6373, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 212.038, + "successful_latency_ms": { + "p50": 79.158, + "p95": 114.991, + "p99": 179.677 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-1-warmup-run-0.json b/evidence/track1/fixed-1-warmup-run-0.json new file mode 100644 index 0000000..503376e --- /dev/null +++ b/evidence/track1/fixed-1-warmup-run-0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.065, + "concurrency": 16, + "successful_requests": 1036, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 204.529, + "successful_latency_ms": { + "p50": 81.556, + "p95": 109.862, + "p99": 172.61 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-2-run-1.json b/evidence/track1/fixed-2-run-1.json new file mode 100644 index 0000000..27aa6a4 --- /dev/null +++ b/evidence/track1/fixed-2-run-1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.098, + "concurrency": 16, + "successful_requests": 5968, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 198.285, + "successful_latency_ms": { + "p50": 86.571, + "p95": 190.715, + "p99": 278.78 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-2-run-2.json b/evidence/track1/fixed-2-run-2.json new file mode 100644 index 0000000..36d1fef --- /dev/null +++ b/evidence/track1/fixed-2-run-2.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.03, + "concurrency": 16, + "successful_requests": 6736, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 224.312, + "successful_latency_ms": { + "p50": 80.141, + "p95": 150.189, + "p99": 197.092 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-2-run-3.json b/evidence/track1/fixed-2-run-3.json new file mode 100644 index 0000000..ad04858 --- /dev/null +++ b/evidence/track1/fixed-2-run-3.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.031, + "concurrency": 16, + "successful_requests": 6473, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 215.547, + "successful_latency_ms": { + "p50": 83.643, + "p95": 159.92, + "p99": 196.349 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-2-warmup-run-0.json b/evidence/track1/fixed-2-warmup-run-0.json new file mode 100644 index 0000000..8a772b5 --- /dev/null +++ b/evidence/track1/fixed-2-warmup-run-0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.017, + "concurrency": 16, + "successful_requests": 990, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 197.311, + "successful_latency_ms": { + "p50": 82.99, + "p95": 199.803, + "p99": 294.885 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-4-run-1.json b/evidence/track1/fixed-4-run-1.json new file mode 100644 index 0000000..700c390 --- /dev/null +++ b/evidence/track1/fixed-4-run-1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.155, + "concurrency": 16, + "successful_requests": 5464, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 181.196, + "successful_latency_ms": { + "p50": 85.443, + "p95": 200.223, + "p99": 467.896 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-4-run-2.json b/evidence/track1/fixed-4-run-2.json new file mode 100644 index 0000000..9f28120 --- /dev/null +++ b/evidence/track1/fixed-4-run-2.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.201, + "concurrency": 16, + "successful_requests": 4377, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 144.927, + "successful_latency_ms": { + "p50": 98.238, + "p95": 287.157, + "p99": 494.409 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-4-run-3.json b/evidence/track1/fixed-4-run-3.json new file mode 100644 index 0000000..7206a67 --- /dev/null +++ b/evidence/track1/fixed-4-run-3.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.261, + "concurrency": 16, + "successful_requests": 4324, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 142.888, + "successful_latency_ms": { + "p50": 94.377, + "p95": 293.944, + "p99": 1029.361 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/fixed-4-warmup-run-0.json b/evidence/track1/fixed-4-warmup-run-0.json new file mode 100644 index 0000000..2e7bf06 --- /dev/null +++ b/evidence/track1/fixed-4-warmup-run-0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.173, + "concurrency": 16, + "successful_requests": 1140, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 220.377, + "successful_latency_ms": { + "p50": 64.745, + "p95": 197.524, + "p99": 398.349 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-1-run-1.json b/evidence/track1/growth-1-run-1.json new file mode 100644 index 0000000..4097620 --- /dev/null +++ b/evidence/track1/growth-1-run-1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.039, + "concurrency": 16, + "successful_requests": 6333, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 210.824, + "successful_latency_ms": { + "p50": 80.103, + "p95": 114.112, + "p99": 182.734 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-1-run-2.json b/evidence/track1/growth-1-run-2.json new file mode 100644 index 0000000..66983e3 --- /dev/null +++ b/evidence/track1/growth-1-run-2.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.073, + "concurrency": 16, + "successful_requests": 6325, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 210.32, + "successful_latency_ms": { + "p50": 79.313, + "p95": 117.188, + "p99": 183.607 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-1-run-3.json b/evidence/track1/growth-1-run-3.json new file mode 100644 index 0000000..6581c6d --- /dev/null +++ b/evidence/track1/growth-1-run-3.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.03, + "concurrency": 16, + "successful_requests": 6422, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 213.855, + "successful_latency_ms": { + "p50": 79.164, + "p95": 114.738, + "p99": 181.052 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-1-warmup-run-0.json b/evidence/track1/growth-1-warmup-run-0.json new file mode 100644 index 0000000..62d5fc1 --- /dev/null +++ b/evidence/track1/growth-1-warmup-run-0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.03, + "concurrency": 16, + "successful_requests": 1054, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 209.531, + "successful_latency_ms": { + "p50": 77.196, + "p95": 116.562, + "p99": 184.922 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-2-run-1.json b/evidence/track1/growth-2-run-1.json new file mode 100644 index 0000000..d5413e7 --- /dev/null +++ b/evidence/track1/growth-2-run-1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.017, + "concurrency": 16, + "successful_requests": 18059, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 601.627, + "successful_latency_ms": { + "p50": 19.831, + "p95": 60.095, + "p99": 81.757 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-2-run-2.json b/evidence/track1/growth-2-run-2.json new file mode 100644 index 0000000..219ccbf --- /dev/null +++ b/evidence/track1/growth-2-run-2.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.494, + "concurrency": 16, + "successful_requests": 18280, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 599.463, + "successful_latency_ms": { + "p50": 19.535, + "p95": 59.859, + "p99": 78.355 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-2-run-3.json b/evidence/track1/growth-2-run-3.json new file mode 100644 index 0000000..d0a5ee7 --- /dev/null +++ b/evidence/track1/growth-2-run-3.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.029, + "concurrency": 16, + "successful_requests": 18431, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 613.766, + "successful_latency_ms": { + "p50": 19.791, + "p95": 61.005, + "p99": 77.388 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-2-warmup-run-0.json b/evidence/track1/growth-2-warmup-run-0.json new file mode 100644 index 0000000..a84f1fc --- /dev/null +++ b/evidence/track1/growth-2-warmup-run-0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.037, + "concurrency": 16, + "successful_requests": 3029, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 601.302, + "successful_latency_ms": { + "p50": 20.938, + "p95": 59.639, + "p99": 76.915 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-4-run-1.json b/evidence/track1/growth-4-run-1.json new file mode 100644 index 0000000..94a68db --- /dev/null +++ b/evidence/track1/growth-4-run-1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.012, + "concurrency": 16, + "successful_requests": 32846, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1094.415, + "successful_latency_ms": { + "p50": 10.732, + "p95": 30.846, + "p99": 51.188 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-4-run-2.json b/evidence/track1/growth-4-run-2.json new file mode 100644 index 0000000..bf6061b --- /dev/null +++ b/evidence/track1/growth-4-run-2.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.013, + "concurrency": 16, + "successful_requests": 32672, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1088.609, + "successful_latency_ms": { + "p50": 11.145, + "p95": 30.074, + "p99": 53.423 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-4-run-3.json b/evidence/track1/growth-4-run-3.json new file mode 100644 index 0000000..88a86ae --- /dev/null +++ b/evidence/track1/growth-4-run-3.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.015, + "concurrency": 16, + "successful_requests": 33502, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1116.177, + "successful_latency_ms": { + "p50": 11.142, + "p95": 28.815, + "p99": 49.26 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-4-warmup-run-0.json b/evidence/track1/growth-4-warmup-run-0.json new file mode 100644 index 0000000..94894af --- /dev/null +++ b/evidence/track1/growth-4-warmup-run-0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.014, + "concurrency": 16, + "successful_requests": 5472, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1091.286, + "successful_latency_ms": { + "p50": 11.367, + "p95": 33.413, + "p99": 54.849 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-8-run-1.json b/evidence/track1/growth-8-run-1.json new file mode 100644 index 0000000..eab3e07 --- /dev/null +++ b/evidence/track1/growth-8-run-1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.033, + "concurrency": 16, + "successful_requests": 34199, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1138.726, + "successful_latency_ms": { + "p50": 11.784, + "p95": 29.272, + "p99": 38.508 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-8-run-2.json b/evidence/track1/growth-8-run-2.json new file mode 100644 index 0000000..fb0df2b --- /dev/null +++ b/evidence/track1/growth-8-run-2.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.015, + "concurrency": 16, + "successful_requests": 35418, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1180.016, + "successful_latency_ms": { + "p50": 11.711, + "p95": 26.361, + "p99": 36.002 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-8-run-3.json b/evidence/track1/growth-8-run-3.json new file mode 100644 index 0000000..392cbb4 --- /dev/null +++ b/evidence/track1/growth-8-run-3.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.012, + "concurrency": 16, + "successful_requests": 34848, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1161.122, + "successful_latency_ms": { + "p50": 11.745, + "p95": 28.074, + "p99": 36.688 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/growth-8-warmup-run-0.json b/evidence/track1/growth-8-warmup-run-0.json new file mode 100644 index 0000000..06ad484 --- /dev/null +++ b/evidence/track1/growth-8-warmup-run-0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.014, + "concurrency": 16, + "successful_requests": 5457, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1088.404, + "successful_latency_ms": { + "p50": 11.999, + "p95": 31.015, + "p99": 44.748 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/track1/results.json b/evidence/track1/results.json new file mode 100644 index 0000000..7924f63 --- /dev/null +++ b/evidence/track1/results.json @@ -0,0 +1,6529 @@ +{ + "method": "closed-loop POST message workload via HAProxy; same concurrency and per-run restored PostgreSQL custom-format baseline snapshot", + "database_baseline": { + "snapshot_sha256": "ddd62de0d9ba118508d4ee382c617927f5daa81f2acf769a5b49e67ac6e3db91", + "row_counts": { + "users": 156, + "chats": 52, + "messages": 445522, + "sessions": 154, + "idempotency_records": 445522 + }, + "restore_before_each_warmup_and_measured_repetition": true, + "state_after_experiment": "baseline restored; all synthetic benchmark writes removed" + }, + "system": { + "platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "processor": "arm", + "cpu_count": 10, + "host_memory_bytes": "17179869184", + "docker_server": "28.0.4", + "docker_compose": "2.34.0-desktop.1" + }, + "database_and_lb_limits": { + "postgres": "1 CPU / 1 GiB", + "HAProxy": "0.5 CPU / 128 MiB" + }, + "client_concurrency": 16, + "requested_duration_seconds": 30, + "repetitions_per_case": 3, + "cases": [ + { + "phase": "fixed", + "api_replicas": 1, + "per_replica_cpu_limit": "1.0000", + "per_replica_memory_limit": "512M", + "total_api_cpu_limit": 1.0, + "total_api_memory_limit_mib": 512, + "warmup_seconds": 5, + "baseline_row_counts": { + "users": 156, + "chats": 52, + "messages": 445522, + "sessions": 154, + "idempotency_records": 445522 + }, + "baseline_snapshot_sha256": "ddd62de0d9ba118508d4ee382c617927f5daa81f2acf769a5b49e67ac6e3db91", + "each_repetition_restored_same_baseline": true, + "repetitions": [ + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.046, + "concurrency": 16, + "successful_requests": 6346, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 211.212, + "successful_latency_ms": { + "p50": 80.264, + "p95": 114.896, + "p99": 182.694 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.41, + "memory_bytes": 44386222 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 6.41, + "memory_bytes": 15917384 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.81, + "memory_bytes": 121844531 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.79, + "memory_bytes": 31415337 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.91, + "memory_bytes": 15351153 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 15.84, + "memory_bytes": 122054246 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.63, + "memory_bytes": 31855739 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 11.41, + "memory_bytes": 15560868 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 14.76, + "memory_bytes": 122473677 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.13, + "memory_bytes": 31939625 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.7, + "memory_bytes": 15560868 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 14.76, + "memory_bytes": 126038835 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 103.55, + "memory_bytes": 32138854 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.71, + "memory_bytes": 15697183 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.43, + "memory_bytes": 127401984 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.57, + "memory_bytes": 32495370 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.3, + "memory_bytes": 15843983 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 14.47, + "memory_bytes": 128240845 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 107.21, + "memory_bytes": 31614566 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.61, + "memory_bytes": 15969812 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.61, + "memory_bytes": 129499136 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 103.53, + "memory_bytes": 32222740 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.28, + "memory_bytes": 16777216 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 15.22, + "memory_bytes": 130547712 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.0, + "memory_bytes": 31939625 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.29, + "memory_bytes": 16315843 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.88, + "memory_bytes": 131596288 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.064, + "concurrency": 16, + "successful_requests": 6445, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 214.379, + "successful_latency_ms": { + "p50": 78.662, + "p95": 115.143, + "p99": 181.9 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.45, + "memory_bytes": 30838620 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.02, + "memory_bytes": 16294871 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 20.19, + "memory_bytes": 132435149 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.67, + "memory_bytes": 31446794 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.38, + "memory_bytes": 16158556 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 14.72, + "memory_bytes": 132749722 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.87, + "memory_bytes": 31782339 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 10.14, + "memory_bytes": 16231956 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.58, + "memory_bytes": 133378867 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 108.29, + "memory_bytes": 44291850 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.36, + "memory_bytes": 16494100 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.4, + "memory_bytes": 133274010 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 107.49, + "memory_bytes": 45455770 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.2, + "memory_bytes": 16263414 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.26, + "memory_bytes": 133798298 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.41, + "memory_bytes": 32044483 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.99, + "memory_bytes": 16913531 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.5, + "memory_bytes": 133064294 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 107.0, + "memory_bytes": 31834767 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.72, + "memory_bytes": 16347300 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.33, + "memory_bytes": 133588582 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.36, + "memory_bytes": 31855739 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.34, + "memory_bytes": 16651387 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.81, + "memory_bytes": 133588582 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.91, + "memory_bytes": 34844180 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.5, + "memory_bytes": 16483615 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.93, + "memory_bytes": 133064294 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.056, + "concurrency": 16, + "successful_requests": 6373, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 212.038, + "successful_latency_ms": { + "p50": 79.158, + "p95": 114.991, + "p99": 179.677 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.32, + "memory_bytes": 44627395 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 6.59, + "memory_bytes": 16315843 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.7, + "memory_bytes": 132644864 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.7, + "memory_bytes": 31478252 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.68, + "memory_bytes": 16651387 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 28.22, + "memory_bytes": 137363456 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.53, + "memory_bytes": 31509709 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 11.37, + "memory_bytes": 16399729 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.06, + "memory_bytes": 137468314 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 107.48, + "memory_bytes": 32243712 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.76, + "memory_bytes": 16965960 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 24.07, + "memory_bytes": 153511526 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 103.04, + "memory_bytes": 32621199 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.31, + "memory_bytes": 16441672 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 15.74, + "memory_bytes": 133903155 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.63, + "memory_bytes": 32453427 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.32, + "memory_bytes": 16787702 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.58, + "memory_bytes": 134112870 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.35, + "memory_bytes": 32243712 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.47, + "memory_bytes": 16515072 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 19.35, + "memory_bytes": 134951731 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 102.85, + "memory_bytes": 32023511 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.3, + "memory_bytes": 16494100 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 15.9, + "memory_bytes": 134112870 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.71, + "memory_bytes": 32537313 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.8, + "memory_bytes": 16567501 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.9, + "memory_bytes": 133903155 + } + ] + } + ] + }, + { + "phase": "fixed", + "api_replicas": 2, + "per_replica_cpu_limit": "0.5000", + "per_replica_memory_limit": "256M", + "total_api_cpu_limit": 1.0, + "total_api_memory_limit_mib": 512, + "warmup_seconds": 5, + "baseline_row_counts": { + "users": 156, + "chats": 52, + "messages": 445522, + "sessions": 154, + "idempotency_records": 445522 + }, + "baseline_snapshot_sha256": "ddd62de0d9ba118508d4ee382c617927f5daa81f2acf769a5b49e67ac6e3db91", + "each_repetition_restored_same_baseline": true, + "repetitions": [ + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.098, + "concurrency": 16, + "successful_requests": 5968, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 198.285, + "successful_latency_ms": { + "p50": 86.571, + "p95": 190.715, + "p99": 278.78 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 40.21, + "memory_bytes": 41219523 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 50.72, + "memory_bytes": 42456842 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.18, + "memory_bytes": 16913531 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 28.94, + "memory_bytes": 165675008 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 51.81, + "memory_bytes": 30859592 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 43.57, + "memory_bytes": 30943478 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.11, + "memory_bytes": 16473129 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 23.74, + "memory_bytes": 166723584 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 27.66, + "memory_bytes": 30932992 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 50.94, + "memory_bytes": 31037850 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.18, + "memory_bytes": 16483615 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 20.38, + "memory_bytes": 163892429 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 51.22, + "memory_bytes": 31142707 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 25.46, + "memory_bytes": 30849106 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.6, + "memory_bytes": 16756244 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 19.27, + "memory_bytes": 163997286 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 51.17, + "memory_bytes": 31111250 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 44.4, + "memory_bytes": 43085988 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.62, + "memory_bytes": 16462643 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 21.76, + "memory_bytes": 163997286 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 50.91, + "memory_bytes": 41617981 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 43.28, + "memory_bytes": 42698015 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.92, + "memory_bytes": 16462643 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 23.41, + "memory_bytes": 163892429 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 43.97, + "memory_bytes": 31027364 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 51.59, + "memory_bytes": 40779121 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 10.97, + "memory_bytes": 16997417 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 20.95, + "memory_bytes": 164102144 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 29.65, + "memory_bytes": 31299994 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 51.34, + "memory_bytes": 30974935 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 10.25, + "memory_bytes": 16504586 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.44, + "memory_bytes": 164941005 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 31.2, + "memory_bytes": 30912020 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 51.33, + "memory_bytes": 30974935 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 10.24, + "memory_bytes": 16724787 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 25.14, + "memory_bytes": 163892429 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.03, + "concurrency": 16, + "successful_requests": 6736, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 224.312, + "successful_latency_ms": { + "p50": 80.141, + "p95": 150.189, + "p99": 197.092 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 44.29, + "memory_bytes": 31216108 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 53.68, + "memory_bytes": 42005955 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.95, + "memory_bytes": 16944988 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 19.04, + "memory_bytes": 157496115 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 44.25, + "memory_bytes": 30786191 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 40.69, + "memory_bytes": 43861934 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 6.79, + "memory_bytes": 16462643 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.13, + "memory_bytes": 162424422 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 27.64, + "memory_bytes": 31142707 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 51.63, + "memory_bytes": 31006392 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.53, + "memory_bytes": 16840131 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.67, + "memory_bytes": 162529280 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 37.09, + "memory_bytes": 40149975 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 51.77, + "memory_bytes": 30985421 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.82, + "memory_bytes": 16515072 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 29.1, + "memory_bytes": 162738995 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 43.23, + "memory_bytes": 30922506 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 51.12, + "memory_bytes": 42708500 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.14, + "memory_bytes": 16494100 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 26.3, + "memory_bytes": 164836147 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 45.91, + "memory_bytes": 31069307 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 53.0, + "memory_bytes": 31226593 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 13.39, + "memory_bytes": 16640901 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 32.68, + "memory_bytes": 164836147 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 40.99, + "memory_bytes": 41638953 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 49.13, + "memory_bytes": 30838620 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 13.53, + "memory_bytes": 16850616 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 40.58, + "memory_bytes": 163787571 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 40.72, + "memory_bytes": 30922506 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 52.01, + "memory_bytes": 31425823 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.74, + "memory_bytes": 16536044 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.56, + "memory_bytes": 164207002 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 40.73, + "memory_bytes": 31100764 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 51.4, + "memory_bytes": 31037850 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 11.79, + "memory_bytes": 16630415 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 24.28, + "memory_bytes": 164102144 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.031, + "concurrency": 16, + "successful_requests": 6473, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 215.547, + "successful_latency_ms": { + "p50": 83.643, + "p95": 159.92, + "p99": 196.349 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 53.87, + "memory_bytes": 40747663 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 29.41, + "memory_bytes": 40328233 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.11, + "memory_bytes": 16724787 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 31.49, + "memory_bytes": 159383552 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 51.43, + "memory_bytes": 31593595 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 31.02, + "memory_bytes": 30754734 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 10.1, + "memory_bytes": 16536044 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 21.6, + "memory_bytes": 162634138 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 51.56, + "memory_bytes": 31016878 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 32.61, + "memory_bytes": 40821064 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 10.42, + "memory_bytes": 17658020 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 21.51, + "memory_bytes": 163263283 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 42.67, + "memory_bytes": 30974935 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 45.26, + "memory_bytes": 43987763 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.46, + "memory_bytes": 16630415 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 22.52, + "memory_bytes": 162948710 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 44.54, + "memory_bytes": 31048335 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 25.11, + "memory_bytes": 30670848 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.23, + "memory_bytes": 16766730 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.95, + "memory_bytes": 164102144 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 51.83, + "memory_bytes": 31132221 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 31.76, + "memory_bytes": 31247565 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 11.1, + "memory_bytes": 16882074 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 23.06, + "memory_bytes": 163053568 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 47.45, + "memory_bytes": 31100764 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 48.33, + "memory_bytes": 41513124 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 11.3, + "memory_bytes": 16903045 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 27.01, + "memory_bytes": 163053568 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 51.12, + "memory_bytes": 31394365 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 41.58, + "memory_bytes": 30796677 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 10.88, + "memory_bytes": 16546529 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 20.89, + "memory_bytes": 163577856 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 52.57, + "memory_bytes": 31163679 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 34.39, + "memory_bytes": 30922506 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 11.46, + "memory_bytes": 16609444 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 19.53, + "memory_bytes": 163158426 + } + ] + } + ] + }, + { + "phase": "fixed", + "api_replicas": 4, + "per_replica_cpu_limit": "0.2500", + "per_replica_memory_limit": "128M", + "total_api_cpu_limit": 1.0, + "total_api_memory_limit_mib": 512, + "warmup_seconds": 5, + "baseline_row_counts": { + "users": 156, + "chats": 52, + "messages": 445522, + "sessions": 154, + "idempotency_records": 445522 + }, + "baseline_snapshot_sha256": "ddd62de0d9ba118508d4ee382c617927f5daa81f2acf769a5b49e67ac6e3db91", + "each_repetition_restored_same_baseline": true, + "repetitions": [ + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.155, + "concurrency": 16, + "successful_requests": 5464, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 181.196, + "successful_latency_ms": { + "p50": 85.443, + "p95": 200.223, + "p99": 467.896 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 12.42, + "memory_bytes": 29695672 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 0.15, + "memory_bytes": 29643244 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 0.17, + "memory_bytes": 29632758 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 15.82, + "memory_bytes": 72320287 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 0.52, + "memory_bytes": 16326328 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 2.19, + "memory_bytes": 130442854 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 25.05, + "memory_bytes": 30188503 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 21.48, + "memory_bytes": 42635100 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 26.2, + "memory_bytes": 43589304 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 23.37, + "memory_bytes": 42582671 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 5.14, + "memory_bytes": 16525558 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.23, + "memory_bytes": 182032794 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 23.45, + "memory_bytes": 30146560 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 25.52, + "memory_bytes": 31037850 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 17.57, + "memory_bytes": 30366761 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 17.52, + "memory_bytes": 30157046 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.44, + "memory_bytes": 16577987 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 21.63, + "memory_bytes": 190001971 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 18.0, + "memory_bytes": 30136074 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 25.91, + "memory_bytes": 30534533 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 16.59, + "memory_bytes": 30377247 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 17.88, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 12.59, + "memory_bytes": 16819159 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 14.94, + "memory_bytes": 189897114 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 20.35, + "memory_bytes": 30198989 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 25.54, + "memory_bytes": 30482104 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 22.51, + "memory_bytes": 40191918 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 9.06, + "memory_bytes": 30146560 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 14.04, + "memory_bytes": 16819159 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 38.69, + "memory_bytes": 190001971 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 14.95, + "memory_bytes": 30209475 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 18.97, + "memory_bytes": 30482104 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 20.36, + "memory_bytes": 40516977 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 24.12, + "memory_bytes": 41313894 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 11.78, + "memory_bytes": 16598958 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 46.22, + "memory_bytes": 197971149 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 18.17, + "memory_bytes": 41030779 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 12.88, + "memory_bytes": 30597448 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 8.11, + "memory_bytes": 30649876 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 25.48, + "memory_bytes": 41848668 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.97, + "memory_bytes": 16494100 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 28.83, + "memory_bytes": 200907162 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 19.07, + "memory_bytes": 41209037 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 10.59, + "memory_bytes": 30618419 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 13.06, + "memory_bytes": 40129004 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 25.15, + "memory_bytes": 43253760 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 6.25, + "memory_bytes": 16504586 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 37.64, + "memory_bytes": 216426086 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 6.49, + "memory_bytes": 30576476 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 22.38, + "memory_bytes": 30618419 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 24.49, + "memory_bytes": 44061164 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 25.15, + "memory_bytes": 43306189 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 5.69, + "memory_bytes": 16756244 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 15.6, + "memory_bytes": 199439155 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 4.25, + "memory_bytes": 30765220 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 16.68, + "memory_bytes": 30524047 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 17.55, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 16.72, + "memory_bytes": 40527462 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 3.55, + "memory_bytes": 16399729 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 11.13, + "memory_bytes": 199439155 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.201, + "concurrency": 16, + "successful_requests": 4377, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 144.927, + "successful_latency_ms": { + "p50": 98.238, + "p95": 287.157, + "p99": 494.409 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 23.13, + "memory_bytes": 43117445 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 13.05, + "memory_bytes": 39552287 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 12.65, + "memory_bytes": 41544581 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 25.02, + "memory_bytes": 76619448 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 0.43, + "memory_bytes": 16315843 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 0.93, + "memory_bytes": 130547712 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 17.47, + "memory_bytes": 30198989 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 16.24, + "memory_bytes": 30261903 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 15.05, + "memory_bytes": 30524047 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 16.74, + "memory_bytes": 30157046 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 6.92, + "memory_bytes": 16798188 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.28, + "memory_bytes": 189163110 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 16.54, + "memory_bytes": 30146560 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 23.11, + "memory_bytes": 40307261 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 15.55, + "memory_bytes": 30188503 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 17.33, + "memory_bytes": 30083645 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 10.94, + "memory_bytes": 16515072 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.85, + "memory_bytes": 191889408 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 18.13, + "memory_bytes": 30649876 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 23.98, + "memory_bytes": 40024146 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 17.0, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 22.16, + "memory_bytes": 30492590 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 12.32, + "memory_bytes": 16609444 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 21.6, + "memory_bytes": 195978854 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 20.05, + "memory_bytes": 39919288 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 23.79, + "memory_bytes": 40894464 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 24.0, + "memory_bytes": 40737178 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 19.46, + "memory_bytes": 30461133 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 11.49, + "memory_bytes": 16598958 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 27.42, + "memory_bytes": 197132288 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 11.25, + "memory_bytes": 30366761 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 22.32, + "memory_bytes": 40988836 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 22.45, + "memory_bytes": 40925921 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 16.95, + "memory_bytes": 30503076 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.0, + "memory_bytes": 16483615 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 23.67, + "memory_bytes": 197132288 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 8.73, + "memory_bytes": 30482104 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 25.54, + "memory_bytes": 42561700 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 25.4, + "memory_bytes": 42142269 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 18.1, + "memory_bytes": 30492590 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 6.23, + "memory_bytes": 16557015 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 19.74, + "memory_bytes": 197237146 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 8.16, + "memory_bytes": 30503076 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 27.01, + "memory_bytes": 43778048 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 25.6, + "memory_bytes": 43400561 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 25.57, + "memory_bytes": 43683676 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 6.47, + "memory_bytes": 16525558 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.45, + "memory_bytes": 198285722 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 15.36, + "memory_bytes": 30576476 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 22.56, + "memory_bytes": 43012588 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 24.34, + "memory_bytes": 43358618 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 22.28, + "memory_bytes": 30618419 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 6.39, + "memory_bytes": 16494100 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 24.97, + "memory_bytes": 199753728 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 1.63, + "memory_bytes": 30408704 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 5.01, + "memory_bytes": 30555505 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 13.21, + "memory_bytes": 30251418 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 4.42, + "memory_bytes": 30492590 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 0.16, + "memory_bytes": 16431186 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 8.62, + "memory_bytes": 199648870 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.261, + "concurrency": 16, + "successful_requests": 4324, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 142.888, + "successful_latency_ms": { + "p50": 94.377, + "p95": 293.944, + "p99": 1029.361 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 24.82, + "memory_bytes": 42698015 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 0.18, + "memory_bytes": 29632758 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 12.6, + "memory_bytes": 29664215 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 19.12, + "memory_bytes": 42739958 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 0.25, + "memory_bytes": 16315843 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 1.51, + "memory_bytes": 130862285 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 17.92, + "memory_bytes": 30073160 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 17.72, + "memory_bytes": 30031217 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 24.12, + "memory_bytes": 42844815 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 18.13, + "memory_bytes": 30115103 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 5.62, + "memory_bytes": 16557015 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 38.93, + "memory_bytes": 179725926 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 22.4, + "memory_bytes": 30482104 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 23.22, + "memory_bytes": 30136074 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 10.54, + "memory_bytes": 30524047 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 25.0, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.79, + "memory_bytes": 16777216 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 25.16, + "memory_bytes": 191994266 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 15.87, + "memory_bytes": 30408704 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 23.78, + "memory_bytes": 30775706 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 15.84, + "memory_bytes": 30597448 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 24.7, + "memory_bytes": 30503076 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 10.96, + "memory_bytes": 16577987 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 34.16, + "memory_bytes": 195139994 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 9.7, + "memory_bytes": 30251418 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 4.04, + "memory_bytes": 30219960 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 9.25, + "memory_bytes": 40317747 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 24.68, + "memory_bytes": 30786191 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 3.89, + "memory_bytes": 16525558 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 10.99, + "memory_bytes": 194825421 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 14.09, + "memory_bytes": 40674263 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 9.8, + "memory_bytes": 30429676 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 14.59, + "memory_bytes": 40883978 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 26.4, + "memory_bytes": 43819991 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 5.55, + "memory_bytes": 16567501 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.84, + "memory_bytes": 199858586 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 23.45, + "memory_bytes": 30471619 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 10.46, + "memory_bytes": 39950746 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 25.3, + "memory_bytes": 43620762 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 22.69, + "memory_bytes": 30838620 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 5.75, + "memory_bytes": 16536044 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 33.78, + "memory_bytes": 201955738 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 15.97, + "memory_bytes": 30377247 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 9.64, + "memory_bytes": 30471619 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 25.4, + "memory_bytes": 43788534 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 18.75, + "memory_bytes": 30807163 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.05, + "memory_bytes": 16567501 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 19.53, + "memory_bytes": 203109171 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 16.37, + "memory_bytes": 30419190 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 9.67, + "memory_bytes": 30503076 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 20.58, + "memory_bytes": 41009807 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 21.43, + "memory_bytes": 30628905 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 6.21, + "memory_bytes": 16536044 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 22.25, + "memory_bytes": 202165453 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 25.09, + "memory_bytes": 43683676 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 8.03, + "memory_bytes": 30576476 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 7.95, + "memory_bytes": 30670848 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 21.67, + "memory_bytes": 30702305 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 5.85, + "memory_bytes": 16525558 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.66, + "memory_bytes": 203004314 + } + ] + } + ] + }, + { + "phase": "growth", + "api_replicas": 1, + "per_replica_cpu_limit": "1.0", + "per_replica_memory_limit": "512M", + "total_api_cpu_limit": 1.0, + "total_api_memory_limit_mib": 512, + "warmup_seconds": 5, + "baseline_row_counts": { + "users": 156, + "chats": 52, + "messages": 445522, + "sessions": 154, + "idempotency_records": 445522 + }, + "baseline_snapshot_sha256": "ddd62de0d9ba118508d4ee382c617927f5daa81f2acf769a5b49e67ac6e3db91", + "each_repetition_restored_same_baseline": true, + "repetitions": [ + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.039, + "concurrency": 16, + "successful_requests": 6333, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 210.824, + "successful_latency_ms": { + "p50": 80.103, + "p95": 114.112, + "p99": 182.734 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.25, + "memory_bytes": 44166021 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.37, + "memory_bytes": 16557015 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 20.9, + "memory_bytes": 143969485 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.59, + "memory_bytes": 31520195 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.61, + "memory_bytes": 22072525 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.27, + "memory_bytes": 143759770 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.71, + "memory_bytes": 31604081 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.37, + "memory_bytes": 16913531 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.31, + "memory_bytes": 143864627 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.44, + "memory_bytes": 31813796 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.98, + "memory_bytes": 16630415 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.17, + "memory_bytes": 143864627 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 108.41, + "memory_bytes": 31992054 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.68, + "memory_bytes": 16619930 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 15.69, + "memory_bytes": 144913203 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.53, + "memory_bytes": 32621199 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.86, + "memory_bytes": 16693330 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 19.36, + "memory_bytes": 144179200 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.97, + "memory_bytes": 31771853 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.79, + "memory_bytes": 16630415 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 15.72, + "memory_bytes": 144703488 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.7, + "memory_bytes": 32285655 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.24, + "memory_bytes": 16924017 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 15.31, + "memory_bytes": 144493773 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.83, + "memory_bytes": 32222740 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.46, + "memory_bytes": 16724787 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 21.24, + "memory_bytes": 148163789 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.073, + "concurrency": 16, + "successful_requests": 6325, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 210.32, + "successful_latency_ms": { + "p50": 79.313, + "p95": 117.188, + "p99": 183.607 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.33, + "memory_bytes": 44019220 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 6.15, + "memory_bytes": 16588472 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.03, + "memory_bytes": 143445197 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.84, + "memory_bytes": 31666995 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.12, + "memory_bytes": 16745759 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.18, + "memory_bytes": 144179200 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 107.22, + "memory_bytes": 37455135 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 11.27, + "memory_bytes": 16735273 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.3, + "memory_bytes": 143969485 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.43, + "memory_bytes": 31939625 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.68, + "memory_bytes": 16672358 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 15.0, + "memory_bytes": 144493773 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.94, + "memory_bytes": 32338084 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.09, + "memory_bytes": 16787702 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.61, + "memory_bytes": 143759770 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.07, + "memory_bytes": 31698452 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.65, + "memory_bytes": 16777216 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.38, + "memory_bytes": 143864627 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.38, + "memory_bytes": 32254198 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.28, + "memory_bytes": 16682844 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 15.4, + "memory_bytes": 143864627 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 103.09, + "memory_bytes": 31981568 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.67, + "memory_bytes": 17574134 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.81, + "memory_bytes": 144388915 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 107.3, + "memory_bytes": 32327598 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.44, + "memory_bytes": 16808673 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 14.38, + "memory_bytes": 144388915 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.03, + "concurrency": 16, + "successful_requests": 6422, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 213.855, + "successful_latency_ms": { + "p50": 79.164, + "p95": 114.738, + "p99": 181.052 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 102.67, + "memory_bytes": 30555505 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.68, + "memory_bytes": 16682844 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 19.21, + "memory_bytes": 148373504 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 105.57, + "memory_bytes": 31646024 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.49, + "memory_bytes": 16714301 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 26.54, + "memory_bytes": 163787571 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 108.53, + "memory_bytes": 32296141 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.79, + "memory_bytes": 17773363 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.2, + "memory_bytes": 145332634 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.46, + "memory_bytes": 45015368 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 8.12, + "memory_bytes": 17028874 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.18, + "memory_bytes": 145437491 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.84, + "memory_bytes": 31792824 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.29, + "memory_bytes": 17553162 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.0, + "memory_bytes": 145227776 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.81, + "memory_bytes": 32537313 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 9.17, + "memory_bytes": 16766730 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 17.03, + "memory_bytes": 145332634 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.08, + "memory_bytes": 45141197 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.97, + "memory_bytes": 18161336 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 18.93, + "memory_bytes": 145856922 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.82, + "memory_bytes": 31666995 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 10.31, + "memory_bytes": 17081303 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 16.33, + "memory_bytes": 145122918 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.32, + "memory_bytes": 31666995 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 7.88, + "memory_bytes": 17102275 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 15.49, + "memory_bytes": 145332634 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 0.33, + "memory_bytes": 31174164 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 0.29, + "memory_bytes": 16630415 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 11.58, + "memory_bytes": 145332634 + } + ] + } + ] + }, + { + "phase": "growth", + "api_replicas": 2, + "per_replica_cpu_limit": "1.0", + "per_replica_memory_limit": "512M", + "total_api_cpu_limit": 2.0, + "total_api_memory_limit_mib": 1024, + "warmup_seconds": 5, + "baseline_row_counts": { + "users": 156, + "chats": 52, + "messages": 445522, + "sessions": 154, + "idempotency_records": 445522 + }, + "baseline_snapshot_sha256": "ddd62de0d9ba118508d4ee382c617927f5daa81f2acf769a5b49e67ac6e3db91", + "each_repetition_restored_same_baseline": true, + "repetitions": [ + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.017, + "concurrency": 16, + "successful_requests": 18059, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 601.627, + "successful_latency_ms": { + "p50": 19.831, + "p95": 60.095, + "p99": 81.757 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 91.35, + "memory_bytes": 40663777 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 92.98, + "memory_bytes": 31247565 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 24.12, + "memory_bytes": 16798188 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 62.93, + "memory_bytes": 164102144 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 102.61, + "memory_bytes": 31247565 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 74.13, + "memory_bytes": 31205622 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 23.11, + "memory_bytes": 16861102 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 47.09, + "memory_bytes": 164102144 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 79.02, + "memory_bytes": 31153193 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 103.24, + "memory_bytes": 31132221 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 21.61, + "memory_bytes": 16861102 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 47.27, + "memory_bytes": 163892429 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 100.26, + "memory_bytes": 30817649 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 88.6, + "memory_bytes": 31142707 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 21.68, + "memory_bytes": 17186161 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 51.28, + "memory_bytes": 164311859 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 75.64, + "memory_bytes": 44186993 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 105.68, + "memory_bytes": 31635538 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 21.65, + "memory_bytes": 17448305 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 49.59, + "memory_bytes": 164102144 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 88.46, + "memory_bytes": 30859592 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 94.91, + "memory_bytes": 31341937 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 21.84, + "memory_bytes": 16913531 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 56.26, + "memory_bytes": 164626432 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 78.45, + "memory_bytes": 40789606 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 100.03, + "memory_bytes": 31153193 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 23.96, + "memory_bytes": 16934502 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 55.44, + "memory_bytes": 164207002 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 53.27, + "memory_bytes": 30985421 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 106.49, + "memory_bytes": 31436308 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 20.32, + "memory_bytes": 16997417 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 45.23, + "memory_bytes": 164416717 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 86.17, + "memory_bytes": 31027364 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 91.68, + "memory_bytes": 44910510 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 20.51, + "memory_bytes": 17553162 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 56.59, + "memory_bytes": 164521574 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.494, + "concurrency": 16, + "successful_requests": 18280, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 599.463, + "successful_latency_ms": { + "p50": 19.535, + "p95": 59.859, + "p99": 78.355 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.74, + "memory_bytes": 30932992 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 97.54, + "memory_bytes": 30765220 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 18.91, + "memory_bytes": 17532191 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 45.95, + "memory_bytes": 164102144 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 108.24, + "memory_bytes": 31090278 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 59.04, + "memory_bytes": 30817649 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 22.04, + "memory_bytes": 17479762 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 53.65, + "memory_bytes": 164521574 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 109.3, + "memory_bytes": 44438651 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 74.75, + "memory_bytes": 31289508 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 21.0, + "memory_bytes": 17039360 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 52.43, + "memory_bytes": 169030451 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 64.47, + "memory_bytes": 30912020 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 106.89, + "memory_bytes": 31016878 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 22.12, + "memory_bytes": 17102275 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 52.88, + "memory_bytes": 169135309 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 106.27, + "memory_bytes": 31027364 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 75.34, + "memory_bytes": 30765220 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 25.54, + "memory_bytes": 17846764 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 45.93, + "memory_bytes": 165465293 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 109.17, + "memory_bytes": 31446794 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 61.92, + "memory_bytes": 30775706 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 19.91, + "memory_bytes": 17395876 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 50.94, + "memory_bytes": 165989581 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 84.28, + "memory_bytes": 31782339 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 104.59, + "memory_bytes": 30786191 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 23.9, + "memory_bytes": 17081303 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 50.19, + "memory_bytes": 166094438 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 103.32, + "memory_bytes": 31205622 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 58.19, + "memory_bytes": 31016878 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 23.44, + "memory_bytes": 17154703 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 45.47, + "memory_bytes": 165884723 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 107.27, + "memory_bytes": 31016878 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 78.94, + "memory_bytes": 44417679 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 23.98, + "memory_bytes": 17175675 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 54.07, + "memory_bytes": 165989581 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.029, + "concurrency": 16, + "successful_requests": 18431, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 613.766, + "successful_latency_ms": { + "p50": 19.791, + "p95": 61.005, + "p99": 77.388 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 81.41, + "memory_bytes": 30607933 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 101.44, + "memory_bytes": 43956306 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 20.02, + "memory_bytes": 17291018 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 47.76, + "memory_bytes": 173015040 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 103.18, + "memory_bytes": 31195136 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 81.46, + "memory_bytes": 31719424 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 19.94, + "memory_bytes": 17343447 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 56.1, + "memory_bytes": 173119898 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 75.57, + "memory_bytes": 31132221 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 103.21, + "memory_bytes": 31824282 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 20.65, + "memory_bytes": 17427333 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 52.26, + "memory_bytes": 173539328 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 82.32, + "memory_bytes": 31740396 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 94.97, + "memory_bytes": 31299994 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 23.91, + "memory_bytes": 17437819 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 55.0, + "memory_bytes": 173329613 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 89.89, + "memory_bytes": 31174164 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 96.16, + "memory_bytes": 31593595 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 25.18, + "memory_bytes": 17196646 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 47.71, + "memory_bytes": 173958758 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 107.98, + "memory_bytes": 30995907 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 72.65, + "memory_bytes": 31006392 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 26.26, + "memory_bytes": 17175675 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 45.79, + "memory_bytes": 173958758 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 104.82, + "memory_bytes": 41701868 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 76.39, + "memory_bytes": 30974935 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 23.84, + "memory_bytes": 17731420 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 62.34, + "memory_bytes": 175741338 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 103.8, + "memory_bytes": 31362908 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 56.24, + "memory_bytes": 31048335 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 20.67, + "memory_bytes": 17228104 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 54.27, + "memory_bytes": 175846195 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 63.53, + "memory_bytes": 31488737 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 112.81, + "memory_bytes": 31383880 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 23.39, + "memory_bytes": 17458790 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 57.67, + "memory_bytes": 174797619 + } + ] + } + ] + }, + { + "phase": "growth", + "api_replicas": 4, + "per_replica_cpu_limit": "1.0", + "per_replica_memory_limit": "512M", + "total_api_cpu_limit": 4.0, + "total_api_memory_limit_mib": 2048, + "warmup_seconds": 5, + "baseline_row_counts": { + "users": 156, + "chats": 52, + "messages": 445522, + "sessions": 154, + "idempotency_records": 445522 + }, + "baseline_snapshot_sha256": "ddd62de0d9ba118508d4ee382c617927f5daa81f2acf769a5b49e67ac6e3db91", + "each_repetition_restored_same_baseline": true, + "repetitions": [ + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.012, + "concurrency": 16, + "successful_requests": 32846, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1094.415, + "successful_latency_ms": { + "p50": 10.732, + "p95": 30.846, + "p99": 51.188 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 44.38, + "memory_bytes": 30146560 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 66.67, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 63.19, + "memory_bytes": 30146560 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 48.9, + "memory_bytes": 30440161 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 16.26, + "memory_bytes": 17217618 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 96.23, + "memory_bytes": 194825421 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 57.62, + "memory_bytes": 30545019 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 55.37, + "memory_bytes": 30461133 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 60.08, + "memory_bytes": 30146560 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 55.07, + "memory_bytes": 30691820 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 39.36, + "memory_bytes": 17804820 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 107.53, + "memory_bytes": 205625754 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 51.72, + "memory_bytes": 30534533 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 69.2, + "memory_bytes": 30482104 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 68.76, + "memory_bytes": 30429676 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 57.81, + "memory_bytes": 30534533 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 36.93, + "memory_bytes": 17678991 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 96.49, + "memory_bytes": 212756070 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 71.03, + "memory_bytes": 30597448 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 72.23, + "memory_bytes": 30565990 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 52.55, + "memory_bytes": 30450647 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 69.93, + "memory_bytes": 43673190 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 37.47, + "memory_bytes": 17406362 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 99.35, + "memory_bytes": 212651213 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 51.75, + "memory_bytes": 30565990 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 59.49, + "memory_bytes": 30503076 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 59.28, + "memory_bytes": 43610276 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 60.48, + "memory_bytes": 30534533 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 30.82, + "memory_bytes": 17049846 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 95.16, + "memory_bytes": 218103808 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 66.97, + "memory_bytes": 43767562 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 69.56, + "memory_bytes": 30607933 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 50.43, + "memory_bytes": 30817649 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 64.03, + "memory_bytes": 43578819 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 37.64, + "memory_bytes": 17070817 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 101.11, + "memory_bytes": 218523238 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 41.87, + "memory_bytes": 30723277 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 62.34, + "memory_bytes": 30849106 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 62.69, + "memory_bytes": 30807163 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 40.17, + "memory_bytes": 30859592 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 36.7, + "memory_bytes": 17647534 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 108.47, + "memory_bytes": 232993587 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 52.79, + "memory_bytes": 30712791 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 53.63, + "memory_bytes": 30576476 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 55.4, + "memory_bytes": 30660362 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 55.73, + "memory_bytes": 40537948 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 40.37, + "memory_bytes": 17301504 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 105.42, + "memory_bytes": 216111514 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 71.04, + "memory_bytes": 31226593 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 71.0, + "memory_bytes": 30639391 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 72.37, + "memory_bytes": 30691820 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 52.3, + "memory_bytes": 30953964 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 37.05, + "memory_bytes": 17154703 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 100.06, + "memory_bytes": 216740659 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.013, + "concurrency": 16, + "successful_requests": 32672, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1088.609, + "successful_latency_ms": { + "p50": 11.145, + "p95": 30.074, + "p99": 53.423 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 63.93, + "memory_bytes": 30209475 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 62.59, + "memory_bytes": 30125588 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 64.58, + "memory_bytes": 30513562 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 57.17, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 31.39, + "memory_bytes": 17332961 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 89.67, + "memory_bytes": 210344346 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 57.4, + "memory_bytes": 30492590 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 56.1, + "memory_bytes": 30524047 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 59.17, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 65.08, + "memory_bytes": 41167094 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 40.95, + "memory_bytes": 17343447 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 93.72, + "memory_bytes": 218837811 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 67.48, + "memory_bytes": 30555505 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 55.47, + "memory_bytes": 30534533 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 69.81, + "memory_bytes": 30670848 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 48.58, + "memory_bytes": 30597448 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 38.31, + "memory_bytes": 17154703 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 95.05, + "memory_bytes": 224709837 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 50.14, + "memory_bytes": 30450647 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 67.6, + "memory_bytes": 43568333 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 51.32, + "memory_bytes": 30419190 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 56.46, + "memory_bytes": 30670848 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 35.73, + "memory_bytes": 17301504 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 104.16, + "memory_bytes": 224709837 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 56.87, + "memory_bytes": 30565990 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 56.91, + "memory_bytes": 30628905 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 61.07, + "memory_bytes": 30849106 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 55.08, + "memory_bytes": 30649876 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 32.66, + "memory_bytes": 17689477 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 106.33, + "memory_bytes": 224500122 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 59.2, + "memory_bytes": 42184212 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 69.82, + "memory_bytes": 30828134 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 60.32, + "memory_bytes": 41974497 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 66.66, + "memory_bytes": 30482104 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 33.38, + "memory_bytes": 17490248 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 90.39, + "memory_bytes": 225129267 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 55.76, + "memory_bytes": 30524047 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 57.6, + "memory_bytes": 30597448 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 58.39, + "memory_bytes": 30555505 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 56.12, + "memory_bytes": 30597448 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 32.67, + "memory_bytes": 17322476 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 106.33, + "memory_bytes": 224919552 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 66.36, + "memory_bytes": 30503076 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 67.73, + "memory_bytes": 30849106 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 68.39, + "memory_bytes": 30555505 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 59.12, + "memory_bytes": 30597448 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 43.62, + "memory_bytes": 17280532 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 89.59, + "memory_bytes": 225024410 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 45.79, + "memory_bytes": 30849106 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 45.61, + "memory_bytes": 30628905 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 48.46, + "memory_bytes": 30901535 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 44.99, + "memory_bytes": 30670848 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 32.2, + "memory_bytes": 17186161 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 105.64, + "memory_bytes": 230896435 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.015, + "concurrency": 16, + "successful_requests": 33502, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1116.177, + "successful_latency_ms": { + "p50": 11.142, + "p95": 28.815, + "p99": 49.26 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 65.99, + "memory_bytes": 30754734 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 61.27, + "memory_bytes": 30282875 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 49.54, + "memory_bytes": 30429676 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 35.51, + "memory_bytes": 30115103 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 16.33, + "memory_bytes": 16976445 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 55.98, + "memory_bytes": 195978854 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 53.73, + "memory_bytes": 30545019 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 58.81, + "memory_bytes": 40621834 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 69.41, + "memory_bytes": 43736105 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 51.72, + "memory_bytes": 30419190 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 35.78, + "memory_bytes": 17070817 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 93.04, + "memory_bytes": 216216371 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 53.11, + "memory_bytes": 30817649 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 50.57, + "memory_bytes": 30618419 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 50.18, + "memory_bytes": 30628905 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 63.83, + "memory_bytes": 30492590 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 35.98, + "memory_bytes": 17395876 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 98.03, + "memory_bytes": 222088397 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 59.09, + "memory_bytes": 30565990 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 54.35, + "memory_bytes": 30565990 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 69.74, + "memory_bytes": 42561700 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 56.45, + "memory_bytes": 30450647 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 39.31, + "memory_bytes": 17437819 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 106.07, + "memory_bytes": 221773824 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 69.8, + "memory_bytes": 30565990 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 50.49, + "memory_bytes": 30597448 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 49.31, + "memory_bytes": 30618419 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 50.68, + "memory_bytes": 30440161 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 37.26, + "memory_bytes": 17563648 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 98.52, + "memory_bytes": 222193254 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 55.5, + "memory_bytes": 40254833 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 69.42, + "memory_bytes": 30597448 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 69.2, + "memory_bytes": 30618419 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 50.97, + "memory_bytes": 34823209 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 35.6, + "memory_bytes": 17186161 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 107.15, + "memory_bytes": 222507827 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 82.4, + "memory_bytes": 31163679 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 54.98, + "memory_bytes": 30618419 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 51.35, + "memory_bytes": 30681334 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 73.92, + "memory_bytes": 30838620 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 39.29, + "memory_bytes": 17500733 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 95.75, + "memory_bytes": 222402970 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 51.63, + "memory_bytes": 30607933 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 68.28, + "memory_bytes": 30891049 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 70.39, + "memory_bytes": 30660362 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 50.9, + "memory_bytes": 30534533 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 36.79, + "memory_bytes": 17783849 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 95.09, + "memory_bytes": 222507827 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 52.87, + "memory_bytes": 40747663 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 52.8, + "memory_bytes": 30922506 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 52.17, + "memory_bytes": 30670848 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 58.56, + "memory_bytes": 31100764 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 37.86, + "memory_bytes": 17553162 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 99.34, + "memory_bytes": 223451546 + } + ] + } + ] + }, + { + "phase": "growth", + "api_replicas": 8, + "per_replica_cpu_limit": "1.0", + "per_replica_memory_limit": "512M", + "total_api_cpu_limit": 8.0, + "total_api_memory_limit_mib": 4096, + "warmup_seconds": 5, + "baseline_row_counts": { + "users": 156, + "chats": 52, + "messages": 445522, + "sessions": 154, + "idempotency_records": 445522 + }, + "baseline_snapshot_sha256": "ddd62de0d9ba118508d4ee382c617927f5daa81f2acf769a5b49e67ac6e3db91", + "each_repetition_restored_same_baseline": true, + "repetitions": [ + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.033, + "concurrency": 16, + "successful_requests": 34199, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1138.726, + "successful_latency_ms": { + "p50": 11.784, + "p95": 29.272, + "p99": 38.508 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 44.26, + "memory_bytes": 29978788 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 17.48, + "memory_bytes": 29947331 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 24.74, + "memory_bytes": 30115103 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 25.54, + "memory_bytes": 30125588 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 26.18, + "memory_bytes": 30261903 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 45.17, + "memory_bytes": 29999759 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 45.49, + "memory_bytes": 30157046 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 25.89, + "memory_bytes": 29989274 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 35.54, + "memory_bytes": 17259561 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 104.67, + "memory_bytes": 216530944 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 25.98, + "memory_bytes": 30136074 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 26.92, + "memory_bytes": 29999759 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 26.82, + "memory_bytes": 30104617 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 37.31, + "memory_bytes": 30125588 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 44.67, + "memory_bytes": 30083645 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 26.87, + "memory_bytes": 30031217 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 25.73, + "memory_bytes": 30261903 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 27.28, + "memory_bytes": 30062674 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 35.87, + "memory_bytes": 17532191 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 103.75, + "memory_bytes": 229113856 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 49.17, + "memory_bytes": 30167532 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 41.91, + "memory_bytes": 43033559 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 26.44, + "memory_bytes": 30230446 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 25.87, + "memory_bytes": 30178017 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 24.24, + "memory_bytes": 30125588 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 49.43, + "memory_bytes": 30115103 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 46.29, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 25.53, + "memory_bytes": 30062674 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 34.88, + "memory_bytes": 17291018 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 102.46, + "memory_bytes": 231735296 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 26.66, + "memory_bytes": 30461133 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 43.87, + "memory_bytes": 30125588 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 44.1, + "memory_bytes": 30251418 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 42.46, + "memory_bytes": 30230446 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 45.06, + "memory_bytes": 30282875 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 27.79, + "memory_bytes": 30482104 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 25.64, + "memory_bytes": 30251418 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 27.28, + "memory_bytes": 30198989 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 37.34, + "memory_bytes": 17133732 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 104.39, + "memory_bytes": 242116198 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 47.08, + "memory_bytes": 30167532 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 47.06, + "memory_bytes": 30146560 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 27.02, + "memory_bytes": 30293361 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 43.11, + "memory_bytes": 41796239 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 28.08, + "memory_bytes": 30356275 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 52.29, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 32.98, + "memory_bytes": 30524047 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 46.29, + "memory_bytes": 30282875 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 38.66, + "memory_bytes": 17039360 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 104.74, + "memory_bytes": 244318208 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 26.04, + "memory_bytes": 30429676 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 27.06, + "memory_bytes": 30146560 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 44.44, + "memory_bytes": 30314332 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 46.93, + "memory_bytes": 30482104 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 46.5, + "memory_bytes": 30356275 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 27.78, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 26.6, + "memory_bytes": 30219960 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 30.96, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 39.14, + "memory_bytes": 16976445 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 105.4, + "memory_bytes": 246625075 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 45.81, + "memory_bytes": 30198989 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 44.36, + "memory_bytes": 30198989 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 25.59, + "memory_bytes": 30261903 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 29.29, + "memory_bytes": 39625687 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 26.28, + "memory_bytes": 30324818 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 45.35, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 41.0, + "memory_bytes": 30261903 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 47.14, + "memory_bytes": 30513562 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 38.64, + "memory_bytes": 17028874 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 101.12, + "memory_bytes": 245366784 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 22.92, + "memory_bytes": 30198989 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 23.57, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 41.17, + "memory_bytes": 30324818 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 22.96, + "memory_bytes": 30261903 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 40.69, + "memory_bytes": 30387732 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 22.75, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 38.13, + "memory_bytes": 43557847 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 23.26, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 38.57, + "memory_bytes": 17060332 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 101.56, + "memory_bytes": 251763098 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 44.64, + "memory_bytes": 30366761 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 44.74, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 25.93, + "memory_bytes": 30419190 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 24.97, + "memory_bytes": 30356275 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 24.65, + "memory_bytes": 30398218 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 45.19, + "memory_bytes": 30314332 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 46.67, + "memory_bytes": 30282875 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 44.47, + "memory_bytes": 30398218 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 35.02, + "memory_bytes": 17081303 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 105.96, + "memory_bytes": 254069965 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.015, + "concurrency": 16, + "successful_requests": 35418, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1180.016, + "successful_latency_ms": { + "p50": 11.711, + "p95": 26.361, + "p99": 36.002 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 37.61, + "memory_bytes": 30293361 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 43.02, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 16.44, + "memory_bytes": 29957816 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 23.71, + "memory_bytes": 30251418 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 16.99, + "memory_bytes": 29978788 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 26.42, + "memory_bytes": 30031217 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 24.85, + "memory_bytes": 29905388 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 34.59, + "memory_bytes": 42939187 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 23.9, + "memory_bytes": 16997417 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 85.42, + "memory_bytes": 208561766 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 26.6, + "memory_bytes": 30188503 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 26.36, + "memory_bytes": 30261903 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 45.35, + "memory_bytes": 30209475 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 39.79, + "memory_bytes": 30083645 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 46.87, + "memory_bytes": 30261903 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 26.84, + "memory_bytes": 30440161 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 26.85, + "memory_bytes": 30293361 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 27.26, + "memory_bytes": 30136074 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 36.14, + "memory_bytes": 17049846 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 104.15, + "memory_bytes": 223451546 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 26.14, + "memory_bytes": 30723277 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 28.63, + "memory_bytes": 39678116 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 26.04, + "memory_bytes": 30198989 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 45.48, + "memory_bytes": 30482104 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 26.88, + "memory_bytes": 30052188 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 27.04, + "memory_bytes": 30219960 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 46.49, + "memory_bytes": 30115103 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 47.68, + "memory_bytes": 30094131 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 39.56, + "memory_bytes": 17353933 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 104.3, + "memory_bytes": 236558746 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 48.03, + "memory_bytes": 30524047 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 44.64, + "memory_bytes": 43683676 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 36.87, + "memory_bytes": 30482104 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 27.69, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 44.86, + "memory_bytes": 30073160 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 45.1, + "memory_bytes": 30219960 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 27.02, + "memory_bytes": 30167532 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 27.79, + "memory_bytes": 30125588 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 37.82, + "memory_bytes": 17133732 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 103.85, + "memory_bytes": 239914189 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 28.1, + "memory_bytes": 30282875 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 27.09, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 44.75, + "memory_bytes": 30282875 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 45.72, + "memory_bytes": 30356275 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 46.11, + "memory_bytes": 30251418 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 30.26, + "memory_bytes": 40013660 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 28.11, + "memory_bytes": 34812723 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 28.08, + "memory_bytes": 30167532 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 36.82, + "memory_bytes": 17469276 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 103.54, + "memory_bytes": 240753050 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 44.81, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 47.74, + "memory_bytes": 30261903 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 27.41, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 26.21, + "memory_bytes": 30314332 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 27.4, + "memory_bytes": 30219960 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 41.12, + "memory_bytes": 30786191 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 27.32, + "memory_bytes": 30471619 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 26.8, + "memory_bytes": 30482104 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 40.47, + "memory_bytes": 17081303 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 104.18, + "memory_bytes": 244737638 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 27.41, + "memory_bytes": 30261903 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 26.86, + "memory_bytes": 30251418 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 46.27, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 44.83, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 43.85, + "memory_bytes": 30198989 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 44.32, + "memory_bytes": 43463475 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 32.07, + "memory_bytes": 30303846 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 27.36, + "memory_bytes": 30419190 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 37.97, + "memory_bytes": 17154703 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 102.3, + "memory_bytes": 248093082 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 40.59, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 45.63, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 44.13, + "memory_bytes": 30534533 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 28.7, + "memory_bytes": 39877345 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 27.62, + "memory_bytes": 30534533 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 26.64, + "memory_bytes": 30303846 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 45.38, + "memory_bytes": 30314332 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 45.94, + "memory_bytes": 30146560 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 38.36, + "memory_bytes": 17668506 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 104.95, + "memory_bytes": 250399949 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 27.61, + "memory_bytes": 30230446 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 27.67, + "memory_bytes": 30356275 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 45.95, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 45.26, + "memory_bytes": 30607933 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 50.8, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 31.1, + "memory_bytes": 40370176 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 37.04, + "memory_bytes": 30303846 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 26.59, + "memory_bytes": 30136074 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 40.39, + "memory_bytes": 17144218 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 102.56, + "memory_bytes": 252497101 + } + ] + }, + { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.012, + "concurrency": 16, + "successful_requests": 34848, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1161.122, + "successful_latency_ms": { + "p50": 11.745, + "p95": 28.074, + "p99": 36.688 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.", + "resource_samples": [ + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 25.43, + "memory_bytes": 29999759 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 46.49, + "memory_bytes": 30125588 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 25.49, + "memory_bytes": 30167532 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 39.27, + "memory_bytes": 30094131 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 37.81, + "memory_bytes": 41680896 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 25.63, + "memory_bytes": 30607933 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 43.17, + "memory_bytes": 29968302 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 42.81, + "memory_bytes": 29999759 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 34.94, + "memory_bytes": 17039360 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 104.41, + "memory_bytes": 213385216 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 26.54, + "memory_bytes": 30094131 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 25.53, + "memory_bytes": 30157046 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 44.23, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 45.27, + "memory_bytes": 43421532 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 27.09, + "memory_bytes": 30178017 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 43.39, + "memory_bytes": 30083645 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 26.2, + "memory_bytes": 30020731 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 43.69, + "memory_bytes": 30115103 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 36.89, + "memory_bytes": 17343447 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 105.14, + "memory_bytes": 226702131 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 26.92, + "memory_bytes": 30146560 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 45.93, + "memory_bytes": 30198989 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 26.07, + "memory_bytes": 30565990 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 26.17, + "memory_bytes": 30293361 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 46.62, + "memory_bytes": 30230446 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 38.28, + "memory_bytes": 42593157 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 24.67, + "memory_bytes": 30062674 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 48.54, + "memory_bytes": 30408704 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 34.32, + "memory_bytes": 17112760 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 101.1, + "memory_bytes": 239494758 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 27.92, + "memory_bytes": 30576476 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 28.89, + "memory_bytes": 30240932 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 43.83, + "memory_bytes": 30314332 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 46.71, + "memory_bytes": 30293361 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 27.33, + "memory_bytes": 30450647 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 27.7, + "memory_bytes": 30125588 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 47.96, + "memory_bytes": 30492590 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 28.15, + "memory_bytes": 30450647 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 38.99, + "memory_bytes": 17238589 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 105.96, + "memory_bytes": 244632781 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 41.07, + "memory_bytes": 30303846 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 25.32, + "memory_bytes": 30230446 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 41.0, + "memory_bytes": 43631247 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 27.2, + "memory_bytes": 30293361 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 38.51, + "memory_bytes": 42771415 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 45.87, + "memory_bytes": 30314332 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 25.99, + "memory_bytes": 30303846 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 25.78, + "memory_bytes": 30251418 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 37.97, + "memory_bytes": 17112760 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 105.45, + "memory_bytes": 259312845 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 27.04, + "memory_bytes": 30314332 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 47.15, + "memory_bytes": 43421532 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 24.94, + "memory_bytes": 30303846 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 46.86, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 26.04, + "memory_bytes": 30408704 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 26.37, + "memory_bytes": 30314332 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 50.2, + "memory_bytes": 30576476 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 41.02, + "memory_bytes": 43316675 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 38.18, + "memory_bytes": 17395876 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 105.64, + "memory_bytes": 259417702 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 42.29, + "memory_bytes": 42026926 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 25.95, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 44.27, + "memory_bytes": 30324818 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 34.33, + "memory_bytes": 40642806 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 27.19, + "memory_bytes": 30932992 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 45.13, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 25.67, + "memory_bytes": 30565990 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 25.93, + "memory_bytes": 30272389 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 36.63, + "memory_bytes": 17112760 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 103.63, + "memory_bytes": 259522560 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 46.42, + "memory_bytes": 30366761 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 44.64, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 44.33, + "memory_bytes": 30366761 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 26.46, + "memory_bytes": 30345789 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 46.7, + "memory_bytes": 30691820 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 26.13, + "memory_bytes": 30387732 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 38.66, + "memory_bytes": 30366761 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 44.76, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 36.87, + "memory_bytes": 17427333 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 101.27, + "memory_bytes": 262039142 + }, + { + "container": "mtusi2026lab3-api-11", + "service": "api", + "cpu_percent": 39.97, + "memory_bytes": 30335304 + }, + { + "container": "mtusi2026lab3-api-12", + "service": "api", + "cpu_percent": 30.14, + "memory_bytes": 30293361 + }, + { + "container": "mtusi2026lab3-api-13", + "service": "api", + "cpu_percent": 46.49, + "memory_bytes": 30377247 + }, + { + "container": "mtusi2026lab3-api-14", + "service": "api", + "cpu_percent": 32.56, + "memory_bytes": 40223375 + }, + { + "container": "mtusi2026lab3-api-15", + "service": "api", + "cpu_percent": 29.91, + "memory_bytes": 30429676 + }, + { + "container": "mtusi2026lab3-api-16", + "service": "api", + "cpu_percent": 43.94, + "memory_bytes": 30387732 + }, + { + "container": "mtusi2026lab3-api-17", + "service": "api", + "cpu_percent": 28.25, + "memory_bytes": 30398218 + }, + { + "container": "mtusi2026lab3-api-18", + "service": "api", + "cpu_percent": 26.14, + "memory_bytes": 30293361 + }, + { + "container": "mtusi2026lab3-load_balancer-1", + "service": "load_balancer", + "cpu_percent": 39.77, + "memory_bytes": 17416847 + }, + { + "container": "mtusi2026lab3-postgres-1", + "service": "postgres", + "cpu_percent": 105.88, + "memory_bytes": 264870298 + } + ] + } + ] + } + ] +} diff --git a/evidence/track1/throughput.svg b/evidence/track1/throughput.svg new file mode 100644 index 0000000..726cdb5 --- /dev/null +++ b/evidence/track1/throughput.svg @@ -0,0 +1,26 @@ + + +API scaling: average successful RPS + + +212.5 +fixed / 1 + +212.7 +fixed / 2 + +156.3 +fixed / 4 + +211.7 +growth / 1 + +605.0 +growth / 2 + +1099.7 +growth / 4 + +1160.0 +growth / 8 + diff --git a/examples/requests.http b/examples/requests.http new file mode 100644 index 0000000..492f938 --- /dev/null +++ b/examples/requests.http @@ -0,0 +1,46 @@ +# Optional HTTP-client worksheet; no extension is required by the course. +# Replace IDs/token locally from real responses; do not commit filled-in credentials. +# Canonical API: contracts/openapi.json and contracts/README.md. +@baseUrl = http://localhost:8080 +@aliceId = REPLACE_WITH_CREATED_ALICE_UUID +@bobId = REPLACE_WITH_CREATED_BOB_UUID +@chatId = REPLACE_WITH_CREATED_CHAT_UUID +@sessionToken = REPLACE_LOCALLY_DO_NOT_COMMIT + +### Liveness +GET {{baseUrl}}/health/live + +### Register Alice (repeat with username bob/display_name Боб) +POST {{baseUrl}}/api/v1/users +Content-Type: application/json + +{ + "username": "alice", + "display_name": "Алиса", + "password": "Example-only-not-a-real-secret-123" +} + +### Create session: generate the Base64 value locally, do not commit credentials +# Base64 of UTF-8 username:password; only this endpoint accepts Basic. +POST {{baseUrl}}/api/v1/auth/sessions +Authorization: Basic REPLACE_WITH_LOCAL_BASE64_CREDENTIAL + + +### Create chat; both UUIDs must be real registered users +POST {{baseUrl}}/api/v1/chats +Authorization: Bearer {{sessionToken}} +Content-Type: application/json + +{"title":"Проект по ВНП","member_ids":["{{aliceId}}","{{bobId}}"]} + +### Send message +POST {{baseUrl}}/api/v1/chats/{{chatId}}/messages +Authorization: Bearer {{sessionToken}} +Idempotency-Key: example-message-001 +Content-Type: application/json + +{"text":"Привет, Боб!"} + +### Read first page +GET {{baseUrl}}/api/v1/chats/{{chatId}}/messages?limit=50 +Authorization: Bearer {{sessionToken}} diff --git a/haproxy.cfg b/haproxy.cfg new file mode 100644 index 0000000..9dedf30 --- /dev/null +++ b/haproxy.cfg @@ -0,0 +1,35 @@ +global + log stdout format raw local0 + maxconn 1024 + +defaults + log global + mode http + option httplog + option http-keep-alive + timeout connect 2s + timeout client 15s + timeout server 15s + timeout http-request 5s + timeout check 1s + retries 2 + +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 2s + hold nx 2s + +frontend messenger + bind :8080 + default_backend api_replicas + +backend api_replicas + balance roundrobin + option httpchk GET /health/ready + http-check expect status 200 + option redispatch + default-server inter 1s fall 2 rise 2 + server-template api 1-10 api:8080 check resolvers docker resolve-prefer ipv4 init-addr libc,none diff --git a/infra/README.md b/infra/README.md new file mode 100644 index 0000000..5a39e86 --- /dev/null +++ b/infra/README.md @@ -0,0 +1,7 @@ +# Инфраструктура студента + +Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли. + +В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд. + +Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику. diff --git a/lab.json b/lab.json new file mode 100644 index 0000000..57bb9fb --- /dev/null +++ b/lab.json @@ -0,0 +1,8 @@ +{ + "number": 3, + "title": "Балансировка и отказ API-реплики", + "contract_version": "1.3.0", + "default_base_url": "http://localhost:8080", + "grading": "3; 4 includes 3; 5 includes 4 plus one completed research track", + "scaffold_has_application": false +} diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 0000000..f5431a5 --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,43 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + username varchar(32) NOT NULL UNIQUE, + display_name varchar(100) NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + title varchar(100) NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + joined_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (chat_id, user_id) +); + +CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + text varchar(4000) NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT messages_text_not_blank CHECK (length(btrim(text)) > 0) +); + +CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id); + +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + expires_at timestamptz NOT NULL, + CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at) +); + +CREATE INDEX sessions_expiry_idx ON sessions (expires_at); diff --git a/migrations/002_idempotency.sql b/migrations/002_idempotency.sql new file mode 100644 index 0000000..aae5c1a --- /dev/null +++ b/migrations/002_idempotency.sql @@ -0,0 +1,16 @@ +CREATE TABLE idempotency_records ( + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + method varchar(8) NOT NULL, + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + idempotency_key varchar(128) NOT NULL, + request_hash bytea NOT NULL, + response jsonb NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + expires_at timestamptz NOT NULL, + PRIMARY KEY (user_id, method, chat_id, idempotency_key), + CONSTRAINT idempotency_method_post CHECK (method = 'POST'), + CONSTRAINT idempotency_hash_sha256 CHECK (octet_length(request_hash) = 32), + CONSTRAINT idempotency_expiry_after_creation CHECK (expires_at > created_at) +); + +CREATE INDEX idempotency_records_expiry_idx ON idempotency_records (expires_at); diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..6b103dd --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,2 @@ +# Only for full OpenAPI/JSON Schema validation; HTTP tests use stdlib. +openapi-spec-validator==0.7.2 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..177a977 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +psycopg[binary]==3.2.10 +psycopg-pool==3.3.3 +redis==5.2.1 diff --git a/scripts/bootstrap-secrets.sh b/scripts/bootstrap-secrets.sh new file mode 100755 index 0000000..811b13c --- /dev/null +++ b/scripts/bootstrap-secrets.sh @@ -0,0 +1,27 @@ +#!/bin/sh +set -eu + +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +SECRETS_DIR="$ROOT/secrets" +PASSWORD_FILE="$SECRETS_DIR/postgres_password" +DATABASE_URL_FILE="$SECRETS_DIR/database_url" + +if [ -e "$PASSWORD_FILE" ] || [ -e "$DATABASE_URL_FILE" ]; then + printf '%s\n' 'Secret files already exist; refusing to overwrite them.' >&2 + exit 1 +fi + +command -v openssl >/dev/null 2>&1 || { + printf '%s\n' 'openssl is required to generate local credentials.' >&2 + exit 1 +} + +mkdir -p "$SECRETS_DIR" +chmod 700 "$SECRETS_DIR" +umask 077 +password=$(openssl rand -hex 32) +printf '%s' "$password" > "$PASSWORD_FILE" +printf 'postgresql://messenger:%s@postgres:5432/messenger' "$password" > "$DATABASE_URL_FILE" +chmod 644 "$PASSWORD_FILE" "$DATABASE_URL_FILE" +unset password +printf '%s\n' 'Local PostgreSQL secret files created.' diff --git a/scripts/check_contract.py b/scripts/check_contract.py new file mode 100644 index 0000000..dcb34df --- /dev/null +++ b/scripts/check_contract.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Offline structural checks; full schema validation is a separate target.""" +import ast +import json +from pathlib import Path +import re + +ROOT = Path(__file__).resolve().parents[1] + +def main(): + lab = json.loads((ROOT/'lab.json').read_text())['number'] + spec = json.loads((ROOT/'contracts/openapi.json').read_text()) + assert spec['openapi']=='3.1.0' + assert spec['info']['version']=='1.%d.0'%lab + operation_ids = set() + def walk(value): + if isinstance(value,dict): + if '$ref' in value: + pointer = value['$ref'] + assert pointer.startswith('#/'), 'unexpected external reference' + target = spec + for part in pointer[2:].split('/'): + target = target[part.replace('~1','/').replace('~0','~')] + for v in value.values(): + walk(v) + elif isinstance(value,list): + for v in value: + walk(v) + walk(spec) + for route,methods in spec['paths'].items(): + placeholders = set(re.findall(r'\{([^}]+)\}',route)) + for method,op in methods.items(): + assert op['operationId'] not in operation_ids, 'duplicate operationId' + operation_ids.add(op['operationId']) + params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')} + assert placeholders==params, 'path parameter mismatch: '+route + for response in op['responses'].values(): + assert 'X-Request-Id' in response['headers'] + if lab>=3: + assert 'X-Instance-Id' in response['headers'] + assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2) + assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4) + for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')): + ast.parse(file.read_text(),filename=str(file)) + for file in ROOT.rglob('*.json'): + if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts): + continue + json.loads(file.read_text()) + for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'): + assert (ROOT/required).is_file(), 'missing '+required + print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.') + +if __name__=='__main__': + main() diff --git a/scripts/restart.example.sh b/scripts/restart.example.sh new file mode 100755 index 0000000..967e951 --- /dev/null +++ b/scripts/restart.example.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +# TODO: copy to restart.sh and implement using YOUR compose/stack services. +# Restart API and ALL used state stores (DB, sessions, S3, broker as applicable). +# Preserve persistent volumes and schema/data; never down -v / flush / re-seed. +# Allow operator unseal if required in lab7; do not print credentials. +# Exit 0 only after the intended action; test waits for API readiness separately. +printf '%s +' 'TODO: implement restart.sh for your infrastructure' >&2 +exit 2 diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 0000000..08e2218 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu + +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +cd "$ROOT" + +docker compose --env-file .env restart postgres +docker compose --env-file .env up -d --wait --wait-timeout 60 postgres +docker compose --env-file .env restart api load_balancer diff --git a/scripts/rolling-restart.sh b/scripts/rolling-restart.sh new file mode 100755 index 0000000..3d55038 --- /dev/null +++ b/scripts/rolling-restart.sh @@ -0,0 +1,35 @@ +#!/bin/sh +set -eu + +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +cd "$ROOT" + +docker compose --env-file .env up -d --scale api=2 --wait --wait-timeout 60 +containers=$(docker compose --env-file .env ps -q api) +if [ -z "$containers" ]; then + printf '%s\n' 'No running API containers found.' >&2 + exit 1 +fi + +for container in $containers; do + docker stop --time 15 "$container" >/dev/null + docker start "$container" >/dev/null + attempts=0 + while [ "$attempts" -lt 40 ]; do + state=$(docker inspect --format '{{.State.Health.Status}}' "$container") + if [ "$state" = healthy ]; then + printf 'PASS: API container %s restarted and is healthy\n' "$container" + break + fi + if [ "$state" = unhealthy ] || [ "$state" = none ]; then + printf 'API container %s failed health check (state: %s)\n' "$container" "$state" >&2 + exit 1 + fi + attempts=$((attempts + 1)) + sleep 1 + done + if [ "$attempts" -eq 40 ]; then + printf 'API container %s did not become healthy in 40 seconds\n' "$container" >&2 + exit 1 + fi +done diff --git a/scripts/stop-one.example.sh b/scripts/stop-one.example.sh new file mode 100755 index 0000000..ae149e8 --- /dev/null +++ b/scripts/stop-one.example.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +# TODO: copy to stop-one.sh, map TARGET_INSTANCE_ID to ONE API container/task. +# Stop that instance and leave it stopped; no stop of DB/LB/volumes. +# Return quickly (within 10 s); the test sends requests during this script. +# Restore the replica explicitly after the test. Never print credentials. +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +printf '%s +' 'TODO: implement stop-one.sh for your infrastructure' >&2 +exit 2 diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 0000000..5518062 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,32 @@ +#!/bin/sh +set -eu + +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +cd "$ROOT" + +target_container= +for container in $(docker compose --env-file .env ps -q api); do + hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container") + if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then + target_container=$container + break + fi +done + +if [ -z "$target_container" ]; then + printf '%s\n' 'No running API container matches TARGET_INSTANCE_ID.' >&2 + exit 1 +fi + +if [ -n "${FAILOVER_EVIDENCE_FILE:-}" ]; then + case "$FAILOVER_EVIDENCE_FILE" in + /*) evidence_file=$FAILOVER_EVIDENCE_FILE ;; + *) evidence_file="$ROOT/$FAILOVER_EVIDENCE_FILE" ;; + esac + printf '%s target_instance=%s container=%s\n' \ + "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$TARGET_INSTANCE_ID" "$target_container" \ + >> "$evidence_file" +fi + +docker stop --time 2 "$target_container" >/dev/null diff --git a/scripts/validate_openapi.py b/scripts/validate_openapi.py new file mode 100644 index 0000000..1dfe4a9 --- /dev/null +++ b/scripts/validate_openapi.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""Full OpenAPI and JSON Schema checks; install requirements-dev.txt first.""" +import json +from pathlib import Path +from openapi_spec_validator import validate +from jsonschema import Draft202012Validator + +root = Path(__file__).resolve().parents[1] +spec = json.loads((root/'contracts/openapi.json').read_text()) +validate(spec) +from referencing import Registry, Resource +# The base URI resolves local #/components references inside examples. +resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'}) +registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource)) +for name, example in json.loads((root/'contracts/examples.json').read_text()).items(): + schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name} + Draft202012Validator(schema, registry=registry).validate(example) +for path in (root/'contracts').glob('*.schema.json'): + schema = json.loads(path.read_text()) + Draft202012Validator.check_schema(schema) + for example in schema.get('examples',[]): + Draft202012Validator(schema).validate(example) +print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.') diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..5bc8da3 --- /dev/null +++ b/src/__init__.py @@ -0,0 +1 @@ +"""Messenger API application package.""" diff --git a/src/app.py b/src/app.py new file mode 100644 index 0000000..d5229ba --- /dev/null +++ b/src/app.py @@ -0,0 +1,39 @@ +import logging +import os +import signal +import threading +from functools import partial +from http.server import ThreadingHTTPServer + +from .config import APP_HOST, APP_PORT +from .handlers import MessengerHandler +from .store import Store + +LOGGER = logging.getLogger("messenger") + + +def run_server(): + store = Store() + store.open() + try: + handler = partial(MessengerHandler, store=store) + server = ThreadingHTTPServer((APP_HOST, APP_PORT), handler) + + def handle_shutdown(signum, frame): + LOGGER.info("received signal %s, shutting down gracefully", signum) + threading.Thread(target=server.shutdown, daemon=True).start() + + signal.signal(signal.SIGTERM, handle_shutdown) + signal.signal(signal.SIGINT, handle_shutdown) + LOGGER.info("listening on %s:%s", APP_HOST, APP_PORT) + try: + server.serve_forever() + finally: + server.server_close() + finally: + store.close() + + +def main(): + logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO")) + run_server() diff --git a/src/config.py b/src/config.py new file mode 100644 index 0000000..419b28a --- /dev/null +++ b/src/config.py @@ -0,0 +1,29 @@ +import os +import re +import socket +import uuid + +APP_HOST = os.getenv("APP_HOST", "0.0.0.0") +APP_PORT = int(os.getenv("APP_PORT", "8080")) +INSTANCE_ID = os.getenv("INSTANCE_ID", socket.gethostname() or uuid.uuid4().hex[:12]) +SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600")) +IDEMPOTENCY_TTL_SECONDS = int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400")) +DB_STATEMENT_TIMEOUT_MS = int(os.getenv("DB_STATEMENT_TIMEOUT_MS", "5000")) +DB_LOCK_TIMEOUT_MS = int(os.getenv("DB_LOCK_TIMEOUT_MS", "2000")) +DB_POOL_MAX_SIZE = int(os.getenv("DB_POOL_MAX_SIZE", "16")) +DB_POOL_TIMEOUT_SECONDS = float(os.getenv("DB_POOL_TIMEOUT_SECONDS", "5")) +MAX_INFLIGHT_REQUESTS = int(os.getenv("MAX_INFLIGHT_REQUESTS", "128")) +MAX_REQUEST_BODY_BYTES = int(os.getenv("MAX_REQUEST_BODY_BYTES", "1048576")) +USER_RE = re.compile(r"^[a-z0-9_]{3,32}$") +IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") + +if SESSION_TTL_SECONDS < 1: + raise RuntimeError("SESSION_TTL_SECONDS must be positive") +if IDEMPOTENCY_TTL_SECONDS < 86400: + raise RuntimeError("IDEMPOTENCY_TTL_SECONDS must be at least 86400") +if DB_STATEMENT_TIMEOUT_MS < 1 or DB_LOCK_TIMEOUT_MS < 1: + raise RuntimeError("Database timeouts must be positive") +if DB_POOL_MAX_SIZE < 1 or DB_POOL_TIMEOUT_SECONDS <= 0: + raise RuntimeError("Database pool settings must be positive") +if MAX_INFLIGHT_REQUESTS < 1 or MAX_REQUEST_BODY_BYTES < 1: + raise RuntimeError("HTTP limits must be positive") diff --git a/src/errors.py b/src/errors.py new file mode 100644 index 0000000..35cffe6 --- /dev/null +++ b/src/errors.py @@ -0,0 +1,18 @@ +from typing import Dict, Optional + + +class ApiError(Exception): + def __init__(self, status: int, code: str, message: str, headers: Optional[Dict[str, str]] = None): + super().__init__(message) + self.status = status + self.code = code + self.message = message + self.headers = headers or {} + + +class CacheUnavailableError(Exception): + pass + + +class IdempotencyConflictError(Exception): + pass diff --git a/src/handlers.py b/src/handlers.py new file mode 100644 index 0000000..8a3adff --- /dev/null +++ b/src/handlers.py @@ -0,0 +1,350 @@ +import base64 +import json +import logging +import threading +import uuid +from http.server import BaseHTTPRequestHandler +from typing import Any, Dict, List, Optional, Tuple +from urllib.parse import parse_qs, urlsplit + +import psycopg +from psycopg_pool import PoolTimeout + +from .config import ( + IDEMPOTENCY_KEY_RE, + INSTANCE_ID, + MAX_INFLIGHT_REQUESTS, + MAX_REQUEST_BODY_BYTES, + USER_RE, +) +from .errors import ApiError, CacheUnavailableError, IdempotencyConflictError +from .security import hash_password, isoformat, valid_uuid +from .store import Store + +LOGGER = logging.getLogger("messenger.http") + + +class RequestGuard: + def __init__(self): + self.lock = threading.Lock() + self.inflight = 0 + + def acquire(self): + with self.lock: + if self.inflight >= MAX_INFLIGHT_REQUESTS: + raise ApiError(503, "unavailable", "Server is busy") + self.inflight += 1 + + def release(self): + with self.lock: + self.inflight = max(0, self.inflight - 1) + + +REQUEST_GUARD = RequestGuard() + + +class MessengerHandler(BaseHTTPRequestHandler): + def __init__(self, request, client_address, server, store: Store): + self.store = store + super().__init__(request, client_address, server) + + def log_message(self, format: str, *args): + return + + def do_GET(self): + self._dispatch("GET") + + def do_POST(self): + self._dispatch("POST") + + def do_DELETE(self): + self._dispatch("DELETE") + + def _dispatch(self, method: str): + request_id = self.headers.get("X-Request-Id") or str(uuid.uuid4()) + acquired = False + try: + REQUEST_GUARD.acquire() + acquired = True + parsed = urlsplit(self.path) + path = parsed.path + query = parse_qs(parsed.query, keep_blank_values=True) + if path == "/health/live" and method == "GET": + self._send_json(200, {"status": "ok"}, request_id) + elif path == "/health/ready" and method == "GET": + try: + self.store.ready() + except (psycopg.Error, PoolTimeout, OSError): + raise ApiError(503, "unavailable", "Database is unavailable") + self._send_json(200, {"status": "ok"}, request_id) + elif path == "/api/v1/users" and method == "POST": + self._handle_register(request_id) + elif path == "/api/v1/auth/sessions" and method == "POST": + self._handle_create_session(request_id) + elif path == "/api/v1/auth/sessions/current" and method == "DELETE": + self._handle_revoke_session(request_id) + elif path == "/api/v1/users/me" and method == "GET": + self._send_json(200, self._get_actor(request_id), request_id) + elif path == "/api/v1/chats" and method == "POST": + self._handle_create_chat(request_id) + elif path == "/api/v1/chats" and method == "GET": + self._handle_list_chats(query, request_id) + elif path.startswith("/api/v1/chats/") and path.endswith("/messages") and method in ("GET", "POST"): + chat_id = path.rsplit("/", 2)[1] + if method == "POST": + self._handle_create_message(chat_id, request_id) + else: + self._handle_list_messages(chat_id, query, request_id) + elif path.startswith("/api/v1/chats/") and method == "GET": + self._handle_get_chat(path.rsplit("/", 1)[1], request_id) + else: + raise ApiError(404, "not_found", "Object not found") + except ApiError as exc: + self._send_error(exc.status, exc.code, exc.message, request_id, exc.headers) + except CacheUnavailableError: + self._send_error(503, "unavailable", "Session cache is unavailable", request_id) + except IdempotencyConflictError: + self._send_error(409, "conflict", "Idempotency-Key was already used with another request", request_id) + except (PoolTimeout, psycopg.OperationalError, psycopg.InterfaceError): + self._send_error(503, "unavailable", "Database is unavailable", request_id) + except psycopg.errors.UniqueViolation: + self._send_error(409, "conflict", "Username already exists", request_id) + except psycopg.errors.ForeignKeyViolation: + self._send_error(400, "invalid_request", "Unknown member", request_id) + except Exception as exc: + LOGGER.error("request %s failed with %s", request_id, type(exc).__name__) + self._send_error(500, "internal_error", "Internal server error", request_id) + finally: + if acquired: + REQUEST_GUARD.release() + + def _read_json(self, request_id: str) -> Any: + if self.headers.get_content_type() != "application/json": + raise ApiError(415, "unsupported_media_type", "Content-Type must be application/json") + length = self.headers.get("Content-Length") + if length is None: + raise ApiError(400, "invalid_request", "Missing Content-Length") + try: + size = int(length) + except ValueError: + raise ApiError(400, "invalid_request", "Invalid Content-Length") + if size < 0: + raise ApiError(400, "invalid_request", "Invalid Content-Length") + if size > MAX_REQUEST_BODY_BYTES: + raise ApiError(413, "payload_too_large", "Request body too large") + raw = self.rfile.read(size) + if not raw: + raise ApiError(400, "invalid_request", "Empty body") + try: + return json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError): + raise ApiError(400, "invalid_request", "Malformed JSON") + + def _get_actor(self, request_id: str) -> Dict[str, Any]: + header = self.headers.get("Authorization", "") + scheme, separator, token = header.partition(" ") + if scheme.lower() != "bearer" or not separator or not token or " " in token: + raise ApiError( + 401, + "unauthorized", + "Authentication required", + {"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + user = self.store.session_user(token) + if user is None: + raise ApiError( + 401, + "unauthorized", + "Authentication required", + {"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + return user + + def _handle_register(self, request_id: str): + body = self._read_json(request_id) + if not isinstance(body, dict) or set(body) != {"username", "display_name", "password"}: + raise ApiError(400, "invalid_request", "Expected username, display_name and password") + username = body["username"] + display_name = body["display_name"] + password = body["password"] + if not isinstance(username, str) or not USER_RE.fullmatch(username): + raise ApiError(400, "invalid_request", "Invalid username") + if not isinstance(display_name, str) or not display_name.strip() or len(display_name) > 100: + raise ApiError(400, "invalid_request", "Invalid display_name") + if not isinstance(password, str) or not (12 <= len(password) <= 128): + raise ApiError(400, "invalid_request", "Invalid password") + user = self.store.create_user(username, display_name, hash_password(password)) + self._send_json(201, user, request_id) + + def _basic_credentials(self, request_id: str) -> Tuple[str, str]: + value = self.headers.get("Authorization", "") + scheme, separator, encoded = value.partition(" ") + challenge = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'} + if scheme.lower() != "basic" or not separator or not encoded: + raise ApiError(401, "unauthorized", "Invalid credentials", challenge) + try: + decoded = base64.b64decode(encoded, validate=True).decode("utf-8") + username, password = decoded.split(":", 1) + except (ValueError, UnicodeError): + raise ApiError(401, "unauthorized", "Invalid credentials", challenge) + return username, password + + def _handle_create_session(self, request_id: str): + username, password = self._basic_credentials(request_id) + user = self.store.authenticate(username, password) + if user is None: + raise ApiError( + 401, + "unauthorized", + "Invalid credentials", + {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + token, expires_at = self.store.create_session(user["id"]) + self._send_json( + 201, + {"token": token, "token_type": "Bearer", "expires_at": isoformat(expires_at), "user": user}, + request_id, + ) + + def _handle_revoke_session(self, request_id: str): + self._get_actor(request_id) + token = self.headers["Authorization"].partition(" ")[2] + if not self.store.revoke_session(token): + raise ApiError( + 401, + "unauthorized", + "Authentication required", + {"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + self.send_response(204) + self.send_header("X-Request-Id", request_id) + self.send_header("X-Instance-Id", INSTANCE_ID) + self.end_headers() + + def _handle_create_chat(self, request_id: str): + actor = self._get_actor(request_id) + body = self._read_json(request_id) + if not isinstance(body, dict) or set(body) != {"title", "member_ids"}: + raise ApiError(400, "invalid_request", "Expected title and member_ids") + title, member_ids = body["title"], body["member_ids"] + if not isinstance(title, str) or not title.strip() or len(title) > 100: + raise ApiError(400, "invalid_request", "Invalid title") + if ( + not isinstance(member_ids, list) + or not 1 <= len(member_ids) <= 100 + or any(not isinstance(item, str) or not valid_uuid(item) for item in member_ids) + or len(member_ids) != len(set(member_ids)) + or actor["id"] not in member_ids + ): + raise ApiError(400, "invalid_request", "Invalid member_ids") + chat = self.store.create_chat(title, member_ids, actor["id"]) + self._send_json(201, chat, request_id) + + def _handle_list_chats(self, query: Dict[str, List[str]], request_id: str): + actor = self._get_actor(request_id) + try: + limit = int(query.get("limit", ["50"])[0]) + except ValueError: + raise ApiError(400, "invalid_request", "Invalid limit") + if not 1 <= limit <= 100: + raise ApiError(400, "invalid_request", "Invalid limit") + cursor = query.get("cursor", [None])[0] + try: + chats, next_cursor = self.store.list_chats(actor["id"], limit, cursor) + except ValueError: + raise ApiError(400, "invalid_request", "Invalid cursor") + self._send_json(200, {"items": chats, "next_cursor": next_cursor}, request_id) + + def _handle_get_chat(self, chat_id: str, request_id: str): + actor = self._get_actor(request_id) + if not valid_uuid(chat_id): + raise ApiError(400, "invalid_request", "Invalid chat id") + chat = self.store.get_chat(chat_id, actor["id"]) + if chat is None: + raise ApiError(404, "not_found", "Chat not found") + self._send_json(200, chat, request_id) + + def _handle_create_message(self, chat_id: str, request_id: str): + actor = self._get_actor(request_id) + if not valid_uuid(chat_id): + raise ApiError(400, "invalid_request", "Invalid chat id") + chat_id = str(uuid.UUID(chat_id)) + idempotency_key = self.headers.get("Idempotency-Key", "") + if not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key): + raise ApiError(400, "invalid_request", "Invalid or missing Idempotency-Key") + body = self._read_json(request_id) + if not isinstance(body, dict) or set(body) != {"text"}: + raise ApiError(400, "invalid_request", "Expected text") + text = body["text"] + if not isinstance(text, str) or not text.strip() or len(text) > 4000: + raise ApiError(400, "invalid_request", "Invalid message text") + canonical_body = json.dumps( + {"text": text}, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ) + message = self.store.create_idempotent_message( + chat_id, + actor["id"], + text, + idempotency_key, + canonical_body, + ) + if message is None: + raise ApiError(404, "not_found", "Chat not found") + self._send_json(201, message, request_id) + + def _handle_list_messages(self, chat_id: str, query: Dict[str, List[str]], request_id: str): + actor = self._get_actor(request_id) + if not valid_uuid(chat_id): + raise ApiError(400, "invalid_request", "Invalid chat id") + try: + limit = int(query.get("limit", ["50"])[0]) + except ValueError: + raise ApiError(400, "invalid_request", "Invalid limit") + if not 1 <= limit <= 100: + raise ApiError(400, "invalid_request", "Invalid limit") + cursor = query.get("cursor", [None])[0] + try: + result = self.store.list_messages(chat_id, actor["id"], limit, cursor) + except ValueError: + raise ApiError(400, "invalid_request", "Invalid cursor") + if result is None: + raise ApiError(404, "not_found", "Chat not found") + items, next_cursor = result + self._send_json(200, {"items": items, "next_cursor": next_cursor}, request_id) + + def _send_json( + self, + status: int, + payload: Dict[str, Any], + request_id: str, + headers: Optional[Dict[str, str]] = None, + ): + body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.send_header("X-Request-Id", request_id) + self.send_header("X-Instance-Id", INSTANCE_ID) + if headers: + for key, value in headers.items(): + self.send_header(key, value) + self.end_headers() + self.wfile.write(body) + + def _send_error( + self, + status: int, + code: str, + message: str, + request_id: str, + extra_headers: Optional[Dict[str, str]] = None, + ): + self._send_json( + status, + {"error": {"code": code, "message": message, "request_id": request_id}}, + request_id, + extra_headers, + ) diff --git a/src/migrate.py b/src/migrate.py new file mode 100644 index 0000000..1ae2700 --- /dev/null +++ b/src/migrate.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +import logging +import sys +from pathlib import Path + +if __package__ in (None, ""): + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + from src.store import Store +else: + from .store import Store + + +def main(): + logging.basicConfig(level="INFO") + store = Store() + store.open() + try: + store.migrate() + finally: + store.close() + + +if __name__ == "__main__": + main() diff --git a/src/security.py b/src/security.py new file mode 100644 index 0000000..6ec821f --- /dev/null +++ b/src/security.py @@ -0,0 +1,53 @@ +import base64 +import hashlib +import hmac +import secrets +import uuid +from datetime import datetime, timezone + + +def isoformat(value: datetime) -> str: + return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") + + +def utc_now() -> datetime: + return datetime.now(timezone.utc) + + +def valid_uuid(value: str) -> bool: + try: + uuid.UUID(value) + return True + except (ValueError, TypeError, AttributeError): + return False + + +def hash_password(password: str) -> str: + salt = secrets.token_bytes(16) + derived = hashlib.scrypt( + password.encode("utf-8"), salt=salt, n=32768, r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024 + ) + salt_text = base64.urlsafe_b64encode(salt).decode("ascii") + hash_text = base64.urlsafe_b64encode(derived).decode("ascii") + return f"scrypt$32768$8$1${salt_text}${hash_text}" + + +def verify_password(password: str, stored: str) -> bool: + try: + scheme, n, r, p, salt_text, hash_text = stored.split("$") + if scheme != "scrypt": + return False + salt = base64.urlsafe_b64decode(salt_text.encode("ascii")) + expected = base64.urlsafe_b64decode(hash_text.encode("ascii")) + actual = hashlib.scrypt( + password.encode("utf-8"), + salt=salt, + n=int(n), + r=int(r), + p=int(p), + dklen=len(expected), + maxmem=64 * 1024 * 1024, + ) + return hmac.compare_digest(actual, expected) + except (ValueError, TypeError, UnicodeError): + return False diff --git a/src/server.py b/src/server.py new file mode 100644 index 0000000..60fd3d5 --- /dev/null +++ b/src/server.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +import sys +from pathlib import Path + +if __package__ in (None, ""): + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + from src.app import main +else: + from .app import main + + +if __name__ == "__main__": + main() diff --git a/src/store.py b/src/store.py new file mode 100644 index 0000000..476dba1 --- /dev/null +++ b/src/store.py @@ -0,0 +1,394 @@ +import base64 +import hashlib +import hmac +import json +import logging +import math +import os +import secrets +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +import redis +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool + +from .config import ( + DB_LOCK_TIMEOUT_MS, + DB_POOL_MAX_SIZE, + DB_POOL_TIMEOUT_SECONDS, + DB_STATEMENT_TIMEOUT_MS, + IDEMPOTENCY_TTL_SECONDS, + SESSION_TTL_SECONDS, +) +from .errors import CacheUnavailableError, IdempotencyConflictError +from .security import isoformat, utc_now, valid_uuid, verify_password + +LOGGER = logging.getLogger("messenger.store") + + +def database_url() -> str: + value = os.getenv("DATABASE_URL") + if value: + return value + file_path = os.getenv("DATABASE_URL_FILE") + if file_path: + return Path(file_path).read_text(encoding="utf-8").strip() + raise RuntimeError("Set DATABASE_URL or DATABASE_URL_FILE") + + +class Store: + """PostgreSQL source of truth and optional Redis session lookup cache.""" + + def __init__(self): + self.pool = ConnectionPool( + conninfo=database_url(), + min_size=1, + max_size=DB_POOL_MAX_SIZE, + timeout=DB_POOL_TIMEOUT_SECONDS, + kwargs={ + "row_factory": dict_row, + "connect_timeout": 5, + "options": ( + f"-c statement_timeout={DB_STATEMENT_TIMEOUT_MS} " + f"-c lock_timeout={DB_LOCK_TIMEOUT_MS} " + "-c idle_in_transaction_session_timeout=10000" + ), + }, + open=False, + ) + cache_url = os.getenv("CACHE_URL") + self.cache = ( + redis.Redis.from_url( + cache_url, + decode_responses=True, + socket_connect_timeout=0.25, + socket_timeout=0.25, + retry_on_timeout=False, + max_connections=16, + ) + if cache_url + else None + ) + + def open(self): + self.pool.open(wait=True, timeout=10) + + def close(self): + if self.cache is not None: + self.cache.close() + self.pool.close() + + def ready(self) -> bool: + with self.pool.connection(timeout=2) as conn: + conn.execute("SELECT 1") + return True + + def migrate(self): + migrations = Path(__file__).resolve().parents[1] / "migrations" + with self.pool.connection() as conn: + with conn.transaction(): + conn.execute( + "CREATE TABLE IF NOT EXISTS schema_migrations " + "(version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())" + ) + conn.execute("SELECT pg_advisory_xact_lock(2741662026)") + applied = {row["version"] for row in conn.execute("SELECT version FROM schema_migrations")} + for migration in sorted(migrations.glob("*.sql")): + if migration.name in applied: + continue + conn.execute(migration.read_text(encoding="utf-8")) + conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (migration.name,)) + + @staticmethod + def user(row: Dict[str, Any]) -> Dict[str, Any]: + return { + "id": str(row["id"]), + "username": row["username"], + "display_name": row["display_name"], + "created_at": isoformat(row["created_at"]), + } + + @staticmethod + def chat(row: Dict[str, Any], member_ids: List[str]) -> Dict[str, Any]: + return { + "id": str(row["id"]), + "title": row["title"], + "member_ids": member_ids, + "created_at": isoformat(row["created_at"]), + } + + @staticmethod + def message(row: Dict[str, Any]) -> Dict[str, Any]: + return { + "id": str(row["id"]), + "chat_id": str(row["chat_id"]), + "sender_id": str(row["sender_id"]), + "text": row["text"], + "created_at": isoformat(row["created_at"]), + } + + def create_user(self, username: str, display_name: str, password_hash: str) -> Dict[str, Any]: + with self.pool.connection() as conn: + with conn.transaction(): + row = conn.execute( + "INSERT INTO users (username, display_name, password_hash) " + "VALUES (%s, %s, %s) RETURNING id, username, display_name, created_at", + (username, display_name, password_hash), + ).fetchone() + return self.user(row) + + def get_user(self, user_id: str) -> Optional[Dict[str, Any]]: + with self.pool.connection() as conn: + row = conn.execute( + "SELECT id, username, display_name, created_at FROM users WHERE id = %s", + (user_id,), + ).fetchone() + return self.user(row) if row else None + + def authenticate(self, username: str, password: str) -> Optional[Dict[str, Any]]: + with self.pool.connection() as conn: + row = conn.execute( + "SELECT id, username, display_name, created_at, password_hash " + "FROM users WHERE username = %s", + (username,), + ).fetchone() + if not row or not verify_password(password, row["password_hash"]): + return None + return self.user(row) + + def create_session(self, user_id: str) -> Tuple[str, datetime]: + token = secrets.token_urlsafe(32) + expires_at = utc_now() + timedelta(seconds=SESSION_TTL_SECONDS) + token_hash = hashlib.sha256(token.encode("ascii")).digest() + with self.pool.connection() as conn: + conn.execute( + "INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s, %s, %s)", + (token_hash, user_id, expires_at), + ) + return token, expires_at + + @staticmethod + def _session_lock_key(token_hash: bytes) -> int: + return int.from_bytes(token_hash[:8], byteorder="big", signed=True) + + def session_user(self, token: str) -> Optional[Dict[str, Any]]: + token_hash = hashlib.sha256(token.encode("utf-8")).digest() + cache_key = "messenger:session:" + token_hash.hex() + if self.cache is not None: + try: + cached = self.cache.get(cache_key) + if cached: + return json.loads(cached) + except (redis.RedisError, ValueError, TypeError): + LOGGER.warning("session cache read failed; falling back to PostgreSQL") + with self.pool.connection() as conn: + with conn.transaction(): + conn.execute("SELECT pg_advisory_xact_lock(%s)", (self._session_lock_key(token_hash),)) + row = conn.execute( + "SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at " + "FROM sessions s JOIN users u ON u.id = s.user_id " + "WHERE s.token_hash = %s AND s.expires_at > now()", + (token_hash,), + ).fetchone() + if not row: + return None + user = self.user(row) + if self.cache is not None: + ttl_ms = math.floor((row["expires_at"] - utc_now()).total_seconds() * 1000) + if ttl_ms > 0: + try: + self.cache.set(cache_key, json.dumps(user, separators=(",", ":")), px=ttl_ms) + except redis.RedisError: + LOGGER.warning("session cache write failed; PostgreSQL remains authoritative") + return user + + def revoke_session(self, token: str) -> bool: + token_hash = hashlib.sha256(token.encode("utf-8")).digest() + with self.pool.connection() as conn: + with conn.transaction(): + conn.execute("SELECT pg_advisory_xact_lock(%s)", (self._session_lock_key(token_hash),)) + if self.cache is not None: + try: + self.cache.delete("messenger:session:" + token_hash.hex()) + except redis.RedisError as exc: + raise CacheUnavailableError from exc + result = conn.execute("DELETE FROM sessions WHERE token_hash = %s", (token_hash,)) + return result.rowcount == 1 + + def create_chat(self, title: str, member_ids: List[str], actor_id: str) -> Dict[str, Any]: + if actor_id not in member_ids or len(member_ids) != len(set(member_ids)): + raise ValueError("invalid members") + with self.pool.connection() as conn: + with conn.transaction(): + row = conn.execute( + "INSERT INTO chats (title) VALUES (%s) RETURNING id, title, created_at", + (title,), + ).fetchone() + for member_id in member_ids: + conn.execute( + "INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", + (row["id"], member_id), + ) + return self.chat(row, member_ids) + + def get_chat(self, chat_id: str, user_id: str) -> Optional[Dict[str, Any]]: + with self.pool.connection() as conn: + row = conn.execute( + "SELECT c.id, c.title, c.created_at FROM chats c " + "JOIN chat_members m ON m.chat_id = c.id " + "WHERE c.id = %s AND m.user_id = %s", + (chat_id, user_id), + ).fetchone() + if not row: + return None + members = conn.execute( + "SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY joined_at, user_id", + (chat_id,), + ).fetchall() + return self.chat(row, [str(item["user_id"]) for item in members]) + + def list_chats( + self, user_id: str, limit: int, cursor: Optional[str] + ) -> Tuple[List[Dict[str, Any]], Optional[str]]: + where = "own.user_id = %s" + params: List[Any] = [user_id] + if cursor is not None: + try: + raw = base64.b64decode( + cursor.encode("ascii") + b"=" * (-len(cursor) % 4), + altchars=b"-_", + validate=True, + ) + cursor_user, timestamp, chat_id = raw.decode("utf-8").split("|", 2) + if cursor_user != user_id or not valid_uuid(chat_id): + raise ValueError("cursor scope") + created_at = datetime.fromisoformat(timestamp.replace("Z", "+00:00")) + if created_at.tzinfo is None or created_at.utcoffset() is None: + raise ValueError("cursor timestamp must include a timezone") + where += " AND (c.created_at, c.id) > (%s, %s)" + params.extend((created_at, chat_id)) + except (ValueError, UnicodeError, TypeError) as exc: + raise ValueError("invalid cursor") from exc + params.append(limit + 1) + with self.pool.connection() as conn: + rows = conn.execute( + "SELECT c.id, c.title, c.created_at FROM chats c " + "JOIN chat_members own ON own.chat_id = c.id " + f"WHERE {where} ORDER BY c.created_at, c.id LIMIT %s", + params, + ).fetchall() + has_more = len(rows) > limit + page = rows[:limit] + result = [] + for row in page: + members = conn.execute( + "SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY joined_at, user_id", + (row["id"],), + ).fetchall() + result.append(self.chat(row, [str(item["user_id"]) for item in members])) + next_cursor = None + if has_more and page: + last = page[-1] + cursor_data = f"{user_id}|{isoformat(last['created_at'])}|{last['id']}".encode("utf-8") + next_cursor = base64.urlsafe_b64encode(cursor_data).decode("ascii").rstrip("=") + return result, next_cursor + + def create_idempotent_message( + self, + chat_id: str, + sender_id: str, + text: str, + idempotency_key: str, + canonical_body: str, + ) -> Optional[Dict[str, Any]]: + request_hash = hashlib.sha256(canonical_body.encode("utf-8")).digest() + lock_material = "\0".join((sender_id, "POST", chat_id, idempotency_key)).encode("utf-8") + lock_key = int.from_bytes(hashlib.sha256(lock_material).digest()[:8], "big", signed=True) + with self.pool.connection() as conn: + with conn.transaction(): + member = conn.execute( + "SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", + (chat_id, sender_id), + ).fetchone() + if not member: + return None + + conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_key,)) + existing = conn.execute( + "SELECT request_hash, response, expires_at " + "FROM idempotency_records " + "WHERE user_id = %s AND method = 'POST' AND chat_id = %s AND idempotency_key = %s " + "FOR UPDATE", + (sender_id, chat_id, idempotency_key), + ).fetchone() + if existing and existing["expires_at"] > utc_now(): + if not hmac.compare_digest(bytes(existing["request_hash"]), request_hash): + raise IdempotencyConflictError + return existing["response"] + if existing: + conn.execute( + "DELETE FROM idempotency_records " + "WHERE user_id = %s AND method = 'POST' AND chat_id = %s AND idempotency_key = %s", + (sender_id, chat_id, idempotency_key), + ) + + row = conn.execute( + "INSERT INTO messages (chat_id, sender_id, text) " + "VALUES (%s, %s, %s) RETURNING id, chat_id, sender_id, text, created_at", + (chat_id, sender_id, text), + ).fetchone() + message = self.message(row) + conn.execute( + "INSERT INTO idempotency_records " + "(user_id, method, chat_id, idempotency_key, request_hash, response, expires_at) " + "VALUES (%s, 'POST', %s, %s, %s, %s::jsonb, %s)", + ( + sender_id, + chat_id, + idempotency_key, + request_hash, + json.dumps(message, ensure_ascii=False, separators=(",", ":")), + utc_now() + timedelta(seconds=IDEMPOTENCY_TTL_SECONDS), + ), + ) + return message + + def list_messages( + self, chat_id: str, user_id: str, limit: int, cursor: Optional[str] + ) -> Optional[Tuple[List[Dict[str, Any]], Optional[str]]]: + with self.pool.connection() as conn: + is_member = conn.execute( + "SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", + (chat_id, user_id), + ).fetchone() + if not is_member: + return None + where = "chat_id = %s" + params: List[Any] = [chat_id] + if cursor: + try: + raw = base64.urlsafe_b64decode(cursor.encode("ascii") + b"=" * (-len(cursor) % 4)) + decoded_chat, timestamp, message_id = raw.decode("utf-8").split("|", 2) + if decoded_chat != chat_id or not valid_uuid(message_id): + raise ValueError("cursor scope") + created_at = datetime.fromisoformat(timestamp.replace("Z", "+00:00")) + where += " AND (created_at, id) > (%s, %s)" + params.extend((created_at, message_id)) + except (ValueError, UnicodeError, TypeError) as exc: + raise ValueError("invalid cursor") from exc + params.append(limit + 1) + rows = conn.execute( + "SELECT id, chat_id, sender_id, text, created_at FROM messages " + f"WHERE {where} ORDER BY created_at, id LIMIT %s", + params, + ).fetchall() + has_more = len(rows) > limit + page = rows[:limit] + next_cursor = None + if has_more and page: + last = page[-1] + cursor_data = f"{chat_id}|{isoformat(last['created_at'])}|{last['id']}".encode("utf-8") + next_cursor = base64.urlsafe_b64encode(cursor_data).decode("ascii").rstrip("=") + return [self.message(row) for row in page], next_cursor diff --git a/student-tests/test_idempotency_race.py b/student-tests/test_idempotency_race.py new file mode 100644 index 0000000..646869a --- /dev/null +++ b/student-tests/test_idempotency_race.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Prove a concurrent idempotency-key race through the load balancer.""" +from concurrent.futures import ThreadPoolExecutor +import threading +import sys +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, arguments, check, run + + +def main(): + args = arguments("Concurrent shared-idempotency integration check") + client = Client(args.base_url, args.ca_file) + alice, _, _, chat = client.bootstrap() + key = "race-" + uuid.uuid4().hex + text = "concurrent-" + uuid.uuid4().hex + count = 12 + barrier = threading.Barrier(count) + + def send_once(_): + worker = Client(args.base_url, args.ca_file) + barrier.wait(timeout=10) + return worker.message(alice, chat, text, key=key) + + with ThreadPoolExecutor(max_workers=count) as pool: + responses = list(pool.map(send_once, range(count))) + + instance_ids = {response["headers"]["X-Instance-Id"] for response in responses} + messages = [response["json"] for response in responses] + check(len(instance_ids) >= 2, "concurrent requests did not reach multiple API replicas") + check(all(message == messages[0] for message in messages), "same-key requests returned different messages") + page = client.call( + "GET", + "/api/v1/chats/" + chat["id"] + "/messages?limit=100", + actor=alice, + schema="MessagePage", + )["json"] + matches = [message for message in page["items"] if message["text"] == text] + check(len(matches) == 1 and matches[0] == messages[0], "concurrent retry persisted duplicate messages") + print(f"PASS: {count} concurrent same-key requests on {len(instance_ids)} replicas returned one message") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/track1_benchmark.py b/student-tests/track1_benchmark.py new file mode 100644 index 0000000..fe77957 --- /dev/null +++ b/student-tests/track1_benchmark.py @@ -0,0 +1,385 @@ +#!/usr/bin/env python3 +"""Repeatable 1/2/4 replica throughput experiment with Docker resource samples.""" +import argparse +import json +import math +import platform +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import time +import hashlib + +ROOT = Path(__file__).resolve().parents[1] +LOAD_TEST = ROOT / "tests" / "load.py" +OUTPUT_DIR = ROOT / "evidence" / "track1" +COMPOSE = ["docker", "compose", "--env-file", ".env"] + + +def run(command, *, env=None, capture=True): + return subprocess.run( + command, + cwd=ROOT, + env=env, + check=True, + text=True, + stdout=subprocess.PIPE if capture else None, + stderr=subprocess.PIPE if capture else None, + ) + + +def compose_environment(cpu_limit, memory_limit): + import os + + env = os.environ.copy() + env["API_CPU_LIMIT"] = cpu_limit + env["API_MEMORY_LIMIT"] = memory_limit + return env + + +def database_counts(): + query = ( + "SELECT json_build_object(" + "'users', (SELECT count(*) FROM users), " + "'chats', (SELECT count(*) FROM chats), " + "'messages', (SELECT count(*) FROM messages), " + "'sessions', (SELECT count(*) FROM sessions), " + "'idempotency_records', (SELECT count(*) FROM idempotency_records)" + ")::text" + ) + result = run( + COMPOSE + + [ + "exec", + "-T", + "postgres", + "psql", + "-X", + "-qAt", + "-U", + "messenger", + "-d", + "messenger", + "-c", + query, + ] + ) + return json.loads(result.stdout) + + +def create_database_snapshot(destination): + with destination.open("wb") as dump: + result = subprocess.run( + COMPOSE + ["exec", "-T", "postgres", "pg_dump", "-Fc", "-U", "messenger", "-d", "messenger"], + cwd=ROOT, + check=False, + stdout=dump, + stderr=subprocess.PIPE, + ) + if result.returncode: + raise RuntimeError("failed to create PostgreSQL baseline snapshot: " + result.stderr.decode(errors="replace")) + digest_builder = hashlib.sha256() + with destination.open("rb") as dump: + for chunk in iter(lambda: dump.read(1024 * 1024), b""): + digest_builder.update(chunk) + digest = digest_builder.hexdigest() + return digest, database_counts() + + +def restore_database_snapshot(snapshot, baseline_counts, api_replicas, cpu_limit, memory_limit): + env = compose_environment(cpu_limit, memory_limit) + run(COMPOSE + ["stop", "api"]) + with snapshot.open("rb") as dump: + result = subprocess.run( + COMPOSE + + [ + "exec", + "-T", + "postgres", + "pg_restore", + "-U", + "messenger", + "--clean", + "--if-exists", + "--no-owner", + "--no-acl", + "--exit-on-error", + "--dbname=messenger", + ], + cwd=ROOT, + check=False, + stdin=dump, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + if result.returncode: + raise RuntimeError("failed to restore PostgreSQL baseline snapshot: " + result.stderr.decode(errors="replace")) + restored_counts = database_counts() + if restored_counts != baseline_counts: + raise RuntimeError( + "restored PostgreSQL baseline has different row counts: " + + json.dumps(restored_counts, sort_keys=True) + ) + run( + COMPOSE + + [ + "up", + "-d", + "--no-deps", + "--build", + "--force-recreate", + "--scale", + f"api={api_replicas}", + "--wait", + "--wait-timeout", + "120", + "api", + ], + env=env, + ) + + +def docker_stats(): + containers = run( + ["docker", "compose", "--env-file", ".env", "ps", "-q"], + ).stdout.splitlines() + if not containers: + return [] + result = run( + [ + "docker", + "stats", + "--no-stream", + "--format", + "{{.Name}}|{{.CPUPerc}}|{{.MemUsage}}", + *containers, + ] + ) + samples = [] + for line in result.stdout.splitlines(): + name, cpu, memory = line.split("|", 2) + used = memory.split("/", 1)[0].strip() + samples.append( + { + "container": name, + "service": "api" if "-api-" in name else "postgres" if "-postgres-" in name else "load_balancer", + "cpu_percent": float(cpu.rstrip("%")), + "memory_bytes": parse_bytes(used), + } + ) + return samples + + +def parse_bytes(value): + match = re.fullmatch(r"([0-9.]+)\s*([KMG]i?B|B)", value) + if not match: + return None + amount = float(match.group(1)) + unit = match.group(2) + power = {"B": 0, "KB": 1, "KiB": 1, "MB": 2, "MiB": 2, "GB": 3, "GiB": 3}[unit] + return round(amount * 1024**power) + + +def run_load(name, duration, concurrency, repetition, base_url): + output = OUTPUT_DIR / f"{name}-run-{repetition}.json" + command = [ + sys.executable, + str(LOAD_TEST), + "--base-url", + base_url, + "--duration", + str(duration), + "--concurrency", + str(concurrency), + "--output", + str(output.relative_to(ROOT)), + ] + process = subprocess.Popen( + command, + cwd=ROOT, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + samples = [] + while process.poll() is None: + samples.extend(docker_stats()) + time.sleep(1) + stdout, stderr = process.communicate() + if process.returncode: + raise RuntimeError(f"load run failed:\n{stdout}\n{stderr}") + metrics = json.loads(output.read_text(encoding="utf-8")) + metrics["resource_samples"] = samples + return metrics + + +def system_info(): + def command_output(command): + try: + return run(command).stdout.strip() + except (OSError, subprocess.CalledProcessError): + return "unavailable" + + return { + "platform": platform.platform(), + "processor": platform.processor() or "unavailable", + "cpu_count": __import__("os").cpu_count(), + "host_memory_bytes": command_output(["sysctl", "-n", "hw.memsize"]), + "docker_server": command_output(["docker", "version", "--format", "{{.Server.Version}}"]), + "docker_compose": command_output(["docker", "compose", "version", "--short"]), + } + + +def configure_limits(count, phase): + if phase == "fixed": + return f"{1 / count:.4f}", f"{512 // count}M" + return "1.0", "512M" + + +def experiment_case(count, phase, args, snapshot, snapshot_hash, baseline_counts): + cpu_limit, memory_limit = configure_limits(count, phase) + restore_database_snapshot(snapshot, baseline_counts, count, cpu_limit, memory_limit) + run_load(f"{phase}-{count}-warmup", args.warmup, args.concurrency, 0, args.base_url) + warmup_counts = database_counts() + if warmup_counts == baseline_counts: + raise RuntimeError("warm-up did not create synthetic workload data") + + repetitions = [] + for repetition in range(1, args.repetitions + 1): + restore_database_snapshot(snapshot, baseline_counts, count, cpu_limit, memory_limit) + repetitions.append(run_load(f"{phase}-{count}", args.duration, args.concurrency, repetition, args.base_url)) + if database_counts() == baseline_counts: + raise RuntimeError(f"{phase}-{count} repetition {repetition} did not write benchmark data") + return { + "phase": phase, + "api_replicas": count, + "per_replica_cpu_limit": cpu_limit, + "per_replica_memory_limit": memory_limit, + "total_api_cpu_limit": round(float(cpu_limit) * count, 4), + "total_api_memory_limit_mib": int(memory_limit[:-1]) * count, + "warmup_seconds": args.warmup, + "baseline_row_counts": baseline_counts, + "baseline_snapshot_sha256": snapshot_hash, + "each_repetition_restored_same_baseline": True, + "repetitions": repetitions, + } + + +def make_graph(cases): + width, height = 900, 420 + margin = 60 + values = [ + ( + f"{case['phase']} / {case['api_replicas']}", + sum(run["successful_rps"] for run in case["repetitions"]) / len(case["repetitions"]), + "#3572A5" if case["phase"] == "fixed" else "#E38B29", + ) + for case in cases + ] + top = max((value for _, value, _ in values), default=1) or 1 + graph_height = height - 2 * margin + bar_width = 78 + gap = (width - 2 * margin - bar_width * len(values)) / max(1, len(values) - 1) + parts = [ + f'', + '', + 'API scaling: average successful RPS', + f'', + ] + for index, (label, value, color) in enumerate(values): + x = margin + index * (bar_width + gap) + bar_height = value / top * graph_height + y = height - margin - bar_height + parts.append(f'') + parts.append(f'{value:.1f}') + parts.append(f'{label}') + parts.append("") + (OUTPUT_DIR / "throughput.svg").write_text("\n".join(parts) + "\n", encoding="utf-8") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--duration", type=int, default=30) + parser.add_argument("--warmup", type=int, default=5) + parser.add_argument("--concurrency", type=int, default=16) + parser.add_argument("--repetitions", type=int, default=3) + parser.add_argument("--base-url", default="http://127.0.0.1:8080") + args = parser.parse_args() + if not 1 <= args.duration <= 3600 or not 1 <= args.warmup <= 600: + parser.error("duration and warmup must be positive and bounded") + if not 1 <= args.concurrency <= 128 or not 1 <= args.repetitions <= 10: + parser.error("concurrency or repetitions out of range") + + OUTPUT_DIR.mkdir(parents=True, exist_ok=True) + results_file = OUTPUT_DIR / "results.json" + + with tempfile.TemporaryDirectory(prefix="lab3-track1-") as temporary_directory: + snapshot = Path(temporary_directory) / "baseline.dump" + run(COMPOSE + ["stop", "api"]) + baseline_counts = None + try: + snapshot_hash, baseline_counts = create_database_snapshot(snapshot) + cases = [] + for phase, replica_counts in (("fixed", (1, 2, 4)), ("growth", (1, 2, 4, 8))): + for count in replica_counts: + cases.append( + experiment_case(count, phase, args, snapshot, snapshot_hash, baseline_counts) + ) + summary = { + "method": ( + "closed-loop POST message workload via HAProxy; same concurrency and per-run " + "restored PostgreSQL custom-format baseline snapshot" + ), + "database_baseline": { + "snapshot_sha256": snapshot_hash, + "row_counts": baseline_counts, + "restore_before_each_warmup_and_measured_repetition": True, + "state_after_experiment": "baseline restored; all synthetic benchmark writes removed", + }, + "system": system_info(), + "database_and_lb_limits": {"postgres": "1 CPU / 1 GiB", "HAProxy": "0.5 CPU / 128 MiB"}, + "client_concurrency": args.concurrency, + "requested_duration_seconds": args.duration, + "repetitions_per_case": args.repetitions, + "cases": cases, + } + results_file.write_text( + json.dumps(summary, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + make_graph(cases) + for case in cases: + values = [run["successful_rps"] for run in case["repetitions"]] + deviation = math.sqrt(sum((value - sum(values) / len(values)) ** 2 for value in values) / len(values)) + print( + f"{case['phase']:6} replicas={case['api_replicas']} " + f"mean_rps={sum(values) / len(values):.2f} stdev={deviation:.2f}" + ) + print(f"Evidence saved under {OUTPUT_DIR.relative_to(ROOT)}") + finally: + if baseline_counts is not None: + restore_database_snapshot(snapshot, baseline_counts, 2, "1.0", "512M") + else: + run( + COMPOSE + + [ + "up", + "-d", + "--no-deps", + "--build", + "--force-recreate", + "--scale", + "api=2", + "--wait", + "--wait-timeout", + "120", + "api", + ], + env=compose_environment("1.0", "512M"), + ) + + +if __name__ == "__main__": + main() diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..0dfa3f8 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,57 @@ +# Публичные проверки + +Python **3.9+**, стандартная библиотека. Сервер уже должен быть запущен; проверки не создают готовое приложение и сами не управляют Docker. `make check` можно выполнить на исходном skeleton, `make test` — только после реализации API. Полная OpenAPI-валидация отдельно: `make validate` после установки `requirements-dev.txt` в venv. + +```sh +make check +make test BASE_URL=http://localhost:8080 +# без make: +python3 tests/smoke.py --base-url http://localhost:8080 +``` + +`smoke.py` выполняет **один сквозной сценарий**, автоматически выбирая профиль из `lab.json`: health → три пользователя → вход с lab2 → чат → сообщения → пагинация → ошибки доступа → идемпотентность с lab3 → файл с lab4 → thumbnail с lab5 → logout. Он проверяет JSON по используемому подмножеству схемы, коды/headers, Unicode, SHA-256 оригинала и фактические JPEG-размеры thumbnail. Это публичный минимум, не полный fuzz/security/load suite. + +Каждый запуск создаёт уникальных синтетических пользователей, чат и сообщения. Данные автоматически не удаляются: в API курса нет delete. Для чистого повтора используйте отдельный тестовый стенд/volume и осознанный сброс своего окружения. Session tokens хранятся только в памяти процесса и не печатаются/не сохраняются. + +## Проверка сохранности, lab2+ + +Скопируйте `scripts/restart.example.sh` в `scripts/restart.sh`, реализуйте перезапуск **API и всех используемых хранилищ** с сохранением volumes и задайте executable bit. Скрипт может опираться на ваш compose.yaml или stack.yaml. Он не должен удалять volumes, повторно seed-ить БД или менять тестовые данные. + +```sh +chmod +x scripts/restart.sh +make test-persistence ACTION_SCRIPT=scripts/restart.sh +``` + +Тест создаёт данные и сессию, запускает указанный файл без shell interpolation, ожидает готовности и проверяет те же данные **с прежним токеном**. В lab4+ также проверяется исходный файл. Hook может работать до 90 секунд, готовность затем ожидается до 90 секунд. TTL сессии для этого теста — минимум 300 секунд. Успех не доказывает, что hook действительно перезапустил БД: приложите команды/состояния контейнеров до и после. + +## Проверка отказа, lab3+ + +Реализуйте `scripts/stop-one.sh` на основе примера. `TARGET_INSTANCE_ID` в окружении содержит alias обслужившей тест API-реплики: сопоставьте его своему контейнеру/Swarm task и остановите именно его. Скрипт должен быстро вернуть 0 и **оставить эту реплику остановленной**; восстановление выполняйте отдельно. Swarm может создать новую task с другим ID — это допустимо. + +```sh +chmod +x scripts/stop-one.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +``` + +Перед отказом тест наблюдает ≥2 API-реплики; 15 секунд отправляет сообщения параллельно выполнению hook, повторяет неопределённый POST с тем же ключом, проверяет восстановление записи за ≤10 секунд, отсутствие остановленной реплики в последних ответах, сохранность подтверждённых сообщений и отсутствие дублей. Ошибки переходного периода учитываются. Затем восстановите реплику и повторите для другой. Скрипт — проверка одного отказа API, не гарантия HA БД/LB/host. Вывод hook скрыт, чтобы не утекли секреты; отлаживайте его отдельно с безопасным выводом. + +## Нагрузка + +```sh +python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json +``` + +Это простой **closed-loop** генератор POST сообщений; он ограничен производительностью клиента и страдает coordinated omission. Он выдаёт successful RPS, ошибки и p50/p95/p99 **только успешных запросов**. Во время нагрузки нет прозрачных retry; timeout мог скрыть совершённую запись, поэтому это throughput HTTP-подтверждений, не точный счётчик COMMIT. Изменение размера истории входит в профиль. Для серьёзного исследования используйте k6/Locust/wrk либо свой обоснованный генератор, а не выводите максимальную пропускную способность из одного запуска этого скрипта. Для нагрузки pipeline изображений нужен отдельный сценарий студента. + +## HTTPS, lab7 + +```sh +make test BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt +make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt +``` + +Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. TLS-тест сначала проверяет рабочее доверенное соединение, затем намеренно пустой trust store и именно ошибку проверки сертификата; network timeout не засчитывается как правильный отказ. **Внутреннее mTLS, identity/authorization, OpenBao policy и hardening проверяют отдельные тесты студента** по trust matrix. Клиентский сертификат внешнему учебному REST-клиенту не требуется: mTLS находится на внутренних связях. + +## Что ещё остаётся доказать + +Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production. diff --git a/tests/client.py b/tests/client.py new file mode 100644 index 0000000..f0499a2 --- /dev/null +++ b/tests/client.py @@ -0,0 +1,217 @@ +"""HTTP helpers for public black-box tests; Python 3.9+, standard library only.""" +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import ssl +import time +import urllib.error +import urllib.request +import uuid + +ROOT = Path(__file__).resolve().parents[1] +LAB = json.loads((ROOT / 'lab.json').read_text())['number'] +SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text()) + +class Failure(AssertionError): + pass + +def check(condition, message): + if not condition: + raise Failure(message) + +def timestamp(value): + check(isinstance(value, str) and value.endswith('Z'), 'timestamp must be UTC ending in Z') + try: + return dt.datetime.fromisoformat(value[:-1] + '+00:00') + except ValueError as exc: + raise Failure('invalid RFC3339 timestamp') from exc + +def validate(value, schema, where='response'): + """Validate the JSON Schema subset used by the supplied contract, not arbitrary OpenAPI.""" + if '$ref' in schema: + target = SPEC + for part in schema['$ref'].split('/')[1:]: + target = target[part] + return validate(value, target, where) + kinds = schema.get('type', []) + if isinstance(kinds, str): + kinds = [kinds] + matches = {'null':value is None, 'boolean':isinstance(value,bool), 'integer':isinstance(value,int) and not isinstance(value,bool), 'number':isinstance(value,(int,float)) and not isinstance(value,bool), 'string':isinstance(value,str), 'array':isinstance(value,list), 'object':isinstance(value,dict)} + if kinds: + check(any(matches.get(k,False) for k in kinds), where + ': incorrect type') + if 'enum' in schema: + check(value in schema['enum'], where + ': invalid enum') + if 'const' in schema: + check(value == schema['const'], where + ': invalid const') + if isinstance(value,dict): + props = schema.get('properties',{}) + check(all(k in value for k in schema.get('required',[])), where + ': missing required fields') + if schema.get('additionalProperties') is False: + check(not set(value).difference(props), where + ': unexpected fields') + for key, sub in props.items(): + if key in value: + validate(value[key], sub, where + '.' + key) + if isinstance(value,list): + check(len(value) >= schema.get('minItems',0), where + ': too few items') + check(len(value) <= schema.get('maxItems',float('inf')), where + ': too many items') + if schema.get('uniqueItems'): + encoded = [json.dumps(x,sort_keys=True) for x in value] + check(len(encoded)==len(set(encoded)), where + ': duplicate items') + if 'items' in schema: + for item in value: + validate(item, schema['items'], where + '[]') + if isinstance(value,str): + check(len(value) >= schema.get('minLength',0), where + ': too short') + check(len(value) <= schema.get('maxLength',float('inf')), where + ': too long') + if 'pattern' in schema: + check(re.search(schema['pattern'], value) is not None, where + ': pattern mismatch') + if schema.get('format') == 'uuid': + try: + uuid.UUID(value) + except ValueError as exc: + raise Failure(where + ': invalid UUID') from exc + if schema.get('format') == 'date-time': + timestamp(value) + if isinstance(value,(int,float)) and not isinstance(value,bool): + check(value >= schema.get('minimum',-float('inf')), where + ': below minimum') + check(value <= schema.get('maximum',float('inf')), where + ': above maximum') + if 'anyOf' in schema: + for alternative in schema['anyOf']: + try: + validate(value, alternative, where) + break + except Failure: + pass + else: + raise Failure(where + ': no anyOf branch matches') + +def shape(value, name): + validate(value, SPEC['components']['schemas'][name]) + return value + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + +class Client: + def __init__(self, base_url=None, ca_file=None, timeout=10): + self.base = (base_url or os.environ.get('BASE_URL') or ('https://localhost:8443' if LAB==7 else 'http://localhost:8080')).rstrip('/') + check(self.base.startswith(('http://','https://')), 'BASE_URL must be HTTP(S)') + check(LAB != 7 or self.base.startswith('https://'), 'lab7 requires HTTPS') + self.timeout = timeout + context = ssl.create_default_context(cafile=ca_file or os.environ.get('CA_FILE') or None) + self.opener = urllib.request.build_opener(NoRedirect(), urllib.request.HTTPSHandler(context=context)) + + def call(self, method, path, expected=200, body=None, actor=None, headers=None, raw=None, schema=None): + h = {'Accept':'application/json'} + if actor: + h['X-User-Id' if LAB==1 else 'Authorization'] = actor['id'] if LAB==1 else 'Bearer ' + actor['token'] + if body is not None: + raw = json.dumps(body,ensure_ascii=False).encode('utf-8') + h['Content-Type'] = 'application/json' + h.update(headers or {}) + req = urllib.request.Request(self.base + path, data=raw, headers=h, method=method) + start = time.monotonic() + try: + response = self.opener.open(req, timeout=self.timeout) + except urllib.error.HTTPError as error: + response = error + except (urllib.error.URLError,TimeoutError,OSError) as exc: + # Do not print URL query, headers, request body, or credentials. + raise Failure(method + ' ' + path.split('?')[0] + ': connection/TLS failure (' + type(exc).__name__ + ')') from None + with response: + status = response.code + rh = response.headers + data = response.read(16*1024*1024 + 1) + check(len(data) <= 16*1024*1024, 'response exceeds test safety limit') + allowed = [expected] if isinstance(expected,int) else expected + check(status in allowed, method + ' ' + path.split('?')[0] + ': expected ' + str(allowed) + ', received ' + str(status)) + check(bool(rh.get('X-Request-Id')), 'missing X-Request-Id') + if LAB>=3: + check(bool(rh.get('X-Instance-Id')), 'missing X-Instance-Id') + payload = None + if schema or status>=400: + check(rh.get_content_type()=='application/json', 'expected application/json') + try: + payload = json.loads(data) + except (ValueError,UnicodeError): + raise Failure('invalid response JSON') from None + shape(payload, 'Error' if status>=400 else schema) + if status>=400: + check(payload['error']['request_id']==rh.get('X-Request-Id'),'error request_id differs from header') + if status==401 and LAB>=2: + scheme = 'Basic' if path=='/api/v1/auth/sessions' else 'Bearer' + check(rh.get('WWW-Authenticate','').lower().startswith(scheme.lower()), 'incorrect WWW-Authenticate challenge') + if status==204: + check(not data, '204 must not contain body') + return {'status':status,'headers':rh,'json':payload,'bytes':data,'elapsed':time.monotonic()-start} + + def user(self, label): + username = 'u_' + label + '_' + uuid.uuid4().hex[:12] + password = 'T3st-' + uuid.uuid4().hex + body = {'username':username,'display_name':'Студент ' + label} + if LAB>=2: + body['password'] = password + user = self.call('POST','/api/v1/users',201,body=body,schema='User')['json'] + check(user['username']==username,'username changed') + actor = {'id':user['id'],'user':user,'registration':body} + if LAB>=2: + credential = base64.b64encode((username+':'+password).encode()).decode() + session = self.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')['json'] + check(session['user']==user,'session user mismatch') + check(timestamp(session['expires_at']) > dt.datetime.now(dt.timezone.utc),'session already expired') + actor['token'] = session['token'] + return actor + + def bootstrap(self): + self.call('GET','/health/live',schema='Health') + self.call('GET','/health/ready',schema='Health') + alice, bob, eve = (self.user(label) for label in ('alice','bob','eve')) + chat = self.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Контрактный тест','member_ids':[alice['id'],bob['id']]},schema='Chat')['json'] + check(set(chat['member_ids'])=={alice['id'],bob['id']},'chat member mismatch') + return alice,bob,eve,chat + + def message(self, actor, chat, text, key=None, attachments=None): + body = {'text':text} + if attachments is not None: + body['attachment_ids'] = attachments + headers = {'Idempotency-Key':key or uuid.uuid4().hex} if LAB>=3 else {} + return self.call('POST','/api/v1/chats/'+chat['id']+'/messages',201,actor=actor,body=body,headers=headers,schema='Message') + + def attachment(self, actor, chat): + content = (ROOT / 'tests/fixtures/sample.png').read_bytes() + att = self.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png',201 if LAB==4 else 202,actor=actor,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')['json'] + check(att['status']==('ready' if LAB==4 else 'queued'),'incorrect upload status') + check(att['chat_id']==chat['id'] and att['owner_id']==actor['id'],'attachment ownership mismatch') + check(att['sha256']==hashlib.sha256(content).hexdigest() and att['size_bytes']==len(content),'original checksum/size mismatch') + return att,content + + def wait_ready(self, actor, att, wait_seconds=60): + deadline = time.monotonic()+wait_seconds + while time.monotonic()=2,'persistence requires lab2+') + check(args.mode!='failover' or LAB>=3,'failover requires lab3+') + script = Path(args.action_script).expanduser().resolve() + check(script.is_file() and os.access(script,os.X_OK),'action script must exist and be executable (chmod +x)') + check('.example.' not in script.name,'copy and implement the example hook first') + c = Client(args.base_url,args.ca_file,timeout=2) + alice,bob,eve,chat = c.bootstrap() + sent = c.message(alice,chat,'Сохранить при отказе') + original = sent['json'] + target = sent['headers'].get('X-Instance-Id','') + attachment = content = None + if LAB>=4: + attachment,content = c.attachment(alice,chat) + if LAB>=5: + attachment = c.wait_ready(alice,attachment) + env = dict(os.environ) + env['TARGET_INSTANCE_ID'] = target + observed = set() + if args.mode=='failover': + for _ in range(40): + observed.add(c.call('GET','/api/v1/users/me',actor=alice,schema='User')['headers']['X-Instance-Id']) + check(len(observed)>=2,'less than two API instances observed before failure; verify LB/session affinity') + print('Executing explicit '+args.mode+' hook; hook output suppressed to avoid leaking secrets.') + # No shell interpolation and no Docker commands in this test. + proc = subprocess.Popen([str(script)],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + started = time.monotonic() + successes,failures,after_instances = [],0,[] + try: + if args.mode=='persistence': + try: + code = proc.wait(timeout=90) + except subprocess.TimeoutExpired: + raise Failure('restart hook exceeded 90 seconds') from None + check(code==0,'restart hook failed (inspect your script locally)') + deadline = time.monotonic()+90 + while True: + try: + c.call('GET','/health/ready',schema='Health') + c.call('GET','/api/v1/users/me',actor=alice,schema='User') + break + except Failure: + check(time.monotonic()=5,'too few successful writes after stop') + check(target not in after_instances[-5:],'target replica still serves requests; hook must leave it stopped') + print(json.dumps({'observed_instances_before':len(observed),'successful_writes':len(successes),'failed_attempts':failures,'first_recovery_seconds':round(first_recovery,3)},ensure_ascii=False)) + # Existing token, no re-login. Read all confirmations and reject duplicates. + messages = history(c,bob,chat) + ids = [m['id'] for m in messages] + check(len(ids)==len(set(ids)),'duplicated message IDs in history') + check(any(m==original for m in messages),'confirmed pre-failure message lost or altered') + for msg in successes: + check(any(m==msg for m in messages),'confirmed in-flight message lost or altered') + # Bodies are unique in this scenario: an uncertain request may exist once, never twice. + texts = [m['text'] for m in messages] + check(len(texts)==len(set(texts)),'uncertain retry created duplicate message') + if attachment: + c.call('GET','/api/v1/attachments/'+attachment['id'],actor=bob,schema='Attachment') + downloaded = c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=bob) + check(downloaded['bytes']==content,'attachment lost or changed across failure') + print('PASS: '+args.mode+' preserved confirmed data and existing session. Hook scope needs operator evidence.') + finally: + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + +if __name__=='__main__': + run(main) diff --git a/tests/smoke.py b/tests/smoke.py new file mode 100644 index 0000000..4cbfa55 --- /dev/null +++ b/tests/smoke.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""One complete public acceptance scenario, cumulative by lab number.""" +import base64 +import hashlib +import uuid +from client import Client, LAB, arguments, check, run, timestamp + + +def main(): + args = arguments('Messenger public smoke; creates synthetic users and messages') + c = Client(args.base_url,args.ca_file) + alice,bob,eve,chat = c.bootstrap() + path = '/api/v1/chats/'+chat['id'] + c.call('POST','/api/v1/users',409,body=alice['registration']) + c.call('GET','/api/v1/users/me',401) + c.call('GET',path,404,actor=eve) + me = c.call('GET','/api/v1/users/me',actor=alice,schema='User')['json'] + check(me==alice['user'],'current user mismatch') + listed = c.call('GET','/api/v1/chats?limit=100',actor=bob,schema='ChatPage')['json'] + check(any(x['id']==chat['id'] for x in listed['items']),'member cannot list chat') + hidden = c.call('GET','/api/v1/chats?limit=100',actor=eve,schema='ChatPage')['json'] + check(all(x['id']!=chat['id'] for x in hidden['items']),'chat leaks to outsider') + key = uuid.uuid4().hex + first = c.message(alice,chat,'Привет, мир 👋',key=key)['json'] + second = c.message(bob,chat,'Сообщение Боба')['json'] + check(first['sender_id']==alice['id'] and second['sender_id']==bob['id'],'sender was not derived from actor') + check(first['chat_id']==second['chat_id']==chat['id'],'wrong chat in message') + check(first['text']=='Привет, мир 👋' and second['text']=='Сообщение Боба','message text changed') + page1 = c.call('GET',path+'/messages?limit=1',actor=bob,schema='MessagePage')['json'] + check(len(page1['items'])==1 and page1['next_cursor'],'first page must have one item and cursor') + from urllib.parse import quote + page2 = c.call('GET',path+'/messages?limit=1&cursor='+quote(page1['next_cursor'],safe=''),actor=alice,schema='MessagePage')['json'] + check(len(page2['items'])==1 and page2['next_cursor'] is None,'second page must finish history') + ordered = sorted([first,second],key=lambda x:(timestamp(x['created_at']),uuid.UUID(x['id']).int)) + check(page1['items']+page2['items']==ordered,'pagination lost, duplicated or reordered a message') + h = {'Idempotency-Key':uuid.uuid4().hex} if LAB>=3 else {} + c.call('POST',path+'/messages',400,actor=alice,body={'text':''},headers=h) + c.call('POST',path+'/messages',404,actor=eve,body={'text':'чужое'},headers=h) + c.call('GET',path+'/messages?limit=0',400,actor=alice) + if LAB>=2: + bad = base64.b64encode((alice['registration']['username']+':wrong-password').encode()).decode() + c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':'Basic '+bad}) + good = base64.b64encode((alice['registration']['username']+':'+alice['registration']['password']).encode()).decode() + c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Basic '+good}) + c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':alice['id']}) + me = c.call('GET','/api/v1/users/me',actor=alice,headers={'X-User-Id':eve['id']},schema='User')['json'] + check(me['id']==alice['id'],'X-User-Id overrode bearer identity') + if LAB>=3: + replay = c.message(alice,chat,first['text'],key=key)['json'] + check(replay==first,'idempotency replay differs') + c.call('POST',path+'/messages',409,actor=alice,body={'text':'другой body'},headers={'Idempotency-Key':key}) + c.call('POST',path+'/messages',400,actor=alice,body={'text':'без ключа'}) + if LAB>=4: + att,content = c.attachment(alice,chat) + # A queued attachment must already be linkable to its own chat. + attached = c.message(alice,chat,'',attachments=[att['id']])['json'] + check(attached['attachment_ids']==[att['id']],'message lost attachment') + ready = c.wait_ready(bob,att) if LAB>=5 else att + check(ready['error_code'] is None,'ready attachment has an error') + download = c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob) + check(download['bytes']==content,'download differs from original') + check(download['headers'].get_content_type()=='image/png','original content type mismatch') + for suffix in ('','/content'): + c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=eve) + if LAB>=5: + variants = [x for x in ready['variants'] if x['name']=='thumbnail'] + check(len(variants)==1,'expected exactly one thumbnail') + v = variants[0] + check((v['width'],v['height'])==(256,160),'thumbnail metadata has wrong dimensions') + thumb = c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',actor=bob) + check(thumb['headers'].get_content_type()=='image/jpeg','thumbnail content type mismatch') + check(len(thumb['bytes'])==v['size_bytes'] and hashlib.sha256(thumb['bytes']).hexdigest()==v['sha256'],'thumbnail checksum mismatch') + from image_probe import jpeg_size + check(jpeg_size(thumb['bytes'])==(256,160),'actual JPEG dimensions mismatch') + if LAB>=2: + c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice) + c.call('GET','/api/v1/users/me',401,actor=alice) + c.call('DELETE','/api/v1/auth/sessions/current',401,actor=alice) + print('PASS: lab%d public API scenario; infrastructure and grading evidence remain separate.' % LAB) + +if __name__=='__main__': + run(main)