forked from mtusi2026/mtusi2026lab3
выполнение лабы на 5
This commit is contained in:
@@ -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
|
||||
@@ -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
|
||||
@@ -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 содержит инструкцию именно моего решения.
|
||||
@@ -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
|
||||
@@ -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.
|
||||
+32
@@ -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.
|
||||
@@ -0,0 +1,19 @@
|
||||
# Работа через fork и pull request
|
||||
|
||||
1. После публикации преподавателем сделайте fork репозитория **текущей** лабораторной в своём аккаунте и clone своего fork. URL преподаватель выдаёт отдельно.
|
||||
2. Создайте ветку `solution/<group>-<surname>` от исходной ветки 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.
|
||||
@@ -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).
|
||||
+25
@@ -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"]
|
||||
@@ -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.
|
||||
@@ -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 в среде подготовки не был доступен. Это проверка материалов и тестовых драйверов, не приёмка будущих решений студентов.
|
||||
@@ -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
|
||||
@@ -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/)
|
||||
@@ -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 профиля.
|
||||
@@ -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: {}
|
||||
+105
@@ -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:
|
||||
@@ -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: <UUID существующего пользователя>`; отсутствие/неизвестный ID — 401. Это учебный выбор пользователя: любой клиент может выдать себя за другого.
|
||||
|
||||
**Lab2–7:** `POST /auth/sessions` принимает только `Authorization: Basic <base64(username:password)>`, без 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 <token>`. Истёкший/отозванный/неизвестный токен — 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, не бинарное содержимое.
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
||||
# Доказательства
|
||||
|
||||
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
|
||||
|
||||
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,2 @@
|
||||
2026-10-21T05:39:45Z target_instance=498a08cd2b5c container=498a08cd2b5cf94be02873ea9eb0c9c5f6b79133ddfd50b44aff134f86222b71
|
||||
2026-10-21T05:40:39Z target_instance=137c7f092d63 container=137c7f092d63cd2e0d8d2b71ceecd67860c35ba79709df56831bba3a967629ba
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,26 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="900" height="420" viewBox="0 0 900 420">
|
||||
<rect width="100%" height="100%" fill="white"/>
|
||||
<text x="450" y="28" text-anchor="middle" font-family="sans-serif" font-size="18">API scaling: average successful RPS</text>
|
||||
<line x1="60" y1="360" x2="840" y2="360" stroke="#333"/>
|
||||
<rect x="60.0" y="305.0" width="78" height="55.0" fill="#3572A5"/>
|
||||
<text x="99.0" y="297.0" text-anchor="middle" font-family="sans-serif" font-size="12">212.5</text>
|
||||
<text x="99.0" y="380" text-anchor="middle" font-family="sans-serif" font-size="12">fixed / 1</text>
|
||||
<rect x="177.0" y="305.0" width="78" height="55.0" fill="#3572A5"/>
|
||||
<text x="216.0" y="297.0" text-anchor="middle" font-family="sans-serif" font-size="12">212.7</text>
|
||||
<text x="216.0" y="380" text-anchor="middle" font-family="sans-serif" font-size="12">fixed / 2</text>
|
||||
<rect x="294.0" y="319.6" width="78" height="40.4" fill="#3572A5"/>
|
||||
<text x="333.0" y="311.6" text-anchor="middle" font-family="sans-serif" font-size="12">156.3</text>
|
||||
<text x="333.0" y="380" text-anchor="middle" font-family="sans-serif" font-size="12">fixed / 4</text>
|
||||
<rect x="411.0" y="305.3" width="78" height="54.7" fill="#E38B29"/>
|
||||
<text x="450.0" y="297.3" text-anchor="middle" font-family="sans-serif" font-size="12">211.7</text>
|
||||
<text x="450.0" y="380" text-anchor="middle" font-family="sans-serif" font-size="12">growth / 1</text>
|
||||
<rect x="528.0" y="203.5" width="78" height="156.5" fill="#E38B29"/>
|
||||
<text x="567.0" y="195.5" text-anchor="middle" font-family="sans-serif" font-size="12">605.0</text>
|
||||
<text x="567.0" y="380" text-anchor="middle" font-family="sans-serif" font-size="12">growth / 2</text>
|
||||
<rect x="645.0" y="75.6" width="78" height="284.4" fill="#E38B29"/>
|
||||
<text x="684.0" y="67.6" text-anchor="middle" font-family="sans-serif" font-size="12">1099.7</text>
|
||||
<text x="684.0" y="380" text-anchor="middle" font-family="sans-serif" font-size="12">growth / 4</text>
|
||||
<rect x="762.0" y="60.0" width="78" height="300.0" fill="#E38B29"/>
|
||||
<text x="801.0" y="52.0" text-anchor="middle" font-family="sans-serif" font-size="12">1160.0</text>
|
||||
<text x="801.0" y="380" text-anchor="middle" font-family="sans-serif" font-size="12">growth / 8</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.2 KiB |
@@ -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}}
|
||||
+35
@@ -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
|
||||
@@ -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-реплику.
|
||||
@@ -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
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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);
|
||||
@@ -0,0 +1,2 @@
|
||||
# Only for full OpenAPI/JSON Schema validation; HTTP tests use stdlib.
|
||||
openapi-spec-validator==0.7.2
|
||||
@@ -0,0 +1,3 @@
|
||||
psycopg[binary]==3.2.10
|
||||
psycopg-pool==3.3.3
|
||||
redis==5.2.1
|
||||
Executable
+27
@@ -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.'
|
||||
@@ -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()
|
||||
Executable
+10
@@ -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
|
||||
Executable
+9
@@ -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
|
||||
Executable
+35
@@ -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
|
||||
Executable
+10
@@ -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
|
||||
Executable
+32
@@ -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
|
||||
@@ -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.')
|
||||
@@ -0,0 +1 @@
|
||||
"""Messenger API application package."""
|
||||
+39
@@ -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()
|
||||
@@ -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")
|
||||
@@ -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
|
||||
+350
@@ -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,
|
||||
)
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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()
|
||||
+394
@@ -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
|
||||
@@ -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)
|
||||
@@ -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'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
|
||||
'<rect width="100%" height="100%" fill="white"/>',
|
||||
'<text x="450" y="28" text-anchor="middle" font-family="sans-serif" font-size="18">API scaling: average successful RPS</text>',
|
||||
f'<line x1="{margin}" y1="{height-margin}" x2="{width-margin}" y2="{height-margin}" stroke="#333"/>',
|
||||
]
|
||||
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'<rect x="{x:.1f}" y="{y:.1f}" width="{bar_width}" height="{bar_height:.1f}" fill="{color}"/>')
|
||||
parts.append(f'<text x="{x+bar_width/2:.1f}" y="{max(48,y-8):.1f}" text-anchor="middle" font-family="sans-serif" font-size="12">{value:.1f}</text>')
|
||||
parts.append(f'<text x="{x+bar_width/2:.1f}" y="{height-margin+20}" text-anchor="middle" font-family="sans-serif" font-size="12">{label}</text>')
|
||||
parts.append("</svg>")
|
||||
(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()
|
||||
@@ -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.
|
||||
+217
@@ -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()<deadline:
|
||||
att = self.call('GET','/api/v1/attachments/'+att['id'],actor=actor,schema='Attachment')['json']
|
||||
check(att['status']!='failed','attachment reached failed')
|
||||
if att['status']=='ready':
|
||||
return att
|
||||
time.sleep(0.3)
|
||||
raise Failure('attachment did not become ready within test deadline')
|
||||
|
||||
def arguments(description, configure=None):
|
||||
import argparse
|
||||
p = argparse.ArgumentParser(description=description)
|
||||
p.add_argument('--base-url', default=None)
|
||||
p.add_argument('--ca-file', default=None)
|
||||
if configure:
|
||||
configure(p)
|
||||
return p.parse_args()
|
||||
|
||||
def run(main):
|
||||
try:
|
||||
main()
|
||||
except (Failure,ValueError,OSError) as exc:
|
||||
print('FAIL:', str(exc))
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Small closed-loop HTTP write benchmark; not an open-loop capacity proof."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import time
|
||||
from client import Client, Failure, LAB, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--duration',type=float,default=30)
|
||||
p.add_argument('--concurrency',type=int,default=4)
|
||||
p.add_argument('--output',default=None,help='Optional JSON metrics, no session tokens')
|
||||
args = arguments('Synthetic POST message load, closed loop; creates users/messages',configure)
|
||||
check(1<=args.duration<=3600,'duration must be 1..3600 seconds')
|
||||
check(1<=args.concurrency<=128,'concurrency must be 1..128')
|
||||
c = Client(args.base_url,args.ca_file)
|
||||
alice,bob,eve,chat = c.bootstrap()
|
||||
barrier = threading.Barrier(args.concurrency)
|
||||
def worker(worker_id):
|
||||
local = Client(args.base_url,args.ca_file,timeout=5)
|
||||
barrier.wait()
|
||||
deadline = time.monotonic()+args.duration
|
||||
latencies,errors = [],0
|
||||
index = 0
|
||||
while time.monotonic()<deadline:
|
||||
start = time.monotonic()
|
||||
try:
|
||||
local.message(alice,chat,'load-%s-%s' % (worker_id,index))
|
||||
latencies.append(time.monotonic()-start)
|
||||
except Failure:
|
||||
errors += 1
|
||||
index += 1
|
||||
return latencies,errors
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
results = list(pool.map(worker,range(args.concurrency)))
|
||||
elapsed = time.monotonic()-started
|
||||
latencies = sorted(x for values,_ in results for x in values)
|
||||
errors = sum(n for _,n in results)
|
||||
total = len(latencies)+errors
|
||||
def percentile(p):
|
||||
return round(1000*latencies[max(0,math.ceil(p*len(latencies))-1)],3) if latencies else None
|
||||
report = {'lab':LAB,'workload':'closed-loop POST messages; no automatic retries','requested_duration_seconds':args.duration,'elapsed_seconds':round(elapsed,3),'concurrency':args.concurrency,'successful_requests':len(latencies),'failed_requests':errors,'error_ratio':round(errors/total,6) if total else None,'successful_rps':round(len(latencies)/elapsed,3),'successful_latency_ms':{'p50':percentile(.50),'p95':percentile(.95),'p99':percentile(.99)},'note':'Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.'}
|
||||
text = json.dumps(report,ensure_ascii=False,indent=2)
|
||||
if args.output:
|
||||
dest = Path(args.output)
|
||||
dest.parent.mkdir(parents=True,exist_ok=True)
|
||||
dest.write_text(text+'\n')
|
||||
print(text)
|
||||
check(bool(latencies),'no successful writes')
|
||||
# Errors are reported, not treated as a universal load-test threshold.
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit operator-authored hook; tokens remain in memory, volumes are never removed by this test."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
from client import Client, Failure, LAB, arguments, check, run
|
||||
|
||||
|
||||
def history(c, actor, chat):
|
||||
path = '/api/v1/chats/'+chat['id']+'/messages?limit=100'
|
||||
result = []
|
||||
seen = set()
|
||||
for _ in range(1000):
|
||||
page = c.call('GET',path,actor=actor,schema='MessagePage')['json']
|
||||
result.extend(page['items'])
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
return result
|
||||
check(cursor not in seen,'cursor cycle')
|
||||
seen.add(cursor)
|
||||
path = '/api/v1/chats/'+chat['id']+'/messages?limit=100&cursor='+quote(cursor,safe='')
|
||||
raise Failure('history pagination exceeded safety bound')
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--mode', choices=['persistence','failover'], required=True)
|
||||
p.add_argument('--action-script',required=True,help='Executable script authored by student; restarts stack or stops ONE API replica')
|
||||
args = arguments('Explicit restart/failover scenario; modifies only synthetic API data',configure)
|
||||
check(LAB>=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()<deadline,'stack/session did not recover within 90 seconds')
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
first_recovery = None
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Запись во время отказа ' + key
|
||||
while time.monotonic()-started < 15:
|
||||
code = proc.poll()
|
||||
check(code is None or code==0,'stop-one hook failed (inspect your script locally)')
|
||||
check(code is not None or time.monotonic()-started<10,'stop-one hook must return within 10 seconds')
|
||||
try:
|
||||
response = c.message(alice,chat,text,key=key)
|
||||
msg = response['json']
|
||||
if code==0:
|
||||
if first_recovery is None:
|
||||
first_recovery = time.monotonic()-started
|
||||
after_instances.append(response['headers']['X-Instance-Id'])
|
||||
successes.append(msg)
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Запись во время отказа ' + key
|
||||
except Failure:
|
||||
failures += 1
|
||||
# Keep SAME key/body after an uncertain POST result.
|
||||
time.sleep(0.1)
|
||||
check(proc.poll()==0,'stop-one hook did not finish successfully')
|
||||
check(first_recovery is not None and first_recovery<=10,'writes did not recover within 10 seconds from hook start')
|
||||
check(len(after_instances)>=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)
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user