commit 6a4cd9534f6805aedb109b77788c4f865a66b484 Author: EgorAnti Date: Tue Nov 3 11:17:30 2026 +0300 create tasks from 4 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..bc16e556 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,20 @@ +.git +.github +.env +.env.* +!.env.example +secrets +certs +volumes +data +backups +*.key +*.pem +*.p12 +*.pfx +*.jks +.venv +__pycache__ +node_modules +evidence +.DS_Store diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..a260ab09 --- /dev/null +++ b/.env.example @@ -0,0 +1,18 @@ +# Copy to .env for the local synthetic lab environment. Never commit .env. +APP_PORT=8080 +DATABASE_NAME=messenger +DATABASE_USER=messenger +DATABASE_PASSWORD=replace-with-a-local-random-password +DATABASE_POOL_SIZE=10 +DATABASE_MIN_IDLE=2 +DATABASE_QUERY_TIMEOUT_SECONDS=5 +DATABASE_TRANSACTION_TIMEOUT_SECONDS=5 +SESSION_TTL_SECONDS=3600 +USER_CACHE_TTL_SECONDS=300 +IDEMPOTENCY_TTL_SECONDS=86400 +REDIS_CONNECT_TIMEOUT=1s +REDIS_COMMAND_TIMEOUT=500ms +REDIS_POOL_MAX_ACTIVE=8 +REDIS_POOL_MAX_IDLE=8 +REDIS_POOL_MIN_IDLE=0 +REDIS_POOL_MAX_WAIT=500ms diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..e6e63eb2 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,18 @@ +## Лабораторная 3 + +Автор / группа: TODO +Целевая оценка (3/4/5): TODO +Трек 5, если заявлен: TODO + +Что реализовано и что перенесено: TODO +Команды запуска из чистого clone: TODO +Результаты проверок и ссылка на REPORT.md: TODO +Ограничения / известные ошибки: TODO +Источники и использование ИИ: TODO + +- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. +- [ ] Контракт и публичные тесты не ослаблены. +- [ ] make check и make test выполнены; приложен реальный вывод. +- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. +- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. +- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. diff --git a/.github/workflows/contracts.yml b/.github/workflows/contracts.yml new file mode 100644 index 00000000..11cf289f --- /dev/null +++ b/.github/workflows/contracts.yml @@ -0,0 +1,16 @@ +name: Skeleton contracts +on: [push, pull_request] +permissions: + contents: read +jobs: + contracts: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -r requirements-dev.txt + - run: make check validate PYTHON=python +# This job validates the skeleton, not a student solution. +# Add build, readiness and make test in a separate application job. diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..b5a71896 --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +# Local/private state +.env +.env.* +!.env.example +secrets/ +certs/private/ +*.key +*.p12 +*.pfx +*.jks +*.pem +*.tfstate* +volumes/ +data/ +backups/ +# Runtime/build artifacts +.venv/ +__pycache__/ +*.py[cod] +node_modules/ +dist/ +build/ +target/ +bin/ +obj/ +coverage/ +*.log +.DS_Store +.idea/ +.vscode/ +# Keep small, sanitized evidence summaries in evidence/ under version control. +# Inspect git diff --cached: ignore rules are not a secret scanner. diff --git a/.gradle/9.7.1/checksums/checksums.lock b/.gradle/9.7.1/checksums/checksums.lock new file mode 100644 index 00000000..83712aa7 Binary files /dev/null and b/.gradle/9.7.1/checksums/checksums.lock differ diff --git a/.gradle/9.7.1/executionHistory/executionHistory.bin b/.gradle/9.7.1/executionHistory/executionHistory.bin new file mode 100644 index 00000000..1c97ae40 Binary files /dev/null and b/.gradle/9.7.1/executionHistory/executionHistory.bin differ diff --git a/.gradle/9.7.1/executionHistory/executionHistory.lock b/.gradle/9.7.1/executionHistory/executionHistory.lock new file mode 100644 index 00000000..bb1ff082 Binary files /dev/null and b/.gradle/9.7.1/executionHistory/executionHistory.lock differ diff --git a/.gradle/9.7.1/fileChanges/last-build.bin b/.gradle/9.7.1/fileChanges/last-build.bin new file mode 100644 index 00000000..f76dd238 Binary files /dev/null and b/.gradle/9.7.1/fileChanges/last-build.bin differ diff --git a/.gradle/9.7.1/fileHashes/fileHashes.bin b/.gradle/9.7.1/fileHashes/fileHashes.bin new file mode 100644 index 00000000..31713fc9 Binary files /dev/null and b/.gradle/9.7.1/fileHashes/fileHashes.bin differ diff --git a/.gradle/9.7.1/fileHashes/fileHashes.lock b/.gradle/9.7.1/fileHashes/fileHashes.lock new file mode 100644 index 00000000..f20a654d Binary files /dev/null and b/.gradle/9.7.1/fileHashes/fileHashes.lock differ diff --git a/.gradle/9.7.1/fileHashes/resourceHashesCache.bin b/.gradle/9.7.1/fileHashes/resourceHashesCache.bin new file mode 100644 index 00000000..971f431a Binary files /dev/null and b/.gradle/9.7.1/fileHashes/resourceHashesCache.bin differ diff --git a/.gradle/9.7.1/gc.properties b/.gradle/9.7.1/gc.properties new file mode 100644 index 00000000..e69de29b diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock new file mode 100644 index 00000000..33e5c47a Binary files /dev/null and b/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ diff --git a/.gradle/buildOutputCleanup/cache.properties b/.gradle/buildOutputCleanup/cache.properties new file mode 100644 index 00000000..1cc1df5f --- /dev/null +++ b/.gradle/buildOutputCleanup/cache.properties @@ -0,0 +1,2 @@ +#Mon Nov 02 12:42:00 MSK 2026 +gradle.version=9.7.1 diff --git a/.gradle/buildOutputCleanup/outputFiles.bin b/.gradle/buildOutputCleanup/outputFiles.bin new file mode 100644 index 00000000..7919f028 Binary files /dev/null and b/.gradle/buildOutputCleanup/outputFiles.bin differ diff --git a/.gradle/vcs-1/gc.properties b/.gradle/vcs-1/gc.properties new file mode 100644 index 00000000..e69de29b diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..ee5533d1 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# Работа через fork и pull request + +1. После публикации преподавателем сделайте fork репозитория **текущей** лабораторной в своём аккаунте и clone своего fork. URL преподаватель выдаёт отдельно. +2. Создайте ветку `solution/-` от исходной ветки skeleton. Ветка преподавателя и файлы контракта остаются основой проверки. +3. Для lab2–7 перенесите из своей предыдущей лабы только исходники, миграции, собственные тесты, Dockerfile и нужные конфигурации. Не копируйте `.git`, `.env`, credentials, volumes, `README.md`, `COURSE.md`, публичные `tests/` и `contracts/` поверх новой версии. Сначала сравните изменения API в `COURSE.md`. +4. Реализуйте задание, добавьте свою инструкцию запуска и заполните `REPORT.md`. Публичные проверки дополняйте отдельными тестами, не ослабляйте assertions. +5. Выполните `make check`, запустите свой стенд, затем `make test`. Выполните сценарии отказов текущей лабы. Их запуск всегда явный: scaffold сам не останавливает контейнеры. +6. Commit и push делайте в свой fork. Откройте PR в исходный репозиторий преподавателя, заголовок: `ЛР N — Группа — Фамилия — на 3/4/5`. Выберите правильную базовую ветку и заполните шаблон. +7. После замечаний обновляйте тот же PR. Чужие решения не переносите без указания источника и согласованных правил курса. + +Платформа может называть PR «merge request» — процесс тот же. `.github/` содержит необязательные удобства для GitHub; проверки локально от платформы не зависят. Инициализация и публикация исходных Git-репозиториев выполняются преподавателем отдельно. + +## Правила изменения skeleton + +Не удаляйте обязательные endpoint, поля, рубрику и публичные проверки. Изменение контракта согласуйте отдельным комментарием/PR; обход тестов не является решением. Код приложения размещайте в `src/` либо в принятой для языка структуре. Собственные тесты — `student-tests/` или штатный каталог фреймворка. Ссылки на результаты проверки и команды запуска должны переживать clone на другой машине. + +## CI + +Готовый GitHub workflow проверяет целостность контракта и синтаксис Python-проверок. Он **не запускает отсутствующее приложение** и **не подтверждает оценку**. Студент добавляет сборку своего приложения, запуск/готовность стенда и `make test` в отдельный job. Не используйте `pull_request_target` для запуска кода из fork, не выдавайте CI секреты или доступ к общему Docker-host. diff --git a/COURSE.md b/COURSE.md new file mode 100644 index 00000000..b02172bb --- /dev/null +++ b/COURSE.md @@ -0,0 +1,53 @@ +# Сквозной проект: мессенджер под нагрузкой + +Семь самостоятельных репозиториев содержат задания и проверяемые контракты одной системы. Вы переносите собственную реализацию между лабораторными. Язык, фреймворк и библиотеки выбираете сами. Web UI, WebSocket, редактирование/удаление сообщений, публичный поиск пользователей и Kubernetes не входят в обязательный минимум: достаточно REST API. + +| Лаба | Новая инженерная задача | Что появляется в системе | +| --- | --- | --- | +| 1 | Контракт, процессы и контейнер | In-memory API, Dockerfile, HTTP smoke | +| 2 | Сохранность и идентификация | PostgreSQL, Basic → сессия; Redis/Valkey на 4 | +| 3 | Горизонтальное масштабирование | Балансировщик, ≥2 API-реплики, общие сессии, идемпотентность | +| 4 | Бинарные данные | Приватное S3-совместимое хранилище и вложения | +| 5 | Фоновая работа | Брокер, worker, состояния вложений и преобразование изображений | +| 6 | Диагностика | OTel Collector, хранилища сигналов, Grafana | +| 7 | Защита и эксплуатация | Argon2id, TLS/mTLS, OpenBao, минимальные привилегии | + +## Как оценивать + +Оценки накопительные **внутри лабораторной**: 4 = весь уровень 3 + весь уровень 4; 5 = весь уровень 4 + **один** полностью выполненный трек 5 на выбор. Несколько недоделанных треков не заменяют один завершённый. Условие «весь уровень» включает реализацию, проверку и объяснение на защите. Красивые схемы и дополнительные технологии не компенсируют неработающий обязательный сценарий. + +Для начала следующей лабы достаточно обязательного минимума предыдущей. Сохраняются предыдущие обязательные возможности, с явно описанными переходами API ниже. Не требуется сначала получить 5 за все ранние лабы. Можно исправлять свою базу по ходу курса; такие исправления выделяйте в PR. Реализация на 3 работоспособна, но не претендует на промышленную готовность. Даже 5 в lab7 — учебная доказанная защита в заявленной модели угроз, а не сертификат полной безопасности. + +На 3 студент самостоятельно собирает рабочую систему. На 4 показывает практики, ожидаемые от стажёра/джуна в команде: воспроизводимость, диагностику, обработку ошибок и проверки отказов. На 5 формулирует гипотезу, ставит эксперимент, приводит измерения и обсуждает границы решения — это предмет конкретной похвалы магистранту. + +## Контракт и совместимость + +`contracts/openapi.json` — OpenAPI 3.1.0, `contracts/README.md` — нормативная семантика. Контракт каждого репозитория самодостаточен; соседние папки на машине преподавателя не нужны. `tests/` — публичные проверки, а не эталонное решение. Контракт, рубрика и публичные тесты имеют приоритет над случайным поведением библиотек. При противоречии создайте вопрос преподавателю; не подгоняйте тест под приложение. + +Три объявленных изменения обязательного API: + +1. **1 → 2:** регистрация требует `password`; `X-User-Id` заменяется Bearer. Basic используется только при создании сессии. +2. **2 → 3:** `Idempotency-Key` обязателен для отправки сообщения; ответы API содержат `X-Instance-Id`. +3. **4 → 5:** загрузка вложения возвращает `202` вместо `201`, состояние становится асинхронным. Клиент опрашивает метаданные. Старое текстовое сообщение остаётся валидным: `attachment_ids` по умолчанию `[]`. + +У lab7 меняется транспорт на HTTPS, бизнес-эндпоинты остаются прежними. Внутреннее mTLS не заменяет пользовательскую сессию. Новые возможности на 4/5 добавляйте обратно совместимо, в отдельном `contracts/extensions.openapi.json` или документе; обязательный контракт сохраняйте. + +## Общая предметная модель + +Пользователь (`username`, `display_name`) состоит в чатах. Список участников задаётся при создании чата и в обязательном API не изменяется. В чате отправляются сообщения, с lab4 — со ссылками на вложения этого чата. Сервер назначает UUID и время. Порядок истории — `(created_at, id)` по возрастанию. Для защиты достаточно показать взаимодействие нескольких API-клиентов; фронтенд не требуется. + +С lab2 данные PostgreSQL — источник истины. Сессии могут храниться в PostgreSQL или Redis/Valkey, если выполняют контракт срока жизни и перезапуска. Файлы с lab4 живут в S3, метаданные — в PostgreSQL. Redis и Valkey — альтернативы: оба одновременно не нужны. Аналогично выбирается одно S3-хранилище, один брокер и один основной путь оркестрации. + +## Воспроизводимость и честные измерения + +- Укажите версии runtime и контейнерных образов, аппаратную конфигурацию, CPU/RAM-лимиты, команду запуска и время прогрева. Для образов используйте явный тег версии или digest, не `latest`. +- Все тестовые пользователи и изображения синтетические. `make test` создаёт данные: запускайте его на учебном стенде. Не публикуйте пароли, токены, приватные ключи, персональные данные или подписанные URL. +- Минимальный отчёт о нагрузке: длительность, конкуренция/интенсивность, успешные RPS, доля ошибок, p50/p95/p99, CPU/RAM, размер набора данных. Универсального проходного RPS для разных ноутбуков нет. +- Сравнивайте одинаковые запросы при одинаковых ресурсах. Успешный `/health/live` не доказывает сохранность сообщений, а HTTP `202` — окончание обработки. +- Один Docker-host не обеспечивает отказоустойчивость к потере этого host. Несколько API-процессов не делают единственную БД или LB высокодоступными. Отдельно называйте, какие отказы выдерживает эксперимент. + +## Что сдавать + +Исходники, Dockerfile, нужные манифесты и конфигурации, миграции, собственные тесты, заполненный `REPORT.md`, сведения об использовании внешнего кода и ИИ. Уметь объяснить и изменить своё решение на защите обязательно. Приложите команды и текстовые результаты; скриншоты — дополнение, а не единственное доказательство. + +PR должен собираться из чистого clone по инструкции автора. Секреты создаются отдельно; тестовые fixtures и открытые конфигурации хранятся в репозитории. Перенос кода между лабами описан в [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..4729dd8b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,37 @@ +# Stage 1: Build +FROM eclipse-temurin:23-jdk AS build + +WORKDIR /app + +COPY gradlew . +COPY gradle gradle +COPY build.gradle settings.gradle ./ + +COPY src src + +RUN --mount=type=cache,target=/root/.gradle \ + chmod +x gradlew && ./gradlew bootJar --no-daemon + + +# Stage 2: Runtime +FROM eclipse-temurin:23-jre + +WORKDIR /app + +COPY --from=build /app/build/libs/*.jar app.jar + +RUN apt-get update \ + && apt-get install --yes --no-install-recommends curl \ + && rm -rf /var/lib/apt/lists/* \ + && useradd --system --create-home messenger + +USER messenger + +EXPOSE 8080 + +STOPSIGNAL SIGTERM + +HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \ + CMD curl --fail --silent --show-error http://localhost:8080/health/ready || exit 1 + +ENTRYPOINT ["java", "-jar", "app.jar"] diff --git a/Dockerfile.example b/Dockerfile.example new file mode 100644 index 00000000..e333a12e --- /dev/null +++ b/Dockerfile.example @@ -0,0 +1,8 @@ +# Teaching outline, not a runnable Dockerfile. Implement your own Dockerfile. +# 1. Choose a runtime/toolchain version and pin the base image tag/digest. +# 2. Copy dependency manifests first; install from the language lockfile. +# 3. Copy source and build. For compiled languages use a separate runtime stage. +# 4. Run the HTTP process as PID 1; listen on 0.0.0.0:8080. +# 5. Add non-root, signals and healthcheck according to the current rubric. +# 6. Pass runtime config/secrets at startup, never COPY .env or secret files. +# This file deliberately has no FROM/CMD: selecting/implementing them is the task. diff --git a/MAINTAINERS.md b/MAINTAINERS.md new file mode 100644 index 00000000..30157433 --- /dev/null +++ b/MAINTAINERS.md @@ -0,0 +1,38 @@ +# Памятка преподавателю — лабораторная 3 + +## Что подготовлено + +Язык реализации не задан. README содержит накопительные уровни 3/4/5, сценарий защиты и вопросы. В каждой лабе собственная полная версия OpenAPI, поэтому fork не зависит от соседних каталогов. Публичный HTTP smoke не содержит реализации сервера; Dockerfile.example и compose.example.yaml (если есть) — задания/ориентиры, не готовый deployment. + +## Перед публикацией + +1. Выберите GitHub/GitLab и организацию, опубликуйте каждый каталог как отдельный template/skeleton repository, сообщите студентам URL и правила именования PR/MR. Эти материалы не публикуют репозитории автоматически. +2. Задайте default branch, защиту исходных материалов и правила приёма. `.github/` уже содержит шаблон PR и CI контракта; в GitLab перенесите эквивалентные настройки, локальные Makefile-команды одинаковы. +3. Сообщите, индивидуальная работа или командная, сроки, правила использования стороннего кода/ИИ и ресурсы демонстрационного стенда. Эти организационные решения намеренно не выдуманы в задании. +4. Уточните ограничения площадки (например доступна ли виртуализация/несколько узлов). Для 5 предусмотрено по два трека: один можно выполнить без настоящего multi-node cloud. Универсальный проходной RPS не установлен. + +## Что проверять + +| Проверка | Что подтверждает | Чего не подтверждает | +| --- | --- | --- | +| make check | Структура файлов, JSON, локальные refs, синтаксис Python | Реализация/запуск API | +| make validate | Полная OpenAPI 3.1, JSON Schema и примеры | Поведение сервера | +| make test | Один сквозной контрактный сценарий текущей лабы | Все ошибки, persistence, HA, security | +| test-persistence (lab2+) | Данные/прежний токен после вызова restart hook | Реальный перезапуск, если hook — no-op | +| test-failover (lab3+) | Смена обслуживающей реплики, сохранность, retry без дубля | Несколько физических узлов, HA DB/LB | +| test-security (lab7) | Доверенный HTTPS и отказ недоверенного CA | Внутреннее mTLS/identity/ACL/OpenBao | +| Защита и тесты студента | Реальность инфраструктуры и критерии выбранного уровня | Неограниченная промышленная безопасность | + +Проверяйте реальные контейнеры/логи процессов и данные до/после отказа: одного X-Instance-Id недостаточно. Для 4 требуются все пункты 3+4, для 5 — все пункты 3+4 и один **завершённый** трек 5. Сравнивайте подтверждённые результаты со сформулированными критериями, а не количество установленных сервисов. + +## Приём PR + +Проверка запускается на изолированном учебном окружении с синтетическими secrets, не на общей production БД. Студенческие Dockerfile/hooks/CI — выполняемый код: обычный fork workflow без секретов и без доступа к общему Docker socket. Не запускайте PR через pull_request_target с привилегиями преподавателя. + +Исходные README/контракт/публичные tests сохраняются, реализация переносится студентом между лабами через собственные исходники и миграции. Исправление общей спецификации публикуйте отдельным изменением, объясняя влияние на все затронутые лабораторные. + +## Проверка этой версии skeleton + +На 2026-09-10 выполнены структурные проверки и полная валидация всех семи OpenAPI/JSON Schema, проверка локальных Markdown-ссылок/YAML и декодирование PNG fixture. HTTP-клиенты проверены на временном изолированном тестовом стенде: позитивный smoke 1–7, отрицательные варианты неправильного sender, pagination, ACL, logout, bytes и пустого API; также пути persistence/failover/load и внешнего TLS. + +Временный стенд не включён в студенческие каталоги и не является эталонным решением. Реальное приложение, Compose, PostgreSQL/S3/broker и mTLS/OpenBao в skeleton отсутствуют: их работоспособность не заявляется. Docker CLI в среде подготовки не был доступен. Это проверка материалов и тестовых драйверов, не приёмка будущих решений студентов. diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..2bf01cf1 --- /dev/null +++ b/Makefile @@ -0,0 +1,37 @@ +PYTHON ?= python3 +BASE_URL ?= http://localhost:8080 +CA_FILE ?= +ACTION_SCRIPT ?= +TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) + +.PHONY: help check validate test test-idempotency load test-persistence test-failover test-failover-each test-rolling + +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) + +test-idempotency: + $(PYTHON) tests/idempotency_concurrent.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +load: + $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-persistence: + $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-failover: + $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-failover-each: + $(PYTHON) tests/failover_each.py --action-script "$(ACTION_SCRIPT)" --restore-script "$(RESTORE_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-rolling: + $(PYTHON) tests/rolling_update.py --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) diff --git a/README.md b/README.md new file mode 100644 index 00000000..f11a3fd3 --- /dev/null +++ b/README.md @@ -0,0 +1,189 @@ +# Лабораторная 3. Балансировка и отказ API-реплики + +Запустить несколько взаимозаменяемых экземпляров API за единой точкой входа и сохранить корректность при остановке одного из них. + +Это **skeleton**, а не готовый сервер. Здесь есть задание, контракт и публичные проверки. Реализацию приложения, Dockerfile и требуемую инфраструктуру пишет студент. Язык и framework свободные; UI не обязателен. + +[Карта курса](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 — на выбор. + +## Реализованный запуск Compose + Nginx + +В этой реализации публичный порт есть только у Nginx. API масштабируется как +один Compose-service без `container_name`; сессии, сообщения и результаты +идемпотентности находятся в общей PostgreSQL. Redis используется только как +необязательный общий cache с безопасным fallback в PostgreSQL. + +Из чистого clone выполните одну последовательность (после копирования +`.env.example` замените локальный пароль): + +```sh +cp .env.example .env +# отредактировать DATABASE_PASSWORD в .env +docker compose --env-file .env build api +docker compose --env-file .env up -d postgres redis +docker compose --env-file .env run --rm migrate +docker compose --env-file .env up -d --scale api=2 api nginx +curl --fail http://localhost:8080/health/ready +``` + +`migrate` — отдельный one-shot процесс; в API Flyway отключён. При обновлении +схемы сначала выполняется совместимая миграция той же командой, затем API +заменяются по одной. Nginx 1.27.4 обновляет адреса `api` через Docker DNS каждые +2 секунды, применяет `least_conn`, не использует sticky session и повторяет +ошибку соединения/502/503/504 на другой реплике. Readiness проверяет завершение +V3-схемы, доступность PostgreSQL и состояние Spring `ACCEPTING_TRAFFIC`. + +Проверки после запуска: + +```sh +make test +make test-idempotency +chmod +x scripts/stop-one.sh scripts/restart.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +make test-persistence ACTION_SCRIPT=scripts/restart.sh +``` + +В Windows PowerShell те же проверки можно выполнить с +`scripts/stop-one.cmd` и `scripts/restart.cmd`; `.sh` остаются основными +POSIX hooks для CI/защиты. + +`test-idempotency` одновременно отправляет 32 одинаковых запроса и требует, +чтобы ответы пришли минимум от двух `X-Instance-Id`, но в истории появилось +ровно одно сообщение. `stop-one.sh` сопоставляет полученный `X-Instance-Id` с +hostname контейнера и останавливает только эту API-реплику. После демонстрации +её можно вернуть командой: + +```sh +docker compose --env-file .env up -d --scale api=2 api +``` + +### Проверки уровня 4 + +Обе реплики последовательно останавливаются с восстановлением между опытами: + +```sh +make test-failover-each \ + ACTION_SCRIPT=scripts/stop-one.sh \ + RESTORE_SCRIPT=scripts/restore-api.sh +``` + +В Windows используйте `.cmd` варианты. Тест сохраняет по каждой реплике +successful RPS, число ошибок и время первой успешной операции после stop. + +Эквивалент rolling update для Compose — последовательная замена каждого +исходного API-контейнера с ожиданием readiness новой реплики перед заменой +следующей. Проверка одновременно держит четыре потока записи: + +```sh +make test-rolling ACTION_SCRIPT=scripts/rolling-update.sh +``` + +Nginx обновляет Docker DNS раз в 2 секунды. Сетевой отказ определяется не +позднее connect timeout 500 ms, зависший ответ — read timeout 4 s; адрес +пассивно исключается на 2 s после первой ошибки. Поэтому верхняя граница +обнаружения одного неотвечающего backend — 4 s, а две upstream-попытки +укладываются примерно в 8.5 s. Docker readiness каждой API проверяется раз в +2 s с timeout 2 s. Nginx OSS использует readiness при начальном/операторском +запуске через Compose и пассивное исключение во время работы. + +Для `POST /chats/{id}/messages` Nginx может повторить запрос на второй backend +даже после начала отправки: тело буферизуется, а обязательный общий +`Idempotency-Key` делает такой retry безопасным. Для остальных POST параметр +`non_idempotent` не включён, чтобы не размножать пользователей или чаты. + +## Что сделать + +1. Выберите Compose + Nginx/HAProxy/Traefik либо Docker Swarm. Для выбранного варианта дайте одну последовательность запуска. +2. Уберите локальные сессии/другие данные, от которых зависит корректность, из API. Миграции выполняйте отдельно и согласованно, а не гонкой всех реплик. +3. Настройте балансировщик, проверки готовности, DNS/обновление backend-адресов и graceful shutdown. Не закрепляйте клиента sticky session как способ исправить раздельное состояние. +4. Реализуйте общую идемпотентность отправки сообщения. Проверьте одинаковый ключ одновременно через разные реплики. +5. Подготовьте явный action script, останавливающий одну выбранную API-реплику, и продемонстрируйте чтение/запись во время отказа. + +## Оценка «3»: работающий минимум + +- Весь стенд описан в compose.yaml или stack.yaml, запускается документированной командой. Не менее двух API-реплик, одна публичная точка входа, одна общая БД и общее хранилище сессий. +- Разные запросы одного пользователя обслуживаются разными репликами без повторного входа. Это видно по X-Instance-Id. Доступ через LB — основной проверяемый маршрут. +- Можно остановить любую одну API-реплику при работающей другой: не позднее 10 секунд продолжаются новые чтения/записи, подтверждённые сообщения доступны. Краткие ошибки/оборванные запросы во время обнаружения отказа измеряются и допустимы. +- Повтор POST сообщения с тем же Idempotency-Key не создаёт дубль, включая конкурентный повтор и переключение реплики. Неподтверждённую запись клиент может безопасно повторить с тем же ключом. +- make test, persistence и failover-сценарий проходят; для failover проверяется наличие ≥2 наблюдаемых реплик. Для Swarm сборка образа и его доступность узлам описаны отдельно. + +## Оценка «4»: уровень стажёра/джуна + +Весь уровень 3 **и все** пункты ниже: + +- Health/readiness, timeouts и прекращение приёма при SIGTERM настроены согласованно; LB исключает недоступный backend. Укажите период проверок и максимальное время обнаружения отказа. +- Последовательно остановите каждую API-реплику (восстанавливая предыдущую); соберите RPS, ошибки и время восстановления. Общая идемпотентность проверяется параллельными запросами с одним ключом. +- Контейнеры имеют CPU/RAM-лимиты, API не публикуют порты наружу в обход LB; секреты и хранилища общие только там, где нужно. Нет container_name, мешающего масштабированию одного Compose-service. +- Rolling update или эквивалентная поочерёдная замена проверена под нагрузкой. Миграции запускаются однократно и совместимы с работающей версией либо ограничение честно описано. + +## Оценка «5»: исследование и доказанный результат + +Весь уровень 4 **и один законченный трек на выбор**. Приведите гипотезу, повторяемую методику, результаты и ограничения. + +**Трек 1. Цена масштабирования.** При фиксированном суммарном CPU/RAM сравните 1/2/4 API-реплики на одном профиле нагрузки; затем проведите серию с ростом ресурсов. Найдите saturation point БД/LB/пула и покажите, почему рост реплик перестаёт помогать. Дайте исходные данные, графики и одно подтверждённое улучшение. + +**Трек 2. Отказ узла.** Расширьте стенд до нескольких узлов, покажите перенос API при потере узла и разберите оставшиеся SPOF (LB, DB, storage). Для заявленной защищённой зависимости покажите реальный failover и сохранность данных. Если DB не реплицирована, не заявляйте выживание её узла. + +## Как начать и проверить + +```sh +# Работает прямо в skeleton, Python 3.9+; приложение не запускается: +make check + +# После реализации запустите свой сервер/стенд по REPORT.md. +# По умолчанию тест использует http://localhost:8080. +make test +``` + +`.env.example`, `compose.example.yaml` и `contracts/infrastructure.json` описывают настройки и роли компонентов. **compose.example.yaml — список ролей с пустым services, не запускаемый стенд.** Реализуйте свой `compose.yaml`/`stack.yaml`, закрепите версии образов, заполните локальный `.env` и опишите bootstrap/миграции. Все зависимости поднимаются из этого репозитория; ссылка «у меня БД уже установлена» не заменяет воспроизводимость. + +```sh +# Compose-вариант после реализации: +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build +# Дождитесь /health/ready; затем make test. +# Для Swarm укажите эквивалентные build/push/deploy-команды в REPORT.md. +``` + + +Примеры запросов доступны в `examples/requests.http`, примеры JSON — в `contracts/examples.json`. Для полной проверки схемы (по желанию локально; CI делает её автоматически): + +```sh +python3 -m venv .venv +.venv/bin/python -m pip install -r requirements-dev.txt +make validate PYTHON=.venv/bin/python +``` + +Smoke не выставляет оценку автоматически. Проверку сохранности/отказов запускайте явно по [tests/README.md](tests/README.md), остальные доказательства приведите в отчёте. + +## Сценарий защиты + +1. Запустить стенд и показать ≥2 разных X-Instance-Id через LB с одной сессией. +2. Запустить make test-failover ACTION_SCRIPT=scripts/stop-one.sh. Скрипт теста выполняет запросы во время action, учитывает ошибки и повторяет сообщения с исходным ключом. +3. Показать, какой контейнер действительно остановлен; заголовок сам по себе не доказательство разных процессов. Повторить для второй реплики после восстановления первой. +4. Проверить restart всего стенда с сохранением volumes и неизменным токеном. Для 4/5 — соответствующие эксперименты. + +## Что должно быть в PR + +compose.yaml или stack.yaml, конфигурация LB, scripts/restart.sh, scripts/stop-one.sh, Dockerfile, миграции, результаты отказов. + +Заполните `REPORT.md` и [шаблон PR](.github/pull_request_template.md), укажите целевую оценку/трек. Не меняйте обязательный контракт и публичные tests ради зелёного результата. Сохраняйте возможности предыдущих лабораторных в пределах [объявленных переходов](COURSE.md). + +## Вопросы на защите + +- Чем отказ процесса отличается от отказа узла? +- Почему depends_on/healthcheck сами по себе не являются балансировщиком? +- Какие POST можно повторять после timeout и что защищает Idempotency-Key? +- Что сломается при увеличении числа API, если сессии находятся в локальной памяти? + +## Первичные материалы + +- [Compose services](https://docs.docker.com/reference/compose-file/services/) +- [Swarm routing mesh](https://docs.docker.com/engine/swarm/ingress/) +- [Swarm services](https://docs.docker.com/engine/swarm/services/) diff --git a/REPORT.md b/REPORT.md new file mode 100644 index 00000000..de046a3a --- /dev/null +++ b/REPORT.md @@ -0,0 +1,137 @@ +# Отчёт — лабораторная 3 + +- Автор, группа: TODO +- Целевая оценка: 4 +- Commit/PR: TODO после публикации +- Помощь ИИ: проектирование Compose/Nginx, общей идемпотентности и тестов; решения проверяются командами ниже. + +## Запуск из чистого clone + +Требуются Docker Engine с Compose v2, `make` и Python 3.9+. Единственная +последовательность запуска: + +```sh +cp .env.example .env +# заменить DATABASE_PASSWORD в .env локальным случайным значением +docker compose --env-file .env build api +docker compose --env-file .env up -d postgres redis +docker compose --env-file .env run --rm migrate +docker compose --env-file .env up -d --scale api=2 api nginx +curl --fail http://localhost:8080/health/ready +``` + +Миграции выполняются отдельным one-shot процессом до реплик. В каждой API +реплике `FLYWAY_ENABLED=false`. Повторная миграция согласуется таблицей истории +Flyway и её блокировкой. Для обновления сначала выполняется обратно совместимая +миграция, затем реплики заменяются по одной. + +Безопасная остановка сохраняет данные: + +```sh +docker compose --env-file .env stop +``` + +Намеренное удаление учебных данных (только после явного решения оператора): + +```sh +docker compose --env-file .env down --volumes +``` + +## Архитектура и корректность + +Путь запроса: клиент → `nginx:80` → `api:8080` × 2 → PostgreSQL. Redis — общий +необязательный cache пользователей; cache miss/отказ приводит к чтению из +PostgreSQL. Сессии, пользователи, чаты, сообщения и идемпотентность хранятся в +PostgreSQL и не зависят от памяти/диска конкретной API-реплики. + +Nginx 1.27.4 использует Docker DNS resolver `127.0.0.11`, TTL 2 s, +`least_conn`, `max_fails=1`, `fail_timeout=2s` и до двух upstream-попыток. Sticky +session отсутствует. API-порты на host не публикуются. Readiness каждые 2 s +проверяет Spring `ACCEPTING_TRAFFIC`, PostgreSQL и наличие V3-таблицы. При +SIGTERM Spring graceful shutdown имеет 10 s, Compose — 12 s, Nginx connect +timeout — 500 ms, read/send timeout — 4 s. Максимум обнаружения зависшего +backend — 4 s; с двумя последовательными timeout-попытками запрос завершается +примерно за 8.5 s. Docker health имеет period 2 s и timeout 2 s. + +Прозрачный `non_idempotent` retry разрешён только для endpoint сообщений: +обязательный `Idempotency-Key` и общая PostgreSQL-транзакция делают повтор +безопасным. Другие POST автоматически после начала отправки не повторяются. + +`X-Instance-Id` создаётся один раз на жизнь процесса из hostname контейнера. +Это позволяет доказать прохождение запросов через разные процессы и точно +сопоставить выбранный ID контейнеру в `scripts/stop-one.sh`. + +## Общая идемпотентность + +Область ключа: `(user_id, POST, canonical chat path, Idempotency-Key)`. Перед +проверкой/созданием сервис берёт transaction-scoped PostgreSQL advisory lock от +этой области. Затем в одной транзакции он проверяет SHA-256 семантического body, +создаёт `messages` и `message_idempotency`. Поэтому конкурентные запросы через +разные реплики сериализуются, а побочный эффект и результат коммитятся атомарно. +Тот же body возвращает исходные 201/Message; другой body даёт 409. Записи моложе +24 часов не удаляются. Возможная 64-битная коллизия advisory-lock только лишний +раз сериализует разные ключи: полная область всё равно проверяется primary key. + +## Воспроизводимые проверки + +| Критерий | Команда | Ожидаемый результат | +| --- | --- | --- | +| Контракт | `make test` | `PASS` | +| Один ключ через разные реплики | `make test-idempotency` | 32 ответа, ≥2 instance ID, 1 message | +| Отказ выбранной реплики | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | чтение/запись восстанавливаются ≤10 s | +| Обе реплики по очереди | `make test-failover-each ACTION_SCRIPT=... RESTORE_SCRIPT=...` | RPS/errors/recovery для каждой реплики | +| Поочерёдная замена | `make test-rolling ACTION_SCRIPT=scripts/rolling-update.sh` | запись продолжается при замене обеих реплик | +| Сохранность и сессия | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | прежний token и данные доступны | +| Конфигурация | `docker compose --env-file .env config --quiet` | exit 0 | + +Перед action-тестами: + +```sh +chmod +x scripts/stop-one.sh scripts/restart.sh +``` + +Для локального запуска из Windows предоставлены эквивалентные +`scripts/stop-one.cmd` и `scripts/restart.cmd`. + +После каждого failover восстановить две реплики и повторить со второй: + +```sh +docker compose --env-file .env up -d --scale api=2 api +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +``` + +Фактический эксперимент 2026-11-03 сохранён в +`evidence/failover-each-2026-11-03.json`, +`evidence/rolling-update-2026-11-03.json` и сводке +`evidence/level4-2026-11-03.md`. Последовательные отказы двух реплик дали +10.839/10.014 успешных операций в секунду, 0 ошибок и восстановление +1.306/2.672 s. Параллельная проверка одного idempotency key: 32 запроса через +две реплики создали одно сообщение. + +Rolling replacement под четырьмя потоками записи занял 115.800 s. Наблюдались +четыре instance ID, 12,147 успешных записей и 177 ошибок: 67.439 successful RPS, +error ratio 1.4362%, p50/p95/p99 успешных запросов 37.729/189.374/215.986 ms. +Ошибки не скрывались клиентским retry. Это closed-loop опыт на одном host; +percentiles не включают ошибки и подвержены coordinated omission. + +### Ресурсы, storage и обновление + +Каждая API-реплика ограничена 0.75 CPU и 768 MiB, Nginx — 0.25 CPU и 128 MiB. +Только Nginx публикует host port. Постоянные volumes принадлежат только +PostgreSQL и Redis; API/Nginx остаются stateless. `container_name` отсутствует. + +`scripts/rolling-update.*` удаляет и заменяет по одной исходной API-реплике, +ожидая health новой перед следующей. V3 является additive-миграцией: создаёт +новую таблицу/индекс, не меняя lab2-таблицы. Старая версия продолжает работать, +пока новая схема уже применена. Новая версия требует V3 для readiness. +Автоматический downgrade схемы не поддерживается; rollback приложения оставляет +неиспользуемую V3-таблицу. + +## Ограничения + +Стенд переживает отказ одного API-процесса, но PostgreSQL, Nginx и Docker host +остаются SPOF. Redis не является источником корректности. Nginx OSS использует +пассивную, а не активную upstream-проверку; Docker health/readiness предотвращает +первичный старт до готовности, а runtime-отказ обнаруживается первой ошибкой и +DNS/passive таймерами. Секрет в `.env` допустим только для локальной учебной +машины; для production нужен secret manager/Compose secrets. diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..5910077b --- /dev/null +++ b/build.gradle @@ -0,0 +1,55 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '4.1.1' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(23) + } +} + +repositories { + mavenCentral() +} + +dependencies { +// implementation 'org.springframework.boot:spring-boot-starter-data-jpa' +// implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-webmvc' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-data-redis' + implementation 'org.springframework.boot:spring-boot-flyway' + implementation 'org.flywaydb:flyway-core' + implementation 'org.flywaydb:flyway-database-postgresql' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.bouncycastle:bcprov-jdk18on:1.84' + implementation 'org.apache.commons:commons-pool2' + runtimeOnly 'org.postgresql:postgresql' + + implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.3' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + annotationProcessor 'org.projectlombok:lombok' +// testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test' +// testImplementation 'org.springframework.boot:spring-boot-starter-security-test' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test' + testCompileOnly 'org.projectlombok:lombok' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testAnnotationProcessor 'org.projectlombok:lombok' + + implementation("com.github.f4b6a3:uuid-creator:6.1.1") + +} + +tasks.named('test') { + useJUnitPlatform() +} + diff --git a/compose.example.yaml b/compose.example.yaml new file mode 100644 index 00000000..dd4d3878 --- /dev/null +++ b/compose.example.yaml @@ -0,0 +1,11 @@ +# Topology worksheet, deliberately NOT a runnable stack (no application supplied). +# Implement compose.yaml or stack.yaml; do not submit this empty file as deployment. +# Service names below are logical roles, not imposed container names. +x-lab-number: 3 +x-required-roles: + - api + - postgres + - load_balancer +# TODO: implement real images/builds, network wiring, volumes, healthchecks, +# credentials and bootstrap. Details: contracts/infrastructure.json and README.md. +services: {} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..de14a7f5 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,122 @@ +name: hla-lab3 + +x-api-environment: &api-environment + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + DATABASE_URL: jdbc:postgresql://postgres:5432/${DATABASE_NAME:-messenger} + DATABASE_USER: ${DATABASE_USER:-messenger} + DATABASE_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env} + DATABASE_POOL_SIZE: ${DATABASE_POOL_SIZE:-10} + DATABASE_MIN_IDLE: ${DATABASE_MIN_IDLE:-2} + DATABASE_QUERY_TIMEOUT_SECONDS: ${DATABASE_QUERY_TIMEOUT_SECONDS:-5} + DATABASE_TRANSACTION_TIMEOUT_SECONDS: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:-5} + REDIS_HOST: redis + REDIS_PORT: 6379 + REDIS_CONNECT_TIMEOUT: ${REDIS_CONNECT_TIMEOUT:-1s} + REDIS_COMMAND_TIMEOUT: ${REDIS_COMMAND_TIMEOUT:-500ms} + REDIS_POOL_MAX_ACTIVE: ${REDIS_POOL_MAX_ACTIVE:-8} + REDIS_POOL_MAX_IDLE: ${REDIS_POOL_MAX_IDLE:-8} + REDIS_POOL_MIN_IDLE: ${REDIS_POOL_MIN_IDLE:-0} + REDIS_POOL_MAX_WAIT: ${REDIS_POOL_MAX_WAIT:-500ms} + USER_CACHE_TTL_SECONDS: ${USER_CACHE_TTL_SECONDS:-300} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + +services: + postgres: + image: postgres:16.4-bookworm + environment: + POSTGRES_DB: ${DATABASE_NAME:-messenger} + POSTGRES_USER: ${DATABASE_USER:-messenger} + POSTGRES_PASSWORD: ${DATABASE_PASSWORD:?Set DATABASE_PASSWORD in .env} + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] + interval: 2s + timeout: 2s + retries: 30 + restart: unless-stopped + networks: [backend] + + redis: + image: redis:7.4-bookworm + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"] + volumes: + - redis-data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 2s + timeout: 2s + retries: 30 + restart: unless-stopped + networks: [backend] + + # One-shot Flyway runner. It is invoked explicitly before API replicas. + migrate: + image: hla-lab3-api:local + environment: + <<: *api-environment + FLYWAY_ENABLED: "true" + MIGRATE_ONLY: "true" + SPRING_MAIN_WEB_APPLICATION_TYPE: none + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + restart: "no" + networks: [backend] + + api: + image: hla-lab3-api:local + build: + context: . + environment: + <<: *api-environment + FLYWAY_ENABLED: "false" + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + healthcheck: + test: ["CMD", "curl", "--fail", "--silent", "http://localhost:8080/health/ready"] + interval: 2s + timeout: 2s + retries: 15 + start_period: 45s + init: true + stop_grace_period: 12s + restart: unless-stopped + cpus: 0.75 + mem_limit: 768m + networks: [backend] + + nginx: + image: nginx:1.27.4-bookworm + ports: + - "127.0.0.1:${APP_PORT:-8080}:80" + volumes: + - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro + depends_on: + api: + condition: service_healthy + healthcheck: + test: ["CMD", "nginx", "-t"] + interval: 2s + timeout: 2s + retries: 15 + stop_grace_period: 10s + restart: unless-stopped + cpus: 0.25 + mem_limit: 128m + networks: [backend] + +networks: + backend: + driver: bridge + +volumes: + postgres-data: + redis-data: diff --git a/contracts/README.md b/contracts/README.md new file mode 100644 index 00000000..8c58b32f --- /dev/null +++ b/contracts/README.md @@ -0,0 +1,61 @@ +# Семантика API + +Этот текст дополняет [openapi.json](openapi.json). Обязательный API соответствует уровню 3 текущей лабораторной. Факультативный crop или rate limiting не становятся обязательными только из-за наличия допустимого имени варианта или кода ошибки в схеме. + +## Формат и ошибки + +- JSON — UTF-8, `Content-Type: application/json`. UUID — строка; время — RFC 3339 UTC с `Z`, назначается сервером. Часы не считаются уникальным ID. +- Каждый ответ API, включая ошибки и health, содержит непустой `X-Request-Id`. Тело ошибки: `{"error":{"code":"invalid_request","message":"...","request_id":"..."}}`; `request_id` совпадает с заголовком. Сообщение ошибки не раскрывает stack trace, SQL, credentials или наличие чужого объекта. +- Обязательные строки не состоят только из пробельных символов. `username` строго `[a-z0-9_]{3,32}`, уникален; `display_name` — 1–100 Unicode code points. JSON с лишними полями или неверными типами — `400`; malformed JSON также `400`. +- `400 invalid_request` — неверные поля, UUID, cursor, limit; `401 unauthorized` — нет действительной идентификации/сессии; `404 not_found` — объекта нет или он чужой; `409 conflict` — username занят, повторный ключ с другим сообщением, объект ещё не готов; `413 payload_too_large`; `415 unsupported_media_type`; `429 rate_limited`; `503 unavailable`. Неожиданное исключение — `500 internal_error` без внутренних деталей. +- Сначала аутентификация, затем доступ к конкретному ресурсу. Любой аутентифицированный участник чата может читать его историю и вложения и писать в него; посторонний получает `404`. Списки содержат только доступные объекты. Не используйте `403` для раскрытия существования чужого чата. +- `GET /health/live` проверяет только жизнь процесса, возвращает `200 {"status":"ok"}`. `GET /health/ready` возвращает 200, если приложение может безопасно обслуживать обязательный синхронный путь; иначе 503 в общем формате ошибки. Какие зависимости критичны, зафиксируйте в отчёте; недоступность Grafana не должна останавливать API. + +## Пользователи, чаты и сообщения + +- `POST /users` публичен; возвращает `201 User`. Пароль/его hash и сессионные данные никогда не входят в User. +- `POST /chats` принимает title и явный список существующих `member_ids`, включая вызывающего. Дубликаты, неизвестные участники и отсутствие вызывающего — 400. Чат создаётся атомарно. GET списка чатов сортируется по `(created_at, id)` по возрастанию. +- Отправитель сообщения выводится из текущей идентификации, поле `sender_id` в запросе не принимается. Текст — до 4000 Unicode code points. Нельзя отправить пустой/пробельный текст без вложений. +- История использует keyset cursor: `(created_at, id)`, по возрастанию; `limit` — целое 1–100, по умолчанию 50. Ответ `{"items":[...],"next_cursor":null}`. Непустой cursor — непрозрачная для клиента строка; последний элемент предыдущей страницы не повторяется. Cursor привязан к ресурсу/запросу: от другого чата — 400. Изменять `limit` при продолжении можно. +- `next_cursor` равен null, если на момент чтения следующей записи нет. Гарантируется отсутствие повторов при обходе неизменной истории; snapshot изоляция между несколькими HTTP-запросами не требуется. При конкурентных вставках опишите выбранную семантику и ограничения часов. +- Подтверждённое сообщение видно следующему чтению через любую API-реплику. Допускается кэш, но он не должен возвращать устаревшую историю после успешной записи. Удаление и изменение участников в обязательный API не входят. + +## Идентификация и сессии + +**Lab1:** защищённые endpoint требуют `X-User-Id: `; отсутствие/неизвестный ID — 401. Это учебный выбор пользователя: любой клиент может выдать себя за другого. + +**Lab2–7:** `POST /auth/sessions` принимает только `Authorization: Basic `, без JSON body. Username ограничен ASCII; пароль кодируется UTF-8, 12–128 code points, двоеточие в пароле допустимо. Неверные credentials — одинаковый 401 и `WWW-Authenticate: Basic realm="messenger", charset="UTF-8"`. + +Вход возвращает `201 {"token":"...","token_type":"Bearer","expires_at":"...Z","user":{...}}`. Токен — непрозрачное случайное значение, не username/UUID и не обязательный JWT; энтропия не менее 256 бит. Храните серверную сессию с expiry; TTL задаётся `SESSION_TTL_SECONDS`, по умолчанию 3600 (в тесте истечения можно 2). В обычном smoke TTL должен быть не менее 300. + +Все защищённые endpoint принимают только `Authorization: Bearer `. Истёкший/отозванный/неизвестный токен — 401 с `WWW-Authenticate: Bearer realm="messenger"`. Basic на бизнес-endpoint — 401. `X-User-Id` с lab2 игнорируется: он не меняет владельца сессии и сам по себе не даёт доступ. `DELETE /auth/sessions/current` отзывает текущий токен и возвращает 204 без тела; повтор с отозванным токеном — 401. + +Пользователи, чаты, сообщения и ещё действительные сессии переживают перезапуск приложения и используемых хранилищ с сохранёнными volumes. TTL не продлевается из-за рестарта. Пароли уже с lab2 хешируются библиотечным password KDF (Argon2id, scrypt или bcrypt с учётом ограничений библиотеки), не SHA-256 и не plaintext. Если bcrypt не поддерживает весь диапазон UTF-8 паролей без усечения, выберите другую библиотечную схему. В lab7 обязателен Argon2id. + +Basic — это кодирование, не шифрование. HTTP lab1–6 допускается только для локального изолированного стенда с синтетическими данными; для удалённой демонстрации нужен TLS. Lab7 использует HTTPS обязательно. См. [RFC 7617](https://www.rfc-editor.org/info/rfc7617/). + +## Балансировка и повторная отправка (с lab3) + +- Каждый ответ, созданный API, содержит `X-Instance-Id`; значение стабильно для жизни процесса. Ошибки соединения, созданные самим LB, могут не иметь этого заголовка. В lab7 используйте случайный alias реплики без раскрытия hostname/IP. +- Для POST сообщения обязателен `Idempotency-Key` (ASCII `[A-Za-z0-9._:-]{1,128}`). Нет/неверный ключ — 400. Область уникальности: текущий пользователь + HTTP-метод + путь чата + ключ. +- При повторе того же валидного JSON в течение 24 часов сервер возвращает тот же код 201 и то же Message. Порядок ключей JSON и отсутствующий `attachment_ids` вместо `[]` семантически равны. Другой body при том же ключе — 409. Разные пользователи/чаты могут использовать одинаковый ключ независимо. +- Одновременные повторы через разные реплики создают ровно одно сообщение. Повтор снова проверяет действительность сессии и доступ. Транзиентные 5xx не фиксируются как окончательный результат; побочный эффект и запись результата должны быть атомарны. +- Ключ обязателен только для сообщений. Самостоятельный retry загрузки файла или создания чата может создать ещё один объект; не добавляйте прозрачные повторы этих POST без расширения контракта. + +## Вложения (с lab4) + +- `POST /chats/{chat_id}/attachments?filename=photo.png`: сырые bytes одного PNG/JPEG; `Content-Type: image/png` или `image/jpeg`. Не multipart. Максимум **10 MiB = 10 485 760 байт**. MIME проверяется по содержимому; заведомо повреждённые/чужие форматы — 415, превышение bytes — 413. Не более 40 миллионов декодированных пикселей (превышение — 413). Устанавливайте лимит до полной распаковки изображения. +- `filename` — отображаемое имя (1–255 code points). Не используйте его как путь/ключ S3. Имя с `/`, `\`, NUL или управляющими символами — 400. Bucket приватен; object key генерирует сервер. Оригинал возвращается побайтно, его lowercase SHA-256 и размер соответствуют исходному файлу. +- Lab4 возвращает `201 Attachment` со `status=ready`, `variants=[]`, `error_code=null` только после сохранения оригинала и метаданных. Lab5–7 возвращают `202 Attachment` со снимком `status=queued`; готовность определяется последующим GET метаданных. Быстрый worker может закончить до первого GET — это нормально. +- Файл заранее привязан к чату. В POST сообщения добавляется `attachment_ids` (0–10 уникальных ID, по умолчанию []). Можно отправить `text=""` с хотя бы одним вложением. Все вложения должны принадлежать этому чату; чужое/неизвестное — 404. Любой участник может ссылаться на доступное вложение чата. Failed-вложение прикреплять нельзя (409); queued/processing с lab5 можно. +- `GET /attachments/{id}` и `/content` доступны только участникам чата. Download возвращает байты с истинным Content-Type, через авторизованный API, **без redirect** в обязательном контракте. Приватный bucket сам по себе не заменяет эту проверку. `variant` по умолчанию original. Для queued/processing content — 409; для failed — 409. Отсутствующий вариант ready-объекта — 404. +- В ready-метаданных `error_code=null`. В failed — краткий машинный код (например `invalid_image`, `processing_failed`, `retry_exhausted`), без stack trace. `size_bytes`, `sha256`, `content_type` всегда описывают оригинал; у вариантов отдельные поля. Публичный API не раскрывает ключи бакета, внутренние адреса и credentials. +- Прямой upload/download по временной подписи — факультативное расширение. Его дополняют ограничение срока/размера, уникальный ключ и подтверждение реально загруженного объекта; он не заменяет стандартный endpoint. Особенности подписанных URL: [S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html). + +## Фоновая обработка (с lab5) + +До 202 все байты приняты в **устойчивый staging**, а намерение обработать файл надёжно сохранено. HTTP-передача клиента не исчезает и не становится мгновенной. Staging — приватный S3-prefix либо общий persistent volume, доступный worker; локальная память/API ephemeral disk не подходит. Worker асинхронно переносит/публикует оригинал в конечный S3-prefix и создаёт варианты; если staging уже в S3, опишите эту границу честно. + +Обязательный thumbnail: JPEG, изображение вписано в 256×256 с сохранением пропорций, без увеличения маленьких исходников, EXIF orientation применяется; alpha компонуется на белый. Размеры округляются вниз, минимум 1 px. Fixture 320×200 должен дать 256×160. Статус ready ставится после сохранения оригинала и thumbnail. Crop на 4: JPEG, центрированный квадрат 128×128 (для маленьких исходников допускается увеличение). Optimized на 4: WebP, вписан в 1280×1280 без увеличения, параметры качества и удаления EXIF документируются; не обещайте уменьшение каждого маленького файла. + +Допустимые состояния и события описаны в `jobs.schema.json` и `attachment-states.md`. Доставка — at least once; обработка идемпотентна, повторы не размножают варианты. Финальные ошибки наблюдаемы, бесконечный немой retry недопустим. Обязательный smoke ждёт ready до 60 секунд; это бюджет локального smoke для одного файла при свободном worker, не универсальный production SLA. В очередь идут ссылки/ID, не бинарное содержимое. diff --git a/contracts/examples.json b/contracts/examples.json new file mode 100644 index 00000000..eaa4fcdf --- /dev/null +++ b/contracts/examples.json @@ -0,0 +1,58 @@ +{ + "CreateUser": { + "username": "alice", + "display_name": "Алиса", + "password": "Example-only-not-a-real-secret-123" + }, + "User": { + "id": "11111111-1111-4111-8111-111111111111", + "username": "alice", + "display_name": "Алиса", + "created_at": "2026-09-01T12:00:00Z" + }, + "CreateChat": { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ] + }, + "Chat": { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ], + "id": "33333333-3333-4333-8333-333333333333", + "created_at": "2026-09-01T12:00:00Z" + }, + "CreateMessage": { + "text": "Привет, Боб!" + }, + "Message": { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z" + }, + "MessagePage": { + "items": [ + { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z" + } + ], + "next_cursor": null + }, + "Error": { + "error": { + "code": "not_found", + "message": "Объект не найден", + "request_id": "example-request-id" + } + } +} diff --git a/contracts/infrastructure.json b/contracts/infrastructure.json new file mode 100644 index 00000000..28439b8f --- /dev/null +++ b/contracts/infrastructure.json @@ -0,0 +1,36 @@ +{ + "lab": 3, + "kind": "requirements, not runnable deployment", + "required_for_grade_3": [ + { + "role": "api", + "count_min": 2, + "student_implements": true, + "persistent_local_state": false + }, + { + "role": "postgres", + "purpose": "users/chats/membership/messages/metadata", + "persistent_volume": true + }, + { + "role": "load_balancer", + "public_entrypoint": true, + "backend_readiness": true + } + ], + "optional_components": [ + { + "role": "redis_or_valkey", + "required_for_lab2_grade4": true, + "note": "Choose one; if only store of sessions, configure durable persistence." + } + ], + "rules": [ + "Choose Compose or Swarm for lab3+; do not need both.", + "Never publish internal API replica ports in bypass of LB from lab3.", + "Versions/digests must be fixed in implementation.", + "Do not remove volumes in restart/failover checks.", + "Document service names, healthchecks, bootstrap/migrations and credentials." + ] +} diff --git a/contracts/openapi.json b/contracts/openapi.json new file mode 100644 index 00000000..da4d1cc7 --- /dev/null +++ b/contracts/openapi.json @@ -0,0 +1,2528 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "MTUSI Messenger — лабораторная 3", + "version": "1.3.0", + "description": "Нормативный минимум на 3. Семантика: contracts/README.md. Расширения на 4/5 не должны менять этот API. Наличие кода ошибки в схеме не требует реализовать факультативную причину его выдачи." + }, + "servers": [ + { + "url": "http://localhost:8080", + "description": "Локальный учебный стенд" + } + ], + "security": [ + { + "bearerAuth": [] + } + ], + "paths": { + "/health/live": { + "get": { + "operationId": "liveness", + "summary": "Процесс жив", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [] + } + }, + "/health/ready": { + "get": { + "operationId": "readiness", + "summary": "Готов принимать трафик", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [] + } + }, + "/api/v1/users": { + "post": { + "operationId": "registerUser", + "summary": "Создать пользователя", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateUser" + } + } + } + } + } + }, + "/api/v1/users/me": { + "get": { + "operationId": "currentUser", + "summary": "Текущий пользователь", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/v1/chats": { + "post": { + "operationId": "createChat", + "summary": "Создать чат; вызывающий должен входить в member_ids", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Chat" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateChat" + } + } + } + } + }, + "get": { + "operationId": "listChats", + "summary": "Чаты текущего пользователя", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatPage" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 50 + } + }, + { + "name": "cursor", + "in": "query", + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + } + }, + "/api/v1/chats/{chat_id}": { + "get": { + "operationId": "getChat", + "summary": "Получить доступный чат", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Chat" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "chat_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ] + } + }, + "/api/v1/chats/{chat_id}/messages": { + "post": { + "operationId": "createMessage", + "summary": "Отправить сообщение", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "chat_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "Idempotency-Key", + "in": "header", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z0-9._:-]+$" + }, + "description": "Обязателен с lab3. Область: пользователь + метод + путь + ключ; хранить результат не менее 24 ч. Повтор того же JSON возвращает исходный 201 и то же сообщение, другой JSON — 409." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateMessage" + } + } + } + } + }, + "get": { + "operationId": "listMessages", + "summary": "Сообщения по (created_at, id) по возрастанию", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessagePage" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "chat_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 50 + } + }, + { + "name": "cursor", + "in": "query", + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + } + }, + "/api/v1/auth/sessions": { + "post": { + "operationId": "createSession", + "summary": "Вход: Basic username:password; выдаёт сессию", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Session" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [ + { + "basicAuth": [] + } + ] + } + }, + "/api/v1/auth/sessions/current": { + "delete": { + "operationId": "revokeSession", + "summary": "Отозвать текущую сессию", + "responses": { + "204": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + } + }, + "components": { + "securitySchemes": { + "basicAuth": { + "type": "http", + "scheme": "basic" + }, + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "opaque session token" + } + }, + "schemas": { + "Error": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "invalid_request", + "unauthorized", + "not_found", + "conflict", + "payload_too_large", + "unsupported_media_type", + "rate_limited", + "unavailable", + "internal_error" + ] + }, + "message": { + "type": "string", + "minLength": 1 + }, + "request_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "code", + "message", + "request_id" + ], + "additionalProperties": false + } + }, + "required": [ + "error" + ], + "additionalProperties": false, + "examples": [ + { + "error": { + "code": "not_found", + "message": "Объект не найден", + "request_id": "example-request-id" + } + } + ] + }, + "Health": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "ok" + ] + } + }, + "required": [ + "status" + ], + "additionalProperties": false + }, + "User": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "username": { + "type": "string", + "pattern": "^[a-z0-9_]{3,32}$" + }, + "display_name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "created_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "username", + "display_name", + "created_at" + ], + "additionalProperties": false, + "examples": [ + { + "id": "11111111-1111-4111-8111-111111111111", + "username": "alice", + "display_name": "Алиса", + "created_at": "2026-09-01T12:00:00Z" + } + ] + }, + "CreateUser": { + "type": "object", + "properties": { + "username": { + "type": "string", + "pattern": "^[a-z0-9_]{3,32}$" + }, + "display_name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "password": { + "type": "string", + "minLength": 12, + "maxLength": 128, + "writeOnly": true + } + }, + "required": [ + "username", + "display_name", + "password" + ], + "additionalProperties": false, + "examples": [ + { + "username": "alice", + "display_name": "Алиса", + "password": "Example-only-not-a-real-secret-123" + } + ] + }, + "Chat": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "member_ids": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "minItems": 1, + "maxItems": 100, + "uniqueItems": true + }, + "created_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "title", + "member_ids", + "created_at" + ], + "additionalProperties": false, + "examples": [ + { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ], + "id": "33333333-3333-4333-8333-333333333333", + "created_at": "2026-09-01T12:00:00Z" + } + ] + }, + "CreateChat": { + "type": "object", + "properties": { + "title": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "member_ids": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "minItems": 1, + "maxItems": 100, + "uniqueItems": true + } + }, + "required": [ + "title", + "member_ids" + ], + "additionalProperties": false, + "examples": [ + { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ] + } + ] + }, + "Message": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "chat_id": { + "type": "string", + "format": "uuid" + }, + "sender_id": { + "type": "string", + "format": "uuid" + }, + "text": { + "type": "string", + "minLength": 1, + "maxLength": 4000 + }, + "created_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "chat_id", + "sender_id", + "text", + "created_at" + ], + "additionalProperties": false, + "examples": [ + { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z" + } + ] + }, + "CreateMessage": { + "type": "object", + "properties": { + "text": { + "type": "string", + "minLength": 1, + "maxLength": 4000 + } + }, + "required": [ + "text" + ], + "additionalProperties": false, + "examples": [ + { + "text": "Привет, Боб!" + } + ] + }, + "ChatPage": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Chat" + } + }, + "next_cursor": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "items", + "next_cursor" + ], + "additionalProperties": false + }, + "MessagePage": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Message" + } + }, + "next_cursor": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "items", + "next_cursor" + ], + "additionalProperties": false, + "examples": [ + { + "items": [ + { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z" + } + ], + "next_cursor": null + } + ] + }, + "Session": { + "type": "object", + "properties": { + "token": { + "type": "string", + "minLength": 32 + }, + "token_type": { + "type": "string", + "const": "Bearer" + }, + "expires_at": { + "type": "string", + "format": "date-time" + }, + "user": { + "$ref": "#/components/schemas/User" + } + }, + "required": [ + "token", + "token_type", + "expires_at", + "user" + ], + "additionalProperties": false + } + } + } +} diff --git a/evidence/README.md b/evidence/README.md new file mode 100644 index 00000000..8df70015 --- /dev/null +++ b/evidence/README.md @@ -0,0 +1,5 @@ +# Доказательства + +Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки. + +Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно. diff --git a/evidence/failover-each-2026-11-03.json b/evidence/failover-each-2026-11-03.json new file mode 100644 index 00000000..b248ffcc --- /dev/null +++ b/evidence/failover-each-2026-11-03.json @@ -0,0 +1,24 @@ +{ + "scenario": "sequential failover of each API replica", + "replicas": 2, + "results": [ + { + "target_instance_id": "170796a1dad0", + "window_seconds": 15.038, + "successful_reads": 81, + "successful_writes": 82, + "failed_attempts": 0, + "successful_rps": 10.839, + "first_recovery_seconds": 1.306 + }, + { + "target_instance_id": "feb12e05fd43", + "window_seconds": 15.079, + "successful_reads": 75, + "successful_writes": 76, + "failed_attempts": 0, + "successful_rps": 10.014, + "first_recovery_seconds": 2.672 + } + ] +} diff --git a/evidence/level4-2026-11-03.md b/evidence/level4-2026-11-03.md new file mode 100644 index 00000000..e13bf373 --- /dev/null +++ b/evidence/level4-2026-11-03.md @@ -0,0 +1,49 @@ +# Lab3 level 4 evidence — 2026-11-03 + +Environment: Windows host, Docker Desktop Engine 28.0.1, Compose deployment on +one machine, two API replicas limited to 0.75 CPU / 768 MiB each. All requests +used Nginx at `http://localhost:8080`; API ports were not published. + +## Sequential failover + +Command: + +```text +python tests/failover_each.py --action-script scripts/stop-one.cmd \ + --restore-script scripts/restore-api.cmd --window 15 \ + --output evidence/failover-each-2026-11-03.json +``` + +| Target instance | Successful reads | Successful writes | Errors | Successful RPS | First recovery | +| --- | ---: | ---: | ---: | ---: | ---: | +| `170796a1dad0` | 81 | 82 | 0 | 10.839 | 1.306 s | +| `feb12e05fd43` | 75 | 76 | 0 | 10.014 | 2.672 s | + +The stopped replica was restored and observed again before the next target was +stopped. Confirmed messages remained readable after both failures. + +## Shared idempotency + +`python tests/idempotency_concurrent.py` passed: 32 concurrent requests with +one key used two API instance IDs and created exactly one message. + +## Sequential replacement under load + +Command: + +```text +python tests/rolling_update.py --action-script scripts/rolling-update.cmd \ + --duration 180 --concurrency 4 \ + --output evidence/rolling-update-2026-11-03.json +``` + +- Rolling action: 115.800 s. +- Four instance IDs observed: two original and two replacements. +- Successful writes: 12,147; failed attempts: 177. +- Successful RPS: 67.439; error ratio: 1.4362%. +- Successful latency: p50 37.729 ms, p95 189.374 ms, p99 215.986 ms. + +This is a closed-loop single-host experiment. It includes coordinated omission +and client overhead; latency percentiles cover successes only. Brief failures +are retained in the result rather than hidden by client retries. PostgreSQL, +Nginx and the Docker host remain single points of failure. diff --git a/evidence/rolling-update-2026-11-03.json b/evidence/rolling-update-2026-11-03.json new file mode 100644 index 00000000..d9bf1b30 --- /dev/null +++ b/evidence/rolling-update-2026-11-03.json @@ -0,0 +1,23 @@ +{ + "scenario": "sequential API replacement under closed-loop writes", + "requested_duration_seconds": 180.0, + "elapsed_seconds": 180.118, + "rolling_action_seconds": 115.8, + "concurrency": 4, + "observed_instance_ids": [ + "5782a3226f58", + "d3604e18baea", + "e54e39339867", + "e55cbed4e283" + ], + "successful_requests": 12147, + "failed_requests": 177, + "error_ratio": 0.014362, + "successful_rps": 67.439, + "successful_latency_ms": { + "p50": 37.729, + "p95": 189.374, + "p99": 215.986 + }, + "note": "Closed-loop result on one host; success latency excludes failures." +} diff --git a/examples/requests.http b/examples/requests.http new file mode 100644 index 00000000..492f9383 --- /dev/null +++ b/examples/requests.http @@ -0,0 +1,46 @@ +# Optional HTTP-client worksheet; no extension is required by the course. +# Replace IDs/token locally from real responses; do not commit filled-in credentials. +# Canonical API: contracts/openapi.json and contracts/README.md. +@baseUrl = http://localhost:8080 +@aliceId = REPLACE_WITH_CREATED_ALICE_UUID +@bobId = REPLACE_WITH_CREATED_BOB_UUID +@chatId = REPLACE_WITH_CREATED_CHAT_UUID +@sessionToken = REPLACE_LOCALLY_DO_NOT_COMMIT + +### Liveness +GET {{baseUrl}}/health/live + +### Register Alice (repeat with username bob/display_name Боб) +POST {{baseUrl}}/api/v1/users +Content-Type: application/json + +{ + "username": "alice", + "display_name": "Алиса", + "password": "Example-only-not-a-real-secret-123" +} + +### Create session: generate the Base64 value locally, do not commit credentials +# Base64 of UTF-8 username:password; only this endpoint accepts Basic. +POST {{baseUrl}}/api/v1/auth/sessions +Authorization: Basic REPLACE_WITH_LOCAL_BASE64_CREDENTIAL + + +### Create chat; both UUIDs must be real registered users +POST {{baseUrl}}/api/v1/chats +Authorization: Bearer {{sessionToken}} +Content-Type: application/json + +{"title":"Проект по ВНП","member_ids":["{{aliceId}}","{{bobId}}"]} + +### Send message +POST {{baseUrl}}/api/v1/chats/{{chatId}}/messages +Authorization: Bearer {{sessionToken}} +Idempotency-Key: example-message-001 +Content-Type: application/json + +{"text":"Привет, Боб!"} + +### Read first page +GET {{baseUrl}}/api/v1/chats/{{chatId}}/messages?limit=50 +Authorization: Bearer {{sessionToken}} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..eddabd2e Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..ad7845be --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..249efbb0 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..a51ec4f5 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/infra/README.md b/infra/README.md new file mode 100644 index 00000000..6c9e9ae6 --- /dev/null +++ b/infra/README.md @@ -0,0 +1,41 @@ +# Инфраструктура студента + +Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом 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-реплику. + +## Топология lab3 + +`nginx:80` — единственная опубликованная точка входа. Он динамически разрешает +Compose DNS-имя `api`, балансирует без affinity и пассивно исключает peer на 2 +секунды после ошибки. `api` не публикует порт на host; две реплики получают +общие PostgreSQL и Redis только через сеть `backend`. + +API readiness вызывается Docker каждые 2 секунды и проверяет Spring readiness, +соединение с PostgreSQL и наличие таблицы миграции V3. При SIGTERM Docker даёт +5 секунд action-script или 12 секунд обычной остановки; Spring прекращает +приём новых запросов и завершает уже принятые в пределах 10 секунд. Nginx имеет +connect timeout 500 ms, read/send timeout 4 s, две upstream-попытки и обновляет +Docker DNS с TTL 2 s. Максимальное обнаружение зависшего backend — 4 s; +максимум двух последовательных timeout-попыток — около 8.5 s. + +Flyway разрешён только в one-shot service `migrate`. У API задано +`FLYWAY_ENABLED=false`, поэтому запуск нескольких реплик не создаёт гонку +инициализации схемы. + +Restart hook поднимает зависимости по фазам и не запускает Nginx, пока обе +API-реплики не стали healthy. Это не позволяет Docker DNS объявить +прогревающуюся реплику через уже доступную публичную точку входа. + +API ограничен 0.75 CPU и 768 MiB на контейнер, Nginx — 0.25 CPU и 128 MiB. +Порт публикует только Nginx. PostgreSQL и Redis имеют собственные volumes; +API и Nginx постоянных volumes не имеют. `container_name` не используется, +поэтому один Compose-service `api` масштабируется параметром `--scale`. + +V3 — additive-миграция: она создаёт новую таблицу и индекс, не изменяя таблицы +lab2. Поэтому старая версия может продолжать работать во время поочерёдной +замены, но новая версия не станет ready до применения V3. Автоматический +downgrade схемы не реализован; rollback приложения оставляет неиспользуемую +таблицу V3. diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 00000000..04ed5162 --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,70 @@ +worker_processes auto; +worker_shutdown_timeout 10s; + +events { + worker_connections 1024; +} + +http { + access_log /var/log/nginx/access.log; + error_log /var/log/nginx/error.log warn; + + # Docker embedded DNS returns current Compose replicas. Nginx OSS 1.27.3+ + # refreshes these addresses without a configuration reload. + resolver 127.0.0.11 valid=2s ipv6=off; + resolver_timeout 1s; + + upstream api_backend { + zone api_backend 64k; + least_conn; + server api:8080 resolve max_fails=1 fail_timeout=2s; + keepalive 32; + } + + server { + listen 80; + server_name _; + + location = /nginx-health { + access_log off; + default_type application/json; + return 200 '{"status":"ok"}'; + } + + # Message POST is the only non-idempotent HTTP method that is safe to + # replay here: the API requires Idempotency-Key and commits the message + # together with its shared PostgreSQL idempotency record. + location ~ ^/api/v1/chats/[0-9a-fA-F-]+/messages$ { + proxy_pass http://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_request_buffering on; + + proxy_connect_timeout 500ms; + proxy_send_timeout 4s; + proxy_read_timeout 4s; + proxy_next_upstream error timeout http_502 http_503 http_504 non_idempotent; + proxy_next_upstream_tries 2; + } + + location / { + proxy_pass http://api_backend; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_connect_timeout 500ms; + proxy_send_timeout 4s; + proxy_read_timeout 4s; + + # No sticky sessions. Failed/unready peers are retried elsewhere. + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_next_upstream_tries 2; + } + } +} diff --git a/lab.json b/lab.json new file mode 100644 index 00000000..57bb9fbb --- /dev/null +++ b/lab.json @@ -0,0 +1,8 @@ +{ + "number": 3, + "title": "Балансировка и отказ API-реплики", + "contract_version": "1.3.0", + "default_base_url": "http://localhost:8080", + "grading": "3; 4 includes 3; 5 includes 4 plus one completed research track", + "scaffold_has_application": false +} diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 00000000..6b103ddb --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,2 @@ +# Only for full OpenAPI/JSON Schema validation; HTTP tests use stdlib. +openapi-spec-validator==0.7.2 diff --git a/scripts/check_contract.py b/scripts/check_contract.py new file mode 100644 index 00000000..dcb34dfa --- /dev/null +++ b/scripts/check_contract.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Offline structural checks; full schema validation is a separate target.""" +import ast +import json +from pathlib import Path +import re + +ROOT = Path(__file__).resolve().parents[1] + +def main(): + lab = json.loads((ROOT/'lab.json').read_text())['number'] + spec = json.loads((ROOT/'contracts/openapi.json').read_text()) + assert spec['openapi']=='3.1.0' + assert spec['info']['version']=='1.%d.0'%lab + operation_ids = set() + def walk(value): + if isinstance(value,dict): + if '$ref' in value: + pointer = value['$ref'] + assert pointer.startswith('#/'), 'unexpected external reference' + target = spec + for part in pointer[2:].split('/'): + target = target[part.replace('~1','/').replace('~0','~')] + for v in value.values(): + walk(v) + elif isinstance(value,list): + for v in value: + walk(v) + walk(spec) + for route,methods in spec['paths'].items(): + placeholders = set(re.findall(r'\{([^}]+)\}',route)) + for method,op in methods.items(): + assert op['operationId'] not in operation_ids, 'duplicate operationId' + operation_ids.add(op['operationId']) + params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')} + assert placeholders==params, 'path parameter mismatch: '+route + for response in op['responses'].values(): + assert 'X-Request-Id' in response['headers'] + if lab>=3: + assert 'X-Instance-Id' in response['headers'] + assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2) + assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4) + for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')): + ast.parse(file.read_text(),filename=str(file)) + for file in ROOT.rglob('*.json'): + if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts): + continue + json.loads(file.read_text()) + for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'): + assert (ROOT/required).is_file(), 'missing '+required + print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.') + +if __name__=='__main__': + main() diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..8e4e21b5 --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,8 @@ +@echo off +setlocal EnableExtensions +cd /d "%~dp0\.." + +docker compose --env-file .env stop nginx api redis postgres || exit /b 1 +docker compose --env-file .env up -d --wait --wait-timeout 90 postgres redis || exit /b 1 +docker compose --env-file .env up -d --wait --wait-timeout 90 --no-deps --scale api=2 api || exit /b 1 +docker compose --env-file .env up -d --no-deps nginx || exit /b 1 diff --git a/scripts/restart.example.sh b/scripts/restart.example.sh new file mode 100644 index 00000000..967e9512 --- /dev/null +++ b/scripts/restart.example.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +# TODO: copy to restart.sh and implement using YOUR compose/stack services. +# Restart API and ALL used state stores (DB, sessions, S3, broker as applicable). +# Preserve persistent volumes and schema/data; never down -v / flush / re-seed. +# Allow operator unseal if required in lab7; do not print credentials. +# Exit 0 only after the intended action; test waits for API readiness separately. +printf '%s +' 'TODO: implement restart.sh for your infrastructure' >&2 +exit 2 diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..9d3a8cd0 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,13 @@ +#!/bin/sh +set -eu + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +PROJECT_DIR=$(dirname -- "$SCRIPT_DIR") +cd "$PROJECT_DIR" + +# Preserve named volumes and the network. The migration job is intentionally +# not re-run during a same-version restart. +docker compose --env-file .env stop nginx api redis postgres +docker compose --env-file .env up -d --wait --wait-timeout 90 postgres redis +docker compose --env-file .env up -d --wait --wait-timeout 90 --no-deps --scale api=2 api +docker compose --env-file .env up -d --no-deps nginx diff --git a/scripts/restore-api.cmd b/scripts/restore-api.cmd new file mode 100644 index 00000000..2fc83566 --- /dev/null +++ b/scripts/restore-api.cmd @@ -0,0 +1,6 @@ +@echo off +setlocal EnableExtensions +cd /d "%~dp0\.." + +docker compose --env-file .env up -d --wait --wait-timeout 90 --no-deps --scale api=2 api +exit /b %ERRORLEVEL% diff --git a/scripts/restore-api.sh b/scripts/restore-api.sh new file mode 100644 index 00000000..6f90f154 --- /dev/null +++ b/scripts/restore-api.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +PROJECT_DIR=$(dirname -- "$SCRIPT_DIR") +cd "$PROJECT_DIR" + +docker compose --env-file .env up -d --wait --wait-timeout 90 \ + --no-deps --scale api=2 api diff --git a/scripts/rolling-update.cmd b/scripts/rolling-update.cmd new file mode 100644 index 00000000..a881740c --- /dev/null +++ b/scripts/rolling-update.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal EnableExtensions +cd /d "%~dp0\.." + +set /a REPLICA_COUNT=0 +for /f "usebackq delims=" %%C in (`docker compose --env-file .env ps -q api`) do set /a REPLICA_COUNT+=1 +if %REPLICA_COUNT% LSS 2 exit /b 2 + +for /f "usebackq delims=" %%C in (`docker compose --env-file .env ps -q api`) do call :replace_one %%C +exit /b 0 + +:replace_one +docker stop --time 10 %1 >nul || exit /b 1 +docker rm %1 >nul || exit /b 1 +docker compose --env-file .env up -d --wait --wait-timeout 90 --no-deps --scale api=2 api >nul || exit /b 1 +exit /b 0 diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh new file mode 100644 index 00000000..17a6c19c --- /dev/null +++ b/scripts/rolling-update.sh @@ -0,0 +1,22 @@ +#!/bin/sh +set -eu + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +PROJECT_DIR=$(dirname -- "$SCRIPT_DIR") +cd "$PROJECT_DIR" + +original_ids=$(docker compose --env-file .env ps -q api) +count=$(printf '%s\n' "$original_ids" | sed '/^$/d' | wc -l | tr -d ' ') +if [ "$count" -lt 2 ]; then + printf '%s\n' 'Rolling update requires at least two API replicas' >&2 + exit 2 +fi + +for container_id in $original_ids; do + # Replace exactly one original replica and wait for the replacement before + # touching the next one. Named volumes and state stores are not changed. + docker stop --time 10 "$container_id" >/dev/null + docker rm "$container_id" >/dev/null + docker compose --env-file .env up -d --wait --wait-timeout 90 \ + --no-deps --scale api=2 api >/dev/null +done diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 00000000..4c96d747 --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,25 @@ +@echo off +setlocal EnableExtensions EnableDelayedExpansion + +if "%TARGET_INSTANCE_ID%"=="" exit /b 2 +cd /d "%~dp0\.." + +set "TARGET_CONTAINER=" +set /a MATCHES=0 +for /f "usebackq delims=" %%C in (`docker compose --env-file .env ps -q api`) do ( + set "CONTAINER_ID=%%C" + set "SHORT_ID=!CONTAINER_ID:~0,12!" + set "HOSTNAME_VALUE=" + for /f "usebackq delims=" %%H in (`docker inspect --format "{{.Config.Hostname}}" %%C`) do set "HOSTNAME_VALUE=%%H" + if "!HOSTNAME_VALUE!"=="%TARGET_INSTANCE_ID%" ( + set "TARGET_CONTAINER=%%C" + set /a MATCHES+=1 + ) else if "!SHORT_ID!"=="%TARGET_INSTANCE_ID%" ( + set "TARGET_CONTAINER=%%C" + set /a MATCHES+=1 + ) +) + +if not "!MATCHES!"=="1" exit /b 2 +docker stop --time 5 "!TARGET_CONTAINER!" >nul +exit /b %ERRORLEVEL% diff --git a/scripts/stop-one.example.sh b/scripts/stop-one.example.sh new file mode 100644 index 00000000..ae149e89 --- /dev/null +++ b/scripts/stop-one.example.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +# TODO: copy to stop-one.sh, map TARGET_INSTANCE_ID to ONE API container/task. +# Stop that instance and leave it stopped; no stop of DB/LB/volumes. +# Return quickly (within 10 s); the test sends requests during this script. +# Restore the replica explicitly after the test. Never print credentials. +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +printf '%s +' 'TODO: implement stop-one.sh for your infrastructure' >&2 +exit 2 diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..3c6cc82c --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,28 @@ +#!/bin/sh +set -eu + +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +PROJECT_DIR=$(dirname -- "$SCRIPT_DIR") +cd "$PROJECT_DIR" + +target="" +matches=0 +for container_id in $(docker compose --env-file .env ps -q api); do + hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container_id") + short_id=$(printf '%s' "$container_id" | cut -c1-12) + if [ "$TARGET_INSTANCE_ID" = "$hostname" ] || [ "$TARGET_INSTANCE_ID" = "$short_id" ]; then + target=$container_id + matches=$((matches + 1)) + fi +done + +if [ "$matches" -ne 1 ]; then + printf '%s\n' "Expected one API replica for X-Instance-Id, found $matches" >&2 + exit 2 +fi + +# Five seconds keeps the operator hook below the test's ten-second budget while +# still delivering SIGTERM and allowing Spring's graceful shutdown phase. +docker stop --time 5 "$target" >/dev/null diff --git a/scripts/validate_openapi.py b/scripts/validate_openapi.py new file mode 100644 index 00000000..1dfe4a98 --- /dev/null +++ b/scripts/validate_openapi.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""Full OpenAPI and JSON Schema checks; install requirements-dev.txt first.""" +import json +from pathlib import Path +from openapi_spec_validator import validate +from jsonschema import Draft202012Validator + +root = Path(__file__).resolve().parents[1] +spec = json.loads((root/'contracts/openapi.json').read_text()) +validate(spec) +from referencing import Registry, Resource +# The base URI resolves local #/components references inside examples. +resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'}) +registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource)) +for name, example in json.loads((root/'contracts/examples.json').read_text()).items(): + schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name} + Draft202012Validator(schema, registry=registry).validate(example) +for path in (root/'contracts').glob('*.schema.json'): + schema = json.loads(path.read_text()) + Draft202012Validator.check_schema(schema) + for example in schema.get('examples',[]): + Draft202012Validator(schema).validate(example) +print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.') diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..d8f971ad --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'mtusi-messenger' diff --git a/src/main/java/com/example/mtusi_messenger/MtusiMessengerApplication.java b/src/main/java/com/example/mtusi_messenger/MtusiMessengerApplication.java new file mode 100644 index 00000000..32e25b92 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/MtusiMessengerApplication.java @@ -0,0 +1,18 @@ +package com.example.mtusi_messenger; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; + +@SpringBootApplication +public class MtusiMessengerApplication { + + public static void main(String[] args) { + ConfigurableApplicationContext context = SpringApplication.run( + MtusiMessengerApplication.class, args); + if (Boolean.parseBoolean(System.getenv("MIGRATE_ONLY"))) { + System.exit(SpringApplication.exit(context)); + } + } + +} diff --git a/src/main/java/com/example/mtusi_messenger/cache/UserCache.java b/src/main/java/com/example/mtusi_messenger/cache/UserCache.java new file mode 100644 index 00000000..04ad8036 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/cache/UserCache.java @@ -0,0 +1,83 @@ +package com.example.mtusi_messenger.cache; + +import com.example.mtusi_messenger.model.User; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.util.Optional; +import java.util.UUID; + +@Component +public class UserCache { + private static final Logger log = LoggerFactory.getLogger(UserCache.class); + private static final String KEY_PREFIX = "messenger:user:"; + + private final StringRedisTemplate redis; + private final ObjectMapper mapper; + private final Duration ttl; + + public UserCache( + StringRedisTemplate redis, + ObjectMapper mapper, + @Value("${messenger.cache.user-ttl-seconds:300}") long ttlSeconds + ) { + if (ttlSeconds <= 0) { + throw new IllegalArgumentException("User cache TTL must be positive"); + } + this.redis = redis; + this.mapper = mapper; + this.ttl = Duration.ofSeconds(ttlSeconds); + } + + public Optional find(UUID userId) { + try { + String value = redis.opsForValue().get(key(userId)); + if (value == null) { + return Optional.empty(); + } + User cachedUser = mapper.readValue(value, User.class); + if (cachedUser == null) { + log.warn("Ignoring null Redis user cache entry for {}", userId); + evict(userId); + return Optional.empty(); + } + return Optional.of(cachedUser); + } catch (DataAccessException e) { + log.warn("Redis user cache is unavailable; using PostgreSQL fallback"); + return Optional.empty(); + } catch (JsonProcessingException e) { + log.warn("Ignoring malformed Redis user cache entry for {}", userId); + evict(userId); + return Optional.empty(); + } + } + + public void put(User user) { + try { + redis.opsForValue().set(key(user.id()), mapper.writeValueAsString(user), ttl); + } catch (DataAccessException e) { + log.warn("Redis user cache is unavailable; user was not cached"); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Cannot serialize user cache entry", e); + } + } + + public void evict(UUID userId) { + try { + redis.delete(key(userId)); + } catch (DataAccessException e) { + log.warn("Redis user cache is unavailable; cache eviction was skipped"); + } + } + + private String key(UUID userId) { + return KEY_PREFIX + userId; + } +} diff --git a/src/main/java/com/example/mtusi_messenger/config/JacksonConfig.java b/src/main/java/com/example/mtusi_messenger/config/JacksonConfig.java new file mode 100644 index 00000000..568a65e2 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/JacksonConfig.java @@ -0,0 +1,28 @@ +package com.example.mtusi_messenger.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer; + +import tools.jackson.databind.cfg.CoercionAction; +import tools.jackson.databind.cfg.CoercionInputShape; +import tools.jackson.databind.type.LogicalType; + +@Configuration +public class JacksonConfig { + + @Bean + JsonMapperBuilderCustomizer strictStringTypes() { + return builder -> builder.withCoercionConfig( + LogicalType.Textual, + config -> { + config.setCoercion( + CoercionInputShape.Integer, CoercionAction.Fail); + config.setCoercion( + CoercionInputShape.Float, CoercionAction.Fail); + config.setCoercion( + CoercionInputShape.Boolean, CoercionAction.Fail); + } + ); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/config/OpenApiConfig.java b/src/main/java/com/example/mtusi_messenger/config/OpenApiConfig.java new file mode 100644 index 00000000..14cc24f6 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/OpenApiConfig.java @@ -0,0 +1,21 @@ +package com.example.mtusi_messenger.config; + + +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import org.springframework.context.annotation.Configuration; + +@SecurityScheme( + name = "basicAuth", + type = SecuritySchemeType.HTTP, + scheme = "basic" +) +@SecurityScheme( + name = "bearerAuth", + type = SecuritySchemeType.HTTP, + scheme = "bearer", + bearerFormat = "opaque session token" +) +@Configuration +public class OpenApiConfig { +} diff --git a/src/main/java/com/example/mtusi_messenger/config/PasswordConfig.java b/src/main/java/com/example/mtusi_messenger/config/PasswordConfig.java new file mode 100644 index 00000000..98436f17 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/PasswordConfig.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.argon2.Argon2PasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class PasswordConfig { + @Bean + PasswordEncoder passwordEncoder() { + return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java b/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java new file mode 100644 index 00000000..e38246af --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/SecurityConfig.java @@ -0,0 +1,92 @@ +package com.example.mtusi_messenger.config; + +import com.example.mtusi_messenger.security.ApiAuthenticationFilter; +import com.example.mtusi_messenger.security.DatabaseAuthenticationProvider; +import com.example.mtusi_messenger.security.RestAuthenticationEntryPoint; +import com.example.mtusi_messenger.service.AuthenticationService; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.AnonymousAuthenticationFilter; + +@Configuration +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) +public class SecurityConfig { + @Bean + AuthenticationManager authenticationManager(DatabaseAuthenticationProvider provider) { + return new ProviderManager(provider); + } + + @Bean + RestAuthenticationEntryPoint basicAuthenticationEntryPoint(ObjectMapper mapper) { + return new RestAuthenticationEntryPoint( + mapper, + "Basic realm=\"messenger\", charset=\"UTF-8\""); + } + + @Bean + RestAuthenticationEntryPoint bearerAuthenticationEntryPoint(ObjectMapper mapper) { + return new RestAuthenticationEntryPoint(mapper, "Bearer realm=\"messenger\""); + } + + @Bean + ApiAuthenticationFilter apiAuthenticationFilter( + AuthenticationManager authenticationManager, + AuthenticationService authenticationService, + @Qualifier("basicAuthenticationEntryPoint") RestAuthenticationEntryPoint basicAuthenticationEntryPoint, + @Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint + ) { + return new ApiAuthenticationFilter( + authenticationManager, + authenticationService, + basicAuthenticationEntryPoint, + bearerAuthenticationEntryPoint); + } + + @Bean + FilterRegistrationBean disableServletFilterRegistration( + ApiAuthenticationFilter filter + ) { + var registration = new FilterRegistrationBean<>(filter); + registration.setEnabled(false); + return registration; + } + + @Bean + SecurityFilterChain securityFilterChain( + HttpSecurity http, + ApiAuthenticationFilter apiAuthenticationFilter, + @Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint + ) throws Exception { + http + .csrf(csrf -> csrf.disable()) + .formLogin(form -> form.disable()) + .httpBasic(basic -> basic.disable()) + .logout(logout -> logout.disable()) + .requestCache(cache -> cache.disable()) + .sessionManagement(session -> session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .exceptionHandling(errors -> errors + .authenticationEntryPoint(bearerAuthenticationEntryPoint)) + .authorizeHttpRequests(authorize -> authorize + .requestMatchers(HttpMethod.GET, "/health/**").permitAll() + .requestMatchers( + "/swagger-ui.html", + "/swagger-ui/**", + "/v3/api-docs/**" + ).permitAll() + .requestMatchers(HttpMethod.POST, "/api/v1/users").permitAll() + .anyRequest().authenticated()) + .addFilterBefore(apiAuthenticationFilter, AnonymousAuthenticationFilter.class); + return http.build(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/config/WebConfig.java b/src/main/java/com/example/mtusi_messenger/config/WebConfig.java new file mode 100644 index 00000000..ac26bb39 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/config/WebConfig.java @@ -0,0 +1,19 @@ +package com.example.mtusi_messenger.config; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class WebConfig { + @Bean + ObjectMapper objectMapper() { + return JsonMapper.builder().findAndAddModules() + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true) + .build(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/ChatController.java b/src/main/java/com/example/mtusi_messenger/controller/ChatController.java new file mode 100644 index 00000000..ff02c9bf --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/ChatController.java @@ -0,0 +1,83 @@ +package com.example.mtusi_messenger.controller; + +import com.example.mtusi_messenger.exception.ApiExceptions; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; +import com.example.mtusi_messenger.dto.*; +import com.example.mtusi_messenger.model.Chat; +import com.example.mtusi_messenger.service.ChatService; +import com.example.mtusi_messenger.security.SessionPrincipal; +import java.util.List; +import java.util.UUID; + +import static com.example.mtusi_messenger.service.UuidValidator.parse; + +@RestController +@RequestMapping("/api/v1/chats") +@SecurityRequirement(name = "bearerAuth") +@RequiredArgsConstructor +public class ChatController { + + private final ChatService chats; + + @PostMapping + public ResponseEntity create(@AuthenticationPrincipal SessionPrincipal principal, + @Valid @RequestBody CreateChatRequest body + ) { + UUID userId = principal.user().id(); + Chat c = chats.create(body, userId); + return ResponseEntity.status(HttpStatus.CREATED).body(ChatResponse.from(c)); + } + + @GetMapping + public ChatPageResponse list(@AuthenticationPrincipal SessionPrincipal principal, + @RequestParam(required = false) String limit, + @RequestParam(required = false) String cursor + ) { + UUID userId = principal.user().id(); + int parsedLimit = validateLimit(limit); + validateCursorPresence(cursor); + List page = chats.page(userId, parsedLimit, cursor); + boolean hasNext = page.size() > parsedLimit; + if (hasNext) page = page.subList(0, parsedLimit); + return new ChatPageResponse(page.stream().map(ChatResponse::from).toList(), page.isEmpty() ? null : + chats.nextCursor(userId, page.get(page.size() - 1), hasNext)); + } + + @GetMapping("/{chatId}") + public ChatResponse get(@AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String chatId + ) { + UUID userId = principal.user().id(); + return ChatResponse.from(chats.getAccessible(parse(chatId), userId)); + } + + private static int validateLimit(String limit) { + if (limit == null) { + return 50; + } + if (!limit.matches("[0-9]+")) { + throw ApiExceptions.invalid("Invalid limit"); + } + try { + int value = Integer.parseInt(limit); + + if (value < 1 || value > 100) { + throw ApiExceptions.invalid("Invalid limit"); + } + + return value; + } catch (NumberFormatException ex) { + throw ApiExceptions.invalid("Invalid limit"); + } + } + + private static void validateCursorPresence(String c) { + if (c != null && c.isBlank()) throw ApiExceptions.invalid("Invalid cursor"); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/HealthController.java b/src/main/java/com/example/mtusi_messenger/controller/HealthController.java new file mode 100644 index 00000000..2b9abc35 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/HealthController.java @@ -0,0 +1,58 @@ +package com.example.mtusi_messenger.controller; + +import org.springframework.http.ResponseEntity; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.boot.availability.ApplicationAvailability; +import org.springframework.boot.availability.ReadinessState; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import com.example.mtusi_messenger.dto.HealthResponse; +import com.example.mtusi_messenger.exception.ApiExceptions; + +@RestController +public class HealthController { + private final JdbcTemplate jdbc; + private final StringRedisTemplate redis; + private final ApplicationAvailability availability; + + public HealthController( + JdbcTemplate jdbc, + StringRedisTemplate redis, + ApplicationAvailability availability + ) { + this.jdbc = jdbc; + this.redis = redis; + this.availability = availability; + } + + @GetMapping("/health/live") + public ResponseEntity live() { + return ResponseEntity.ok(new HealthResponse("ok")); + } + + @GetMapping("/health/ready") + public ResponseEntity ready() { + if (availability.getReadinessState() != ReadinessState.ACCEPTING_TRAFFIC) { + throw ApiExceptions.unavailable("Application is not accepting traffic"); + } + try { + // Warm the lazy Lettuce connection on every replica. Redis remains + // an optional cache: failure is ignored and business reads fall + // back to PostgreSQL. + redis.execute((RedisCallback) connection -> connection.ping()); + } catch (DataAccessException ignored) { + // Optional cache unavailable; PostgreSQL remains authoritative. + } + try { + // A schema-level probe prevents a replica from becoming ready + // before the separately executed migration job has completed. + jdbc.queryForObject("SELECT count(*) FROM message_idempotency", Long.class); + return ResponseEntity.ok(new HealthResponse("ok")); + } catch (DataAccessException e) { + throw ApiExceptions.unavailable("Database is unavailable"); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/MessageController.java b/src/main/java/com/example/mtusi_messenger/controller/MessageController.java new file mode 100644 index 00000000..e26c4cb2 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/MessageController.java @@ -0,0 +1,79 @@ +package com.example.mtusi_messenger.controller; + +import com.example.mtusi_messenger.exception.ApiExceptions; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; +import com.example.mtusi_messenger.dto.*; +import com.example.mtusi_messenger.model.Message; +import com.example.mtusi_messenger.service.MessageService; +import com.example.mtusi_messenger.security.SessionPrincipal; +import java.util.List; +import java.util.UUID; + +import static com.example.mtusi_messenger.service.UuidValidator.parse; + +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/v1/chats/{chatId}/messages") +@SecurityRequirement(name = "bearerAuth") +public class MessageController { + private static final String IDEMPOTENCY_KEY_PATTERN = "[A-Za-z0-9._:-]{1,128}"; + private final MessageService messages; + + @PostMapping + public ResponseEntity create(@AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String chatId, + @RequestHeader(name = "Idempotency-Key", required = false) String idempotencyKey, + @Valid @RequestBody CreateMessageRequest body + ) { + if (idempotencyKey == null || !idempotencyKey.matches(IDEMPOTENCY_KEY_PATTERN)) { + throw ApiExceptions.invalid("Invalid or missing Idempotency-Key"); + } + UUID userId = principal.user().id(); + UUID parsedChatId = parse(chatId); + Message m = messages.create(parsedChatId, userId, body, idempotencyKey); + return ResponseEntity.status(HttpStatus.CREATED).body(MessageResponse.from(m)); + } + + @GetMapping + public MessagePageResponse list(@AuthenticationPrincipal SessionPrincipal principal, + @PathVariable String chatId, + @RequestParam(required = false) String limit, + @RequestParam(required=false) String cursor + ) { + UUID userId = principal.user().id(); + UUID parsedChatId = parse(chatId); + int parsedLimit = validateLimit(limit); + if (cursor != null && cursor.isBlank()) throw ApiExceptions.invalid("Invalid cursor"); + List page = messages.page(parsedChatId, userId, parsedLimit, cursor); + boolean hasNext = page.size() > parsedLimit; if (hasNext) page = page.subList(0, parsedLimit); + return new MessagePageResponse(page.stream().map(MessageResponse::from).toList(), + page.isEmpty() ? null : messages.nextCursor(parsedChatId, page.get(page.size()-1), hasNext)); + } + + private static int validateLimit(String limit) { + if (limit == null) { + return 50; + } + if (!limit.matches("[0-9]+")) { + throw ApiExceptions.invalid("Invalid limit"); + } + try { + int value = Integer.parseInt(limit); + + if (value < 1 || value > 100) { + throw ApiExceptions.invalid("Invalid limit"); + } + + return value; + } catch (NumberFormatException ex) { + throw ApiExceptions.invalid("Invalid limit"); + } + } + +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/SessionController.java b/src/main/java/com/example/mtusi_messenger/controller/SessionController.java new file mode 100644 index 00000000..f79528f3 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/SessionController.java @@ -0,0 +1,41 @@ +package com.example.mtusi_messenger.controller; + +import com.example.mtusi_messenger.dto.SessionResponse; +import com.example.mtusi_messenger.dto.UserResponse; +import com.example.mtusi_messenger.service.AuthenticationService; +import com.example.mtusi_messenger.model.User; +import com.example.mtusi_messenger.security.SessionPrincipal; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/v1/auth/sessions") +@RequiredArgsConstructor +public class SessionController { + private final AuthenticationService authentication; + + @PostMapping + @SecurityRequirement(name = "basicAuth") + public ResponseEntity create(@AuthenticationPrincipal User user) { + var issued = authentication.issueSession(user); + return ResponseEntity.status(HttpStatus.CREATED).body(new SessionResponse( + issued.token(), + "Bearer", + issued.expiresAt(), + UserResponse.from(issued.user()))); + } + + @DeleteMapping("/current") + @SecurityRequirement(name = "bearerAuth") + public ResponseEntity revoke(@AuthenticationPrincipal SessionPrincipal principal) { + authentication.revoke(principal); + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/controller/UserController.java b/src/main/java/com/example/mtusi_messenger/controller/UserController.java new file mode 100644 index 00000000..0d2d9cf6 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/controller/UserController.java @@ -0,0 +1,32 @@ +package com.example.mtusi_messenger.controller; + +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; +import com.example.mtusi_messenger.dto.*; +import com.example.mtusi_messenger.service.UserService; +import com.example.mtusi_messenger.security.SessionPrincipal; + +@RestController +@RequestMapping("/api/v1/users") +@RequiredArgsConstructor +public class UserController { + + private final UserService users; + + @PostMapping + public ResponseEntity create(@Valid @RequestBody CreateUserRequest request) { + var user = users.create(request); + return ResponseEntity.status(HttpStatus.CREATED).body(UserResponse.from(user)); + } + + @GetMapping("/me") + @SecurityRequirement(name = "bearerAuth") + public UserResponse me(@AuthenticationPrincipal SessionPrincipal principal) { + return UserResponse.from(principal.user()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/ChatPageResponse.java b/src/main/java/com/example/mtusi_messenger/dto/ChatPageResponse.java new file mode 100644 index 00000000..e1d54bf2 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/ChatPageResponse.java @@ -0,0 +1,8 @@ +package com.example.mtusi_messenger.dto; + +import java.util.List; + +public record ChatPageResponse( + List items, + String next_cursor +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/ChatResponse.java b/src/main/java/com/example/mtusi_messenger/dto/ChatResponse.java new file mode 100644 index 00000000..96b2abb4 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/ChatResponse.java @@ -0,0 +1,18 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.Chat; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record ChatResponse(UUID id, + String title, + List member_ids, + Instant created_at) { + public static ChatResponse from(Chat c) { + return new ChatResponse( + c.id(), + c.title(), + c.memberIds(), + c.createdAt()); } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/CreateChatRequest.java b/src/main/java/com/example/mtusi_messenger/dto/CreateChatRequest.java new file mode 100644 index 00000000..3f792346 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/CreateChatRequest.java @@ -0,0 +1,19 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.web.NotUnicodeBlank; +import com.example.mtusi_messenger.web.UnicodeSize; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.Size; +import java.util.List; +import java.util.UUID; + +public record CreateChatRequest( + @NotUnicodeBlank + @UnicodeSize(min = 1, max = 100) + String title, + + @NotEmpty + @Size(min = 1, max = 100) + List member_ids +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/CreateMessageRequest.java b/src/main/java/com/example/mtusi_messenger/dto/CreateMessageRequest.java new file mode 100644 index 00000000..6900ecab --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/CreateMessageRequest.java @@ -0,0 +1,8 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.web.NotUnicodeBlank; +import com.example.mtusi_messenger.web.UnicodeSize; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +public record CreateMessageRequest( @NotUnicodeBlank @UnicodeSize(min = 1, max = 4000) String text) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/CreateUserRequest.java b/src/main/java/com/example/mtusi_messenger/dto/CreateUserRequest.java new file mode 100644 index 00000000..6d6e5a91 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/CreateUserRequest.java @@ -0,0 +1,20 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.web.NotUnicodeBlank; +import com.example.mtusi_messenger.web.UnicodeSize; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; + +public record CreateUserRequest( + @NotBlank + @Pattern(regexp = "[a-z0-9_]{3,32}") + String username, + + @NotUnicodeBlank + @UnicodeSize(min = 1, max = 100) + String display_name, + + @NotUnicodeBlank + @UnicodeSize(min = 12, max = 128) + String password +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/ErrorResponse.java b/src/main/java/com/example/mtusi_messenger/dto/ErrorResponse.java new file mode 100644 index 00000000..4b1a2a92 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/ErrorResponse.java @@ -0,0 +1,8 @@ +package com.example.mtusi_messenger.dto; + +public record ErrorResponse(ErrorBody error) { + public record ErrorBody(String code, + String message, + String request_id) + {} +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/HealthResponse.java b/src/main/java/com/example/mtusi_messenger/dto/HealthResponse.java new file mode 100644 index 00000000..9630b107 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/HealthResponse.java @@ -0,0 +1,3 @@ +package com.example.mtusi_messenger.dto; + +public record HealthResponse(String status) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/MessagePageResponse.java b/src/main/java/com/example/mtusi_messenger/dto/MessagePageResponse.java new file mode 100644 index 00000000..db72eee8 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/MessagePageResponse.java @@ -0,0 +1,8 @@ +package com.example.mtusi_messenger.dto; + +import java.util.List; + +public record MessagePageResponse( + List items, + String next_cursor +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/MessageResponse.java b/src/main/java/com/example/mtusi_messenger/dto/MessageResponse.java new file mode 100644 index 00000000..d780c354 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/MessageResponse.java @@ -0,0 +1,19 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.Message; +import java.time.Instant; +import java.util.UUID; + +public record MessageResponse(UUID id, + UUID chat_id, + UUID sender_id, + String text, + Instant created_at) { + public static MessageResponse from(Message m) { + return new MessageResponse(m.id(), + m.chatId(), + m.senderId(), + m.text(), + m.createdAt()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/dto/SessionResponse.java b/src/main/java/com/example/mtusi_messenger/dto/SessionResponse.java new file mode 100644 index 00000000..64b54f99 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/SessionResponse.java @@ -0,0 +1,10 @@ +package com.example.mtusi_messenger.dto; + +import java.time.Instant; + +public record SessionResponse( + String token, + String token_type, + Instant expires_at, + UserResponse user +) {} diff --git a/src/main/java/com/example/mtusi_messenger/dto/UserResponse.java b/src/main/java/com/example/mtusi_messenger/dto/UserResponse.java new file mode 100644 index 00000000..e84bcb71 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/dto/UserResponse.java @@ -0,0 +1,18 @@ +package com.example.mtusi_messenger.dto; + +import com.example.mtusi_messenger.model.User; +import java.time.Instant; +import java.util.UUID; + +public record UserResponse(UUID id, + String username, + String display_name, + Instant created_at) { + public static UserResponse from(User u) { + return new UserResponse( + u.id(), + u.username(), + u.displayName(), + u.createdAt()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/exception/ApiException.java b/src/main/java/com/example/mtusi_messenger/exception/ApiException.java new file mode 100644 index 00000000..2c07f225 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/exception/ApiException.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.exception; + +import org.springframework.http.HttpStatus; + +public class ApiException extends RuntimeException { + private final String code; private final HttpStatus status; private final String authenticate; + public ApiException(String code, HttpStatus status, String message) { this(code, status, message, null); } + public ApiException(String code, HttpStatus status, String message, String authenticate) { + super(message); this.code = code; this.status = status; this.authenticate = authenticate; + } + public String code() { return code; } + public HttpStatus status() { return status; } + public String authenticate() { return authenticate; } +} diff --git a/src/main/java/com/example/mtusi_messenger/exception/ApiExceptions.java b/src/main/java/com/example/mtusi_messenger/exception/ApiExceptions.java new file mode 100644 index 00000000..cf671bf9 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/exception/ApiExceptions.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.exception; + +import org.springframework.http.HttpStatus; + +public final class ApiExceptions { + private ApiExceptions() {} + public static ApiException invalid(String m) { return new ApiException("invalid_request", HttpStatus.BAD_REQUEST, m); } + public static ApiException unauthorized(String m) { return unauthorizedBearer(m); } + public static ApiException unauthorizedBasic(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Basic realm=\"messenger\", charset=\"UTF-8\""); } + public static ApiException unauthorizedBearer(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Bearer realm=\"messenger\""); } + public static ApiException notFound(String m) { return new ApiException("not_found", HttpStatus.NOT_FOUND, m); } + public static ApiException conflict(String m) { return new ApiException("conflict", HttpStatus.CONFLICT, m); } + public static ApiException unavailable(String m) { return new ApiException("unavailable", HttpStatus.SERVICE_UNAVAILABLE, m); } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/Chat.java b/src/main/java/com/example/mtusi_messenger/model/Chat.java new file mode 100644 index 00000000..829d99e5 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/Chat.java @@ -0,0 +1,11 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +public record Chat(UUID id, String title, List memberIds, Instant createdAt) { + public Chat { + memberIds = List.copyOf(memberIds); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/IdempotentMessage.java b/src/main/java/com/example/mtusi_messenger/model/IdempotentMessage.java new file mode 100644 index 00000000..424d7a33 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/IdempotentMessage.java @@ -0,0 +1,3 @@ +package com.example.mtusi_messenger.model; + +public record IdempotentMessage(byte[] requestHash, Message message) {} diff --git a/src/main/java/com/example/mtusi_messenger/model/Message.java b/src/main/java/com/example/mtusi_messenger/model/Message.java new file mode 100644 index 00000000..a52586eb --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/Message.java @@ -0,0 +1,6 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.UUID; + +public record Message(UUID id, UUID chatId, UUID senderId, String text, Instant createdAt) {} diff --git a/src/main/java/com/example/mtusi_messenger/model/MessageKey.java b/src/main/java/com/example/mtusi_messenger/model/MessageKey.java new file mode 100644 index 00000000..545fd607 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/MessageKey.java @@ -0,0 +1,35 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.UUID; + +public record MessageKey(Instant createdAt, UUID id) + implements Comparable { + + private static int compareUuidV7(UUID a, UUID b) { + int result = Long.compareUnsigned( + a.getMostSignificantBits(), + b.getMostSignificantBits() + ); + + if (result != 0) { + return result; + } + + return Long.compareUnsigned( + a.getLeastSignificantBits(), + b.getLeastSignificantBits() + ); + } + + @Override + public int compareTo(MessageKey other) { + int result = createdAt.compareTo(other.createdAt); + + if (result != 0) { + return result; + } + + return compareUuidV7(id, other.id); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/model/Session.java b/src/main/java/com/example/mtusi_messenger/model/Session.java new file mode 100644 index 00000000..27aa2fbe --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/Session.java @@ -0,0 +1,15 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.UUID; + +public record Session(UUID id, UUID userId, byte[] tokenHash, Instant createdAt, Instant expiresAt) { + public Session { + tokenHash = tokenHash.clone(); + } + + @Override + public byte[] tokenHash() { + return tokenHash.clone(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/model/User.java b/src/main/java/com/example/mtusi_messenger/model/User.java new file mode 100644 index 00000000..1fefb17c --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/model/User.java @@ -0,0 +1,6 @@ +package com.example.mtusi_messenger.model; + +import java.time.Instant; +import java.util.UUID; + +public record User(UUID id, String username, String displayName, Instant createdAt) {} diff --git a/src/main/java/com/example/mtusi_messenger/repository/ChatRepository.java b/src/main/java/com/example/mtusi_messenger/repository/ChatRepository.java new file mode 100644 index 00000000..66085e44 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/ChatRepository.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Chat; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface ChatRepository { + Chat save(Chat chat); + Optional findById(UUID id); + boolean isMember(UUID chatId, UUID userId); + List findAllForUser(UUID userId); + List findPageForUser(UUID userId, UUID afterId, java.time.Instant afterCreatedAt, int limitPlusOne); +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/MessageRepository.java b/src/main/java/com/example/mtusi_messenger/repository/MessageRepository.java new file mode 100644 index 00000000..23ea4814 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/MessageRepository.java @@ -0,0 +1,18 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Message; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public interface MessageRepository { + Message save(Message message); + void lockIdempotencyScope(UUID userId, String method, String path, String key); + void deleteExpiredIdempotency(UUID userId, String method, String path, String key, Instant expiresBefore); + Optional findIdempotent( + UUID userId, String method, String path, String key); + void saveIdempotency(UUID userId, String method, String path, String key, + byte[] requestHash, UUID messageId, Instant createdAt); + List findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne); +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresChatRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresChatRepository.java new file mode 100644 index 00000000..17d825d7 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresChatRepository.java @@ -0,0 +1,106 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Chat; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Repository +public class PostgresChatRepository implements ChatRepository { + private final JdbcTemplate jdbc; + + public PostgresChatRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + @Transactional(timeout = 5) + public Chat save(Chat chat) { + jdbc.update(""" + INSERT INTO chats (id, title, created_at) + VALUES (?, ?, ?) + """, chat.id(), chat.title(), Timestamp.from(chat.createdAt())); + + for (UUID memberId : chat.memberIds()) { + jdbc.update(""" + INSERT INTO chat_members (chat_id, user_id) + VALUES (?, ?) + """, chat.id(), memberId); + } + return chat; + } + + @Override + public Optional findById(UUID id) { + return jdbc.query(""" + SELECT id, title, created_at + FROM chats + WHERE id = ? + """, (rs, rowNum) -> new ChatRow( + rs.getObject("id", UUID.class), + rs.getString("title"), + rs.getTimestamp("created_at").toInstant()), id) + .stream().findFirst() + .map(this::toChat); + } + + @Override + public boolean isMember(UUID chatId, UUID userId) { + return Boolean.TRUE.equals(jdbc.queryForObject(""" + SELECT EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = ? AND user_id = ? + ) + """, Boolean.class, chatId, userId)); + } + + @Override + public List findAllForUser(UUID userId) { + return findPageForUser(userId, null, null, Integer.MAX_VALUE); + } + + @Override + public List findPageForUser(UUID userId, UUID afterId, Instant afterCreatedAt, int limitPlusOne) { + StringBuilder sql = new StringBuilder(""" + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members cm ON cm.chat_id = c.id + WHERE cm.user_id = ? + """); + List parameters = new ArrayList<>(); + parameters.add(userId); + + if (afterCreatedAt != null) { + sql.append(" AND (c.created_at, c.id) > (?, ?) "); + parameters.add(Timestamp.from(afterCreatedAt)); + parameters.add(afterId); + } + sql.append(" ORDER BY c.created_at, c.id LIMIT ? "); + parameters.add(limitPlusOne); + + return jdbc.query(sql.toString(), (rs, rowNum) -> new ChatRow( + rs.getObject("id", UUID.class), + rs.getString("title"), + rs.getTimestamp("created_at").toInstant()), parameters.toArray()) + .stream().map(this::toChat).toList(); + } + + private Chat toChat(ChatRow row) { + List members = jdbc.queryForList(""" + SELECT user_id + FROM chat_members + WHERE chat_id = ? + ORDER BY joined_at, user_id + """, UUID.class, row.id()); + return new Chat(row.id(), row.title(), members, row.createdAt()); + } + + private record ChatRow(UUID id, String title, Instant createdAt) {} +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresMessageRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresMessageRepository.java new file mode 100644 index 00000000..0008a7a3 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresMessageRepository.java @@ -0,0 +1,134 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Message; +import com.example.mtusi_messenger.model.IdempotentMessage; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Repository +public class PostgresMessageRepository implements MessageRepository { + private final JdbcTemplate jdbc; + + public PostgresMessageRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + public Message save(Message message) { + jdbc.update(""" + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES (?, ?, ?, ?, ?) + """, message.id(), message.chatId(), message.senderId(), message.text(), + Timestamp.from(message.createdAt())); + return message; + } + + @Override + public void lockIdempotencyScope(UUID userId, String method, String path, String key) { + String scope = userId + "\n" + method + "\n" + path + "\n" + key; + jdbc.query( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + rs -> { + rs.next(); + return null; + }, + scope); + } + + @Override + public void deleteExpiredIdempotency( + UUID userId, + String method, + String path, + String key, + Instant expiresBefore + ) { + jdbc.update(""" + DELETE FROM message_idempotency + WHERE user_id = ? + AND method = ? + AND request_path = ? + AND idempotency_key = ? + AND created_at < ? + """, userId, method, path, key, Timestamp.from(expiresBefore)); + } + + @Override + public Optional findIdempotent( + UUID userId, + String method, + String path, + String key + ) { + return jdbc.query(""" + SELECT i.request_hash, + m.id, m.chat_id, m.sender_id, m.text, m.created_at + FROM message_idempotency i + JOIN messages m ON m.id = i.message_id + WHERE i.user_id = ? + AND i.method = ? + AND i.request_path = ? + AND i.idempotency_key = ? + """, (rs, rowNum) -> new IdempotentMessage( + rs.getBytes("request_hash"), + new Message( + rs.getObject("id", UUID.class), + rs.getObject("chat_id", UUID.class), + rs.getObject("sender_id", UUID.class), + rs.getString("text"), + rs.getTimestamp("created_at").toInstant())), + userId, method, path, key).stream().findFirst(); + } + + @Override + public void saveIdempotency( + UUID userId, + String method, + String path, + String key, + byte[] requestHash, + UUID messageId, + Instant createdAt + ) { + jdbc.update(""" + INSERT INTO message_idempotency + (user_id, method, request_path, idempotency_key, + request_hash, message_id, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + """, userId, method, path, key, requestHash, messageId, + Timestamp.from(createdAt)); + } + + @Override + public List findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne) { + StringBuilder sql = new StringBuilder(""" + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = ? + """); + List parameters = new ArrayList<>(); + parameters.add(chatId); + + if (afterCreatedAt != null) { + sql.append(" AND (created_at, id) > (?, ?) "); + parameters.add(Timestamp.from(afterCreatedAt)); + parameters.add(afterId); + } + sql.append(" ORDER BY created_at, id LIMIT ? "); + parameters.add(limitPlusOne); + + return jdbc.query(sql.toString(), (rs, rowNum) -> new Message( + rs.getObject("id", UUID.class), + rs.getObject("chat_id", UUID.class), + rs.getObject("sender_id", UUID.class), + rs.getString("text"), + rs.getTimestamp("created_at").toInstant()), parameters.toArray()); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresSessionRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresSessionRepository.java new file mode 100644 index 00000000..d0b210b0 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresSessionRepository.java @@ -0,0 +1,51 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Session; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.util.Optional; +import java.util.UUID; + +@Repository +public class PostgresSessionRepository implements SessionRepository { + private final JdbcTemplate jdbc; + + public PostgresSessionRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + public Session save(Session session) { + jdbc.update(""" + INSERT INTO sessions (id, user_id, token_hash, created_at, expires_at) + VALUES (?, ?, ?, ?, ?) + """, session.id(), session.userId(), session.tokenHash(), + Timestamp.from(session.createdAt()), Timestamp.from(session.expiresAt())); + return session; + } + + @Override + public Optional findActiveUserId(byte[] tokenHash) { + return jdbc.query(""" + SELECT user_id + FROM sessions + WHERE token_hash = ? + AND revoked_at IS NULL + AND expires_at > CURRENT_TIMESTAMP + """, (rs, rowNum) -> rs.getObject("user_id", UUID.class), tokenHash) + .stream().findFirst(); + } + + @Override + public boolean revoke(byte[] tokenHash) { + return jdbc.update(""" + UPDATE sessions + SET revoked_at = CURRENT_TIMESTAMP + WHERE token_hash = ? + AND revoked_at IS NULL + AND expires_at > CURRENT_TIMESTAMP + """, tokenHash) == 1; + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/PostgresUserRepository.java b/src/main/java/com/example/mtusi_messenger/repository/PostgresUserRepository.java new file mode 100644 index 00000000..e096b480 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/PostgresUserRepository.java @@ -0,0 +1,72 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.User; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.util.Optional; +import java.util.UUID; + +@Repository +public class PostgresUserRepository implements UserRepository { + private final JdbcTemplate jdbc; + + public PostgresUserRepository(JdbcTemplate jdbc) { + this.jdbc = jdbc; + } + + @Override + public User save(User user, String passwordHash) { + jdbc.update(""" + INSERT INTO users (id, username, display_name, password_hash, created_at) + VALUES (?, ?, ?, ?, ?) + """, user.id(), user.username(), user.displayName(), passwordHash, + Timestamp.from(user.createdAt())); + return user; + } + + @Override + public Optional findById(UUID id) { + return jdbc.query(""" + SELECT id, username, display_name, created_at + FROM users + WHERE id = ? + """, (rs, rowNum) -> new User( + rs.getObject("id", UUID.class), + rs.getString("username"), + rs.getString("display_name"), + rs.getTimestamp("created_at").toInstant()), id) + .stream().findFirst(); + } + + @Override + public Optional findByUsername(String username) { + return jdbc.query(""" + SELECT id, username, display_name, created_at + FROM users + WHERE username = ? + """, (rs, rowNum) -> new User( + rs.getObject("id", UUID.class), + rs.getString("username"), + rs.getString("display_name"), + rs.getTimestamp("created_at").toInstant()), username) + .stream().findFirst(); + } + + @Override + public Optional findCredentialsByUsername(String username) { + return jdbc.query(""" + SELECT id, username, display_name, password_hash, created_at + FROM users + WHERE username = ? + """, (rs, rowNum) -> new UserCredentials( + new User( + rs.getObject("id", UUID.class), + rs.getString("username"), + rs.getString("display_name"), + rs.getTimestamp("created_at").toInstant()), + rs.getString("password_hash")), username) + .stream().findFirst(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/SessionRepository.java b/src/main/java/com/example/mtusi_messenger/repository/SessionRepository.java new file mode 100644 index 00000000..801c9cf4 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/SessionRepository.java @@ -0,0 +1,12 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.Session; + +import java.util.Optional; +import java.util.UUID; + +public interface SessionRepository { + Session save(Session session); + Optional findActiveUserId(byte[] tokenHash); + boolean revoke(byte[] tokenHash); +} diff --git a/src/main/java/com/example/mtusi_messenger/repository/UserRepository.java b/src/main/java/com/example/mtusi_messenger/repository/UserRepository.java new file mode 100644 index 00000000..e4861960 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/repository/UserRepository.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.repository; + +import com.example.mtusi_messenger.model.User; +import java.util.Optional; +import java.util.UUID; + +public interface UserRepository { + User save(User user, String passwordHash); + Optional findById(UUID id); + Optional findByUsername(String username); + Optional findCredentialsByUsername(String username); + + record UserCredentials(User user, String passwordHash) {} +} diff --git a/src/main/java/com/example/mtusi_messenger/security/ApiAuthenticationFilter.java b/src/main/java/com/example/mtusi_messenger/security/ApiAuthenticationFilter.java new file mode 100644 index 00000000..213d8a35 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/ApiAuthenticationFilter.java @@ -0,0 +1,130 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.service.AuthenticationService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Enumeration; +import java.util.List; + +public class ApiAuthenticationFilter extends OncePerRequestFilter { + private static final String AUTHORIZATION = "Authorization"; + private static final String SESSION_PATH = "/api/v1/auth/sessions"; + + private final AuthenticationManager authenticationManager; + private final AuthenticationService sessions; + private final RestAuthenticationEntryPoint basicEntryPoint; + private final RestAuthenticationEntryPoint bearerEntryPoint; + + public ApiAuthenticationFilter( + AuthenticationManager authenticationManager, + AuthenticationService sessions, + RestAuthenticationEntryPoint basicEntryPoint, + RestAuthenticationEntryPoint bearerEntryPoint + ) { + this.authenticationManager = authenticationManager; + this.sessions = sessions; + this.basicEntryPoint = basicEntryPoint; + this.bearerEntryPoint = bearerEntryPoint; + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + boolean basicLogin = HttpMethod.POST.matches(request.getMethod()) + && SESSION_PATH.equals(request.getRequestURI()); + if (isPublicRequest(request) && !basicLogin) { + filterChain.doFilter(request, response); + return; + } + + try { + Authentication authentication = basicLogin + ? authenticateBasic(request) + : authenticateBearer(request); + var context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authentication); + SecurityContextHolder.setContext(context); + filterChain.doFilter(request, response); + } catch (AuthenticationException e) { + SecurityContextHolder.clearContext(); + (basicLogin ? basicEntryPoint : bearerEntryPoint) + .commence(request, response, e); + } finally { + SecurityContextHolder.clearContext(); + } + } + + private Authentication authenticateBasic(HttpServletRequest request) { + String header = singleAuthorizationHeader(request); + if (!header.startsWith("Basic ") || header.length() == 6) { + throw new BadCredentialsException("Invalid Basic credentials"); + } + try { + byte[] decoded = Base64.getDecoder().decode(header.substring(6)); + String credentials = new String(decoded, StandardCharsets.UTF_8); + int separator = credentials.indexOf(':'); + if (separator <= 0) { + throw new BadCredentialsException("Invalid Basic credentials"); + } + return authenticationManager.authenticate( + UsernamePasswordAuthenticationToken.unauthenticated( + credentials.substring(0, separator), + credentials.substring(separator + 1))); + } catch (IllegalArgumentException e) { + throw new BadCredentialsException("Invalid Basic credentials", e); + } + } + + private Authentication authenticateBearer(HttpServletRequest request) { + String header = singleAuthorizationHeader(request); + if (!header.startsWith("Bearer ") || header.length() == 7) { + throw new BadCredentialsException("Invalid Bearer token"); + } + String token = header.substring(7); + if (!token.matches("[A-Za-z0-9_-]{43}")) { + throw new BadCredentialsException("Invalid Bearer token"); + } + SessionPrincipal principal = sessions.authenticateBearer(token); + return UsernamePasswordAuthenticationToken.authenticated(principal, null, List.of()); + } + + private String singleAuthorizationHeader(HttpServletRequest request) { + Enumeration values = request.getHeaders(AUTHORIZATION); + if (values == null || !values.hasMoreElements()) { + throw new BadCredentialsException("Authentication required"); + } + String value = values.nextElement(); + if (values.hasMoreElements()) { + throw new BadCredentialsException("Multiple Authorization headers"); + } + return value; + } + + private boolean isPublicRequest(HttpServletRequest request) { + String path = request.getRequestURI(); + return path.startsWith("/health/") + || path.equals("/swagger-ui.html") + || path.startsWith("/swagger-ui/") + || path.equals("/v3/api-docs") + || path.startsWith("/v3/api-docs/") + || (HttpMethod.POST.matches(request.getMethod()) + && "/api/v1/users".equals(path)); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/DatabaseAuthenticationProvider.java b/src/main/java/com/example/mtusi_messenger/security/DatabaseAuthenticationProvider.java new file mode 100644 index 00000000..0a0c04da --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/DatabaseAuthenticationProvider.java @@ -0,0 +1,63 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.repository.UserRepository; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; +import org.springframework.dao.DataAccessException; + +import java.util.List; + +@Component +public class DatabaseAuthenticationProvider implements AuthenticationProvider { + private final UserRepository users; + private final PasswordEncoder passwordEncoder; + private final String dummyPasswordHash; + + public DatabaseAuthenticationProvider(UserRepository users, PasswordEncoder passwordEncoder) { + this.users = users; + this.passwordEncoder = passwordEncoder; + this.dummyPasswordHash = passwordEncoder.encode("dummy-password-used-only-for-timing"); + } + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + String username = authentication.getName(); + String password = String.valueOf(authentication.getCredentials()); + final java.util.Optional stored; + try { + stored = users.findCredentialsByUsername(username); + } catch (DataAccessException e) { + throw new AuthenticationServiceException("Authentication database is unavailable", e); + } + String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash) + .filter(hash -> hash.startsWith("$argon2")) + .orElse(dummyPasswordHash); + + boolean matches; + try { + matches = passwordEncoder.matches(password, passwordHash); + } catch (IllegalArgumentException e) { + matches = false; + } + + if (stored.isEmpty() || !matches) { + throw new BadCredentialsException("Invalid credentials"); + } + + return UsernamePasswordAuthenticationToken.authenticated( + stored.get().user(), + null, + List.of()); + } + + @Override + public boolean supports(Class authentication) { + return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/RestAuthenticationEntryPoint.java b/src/main/java/com/example/mtusi_messenger/security/RestAuthenticationEntryPoint.java new file mode 100644 index 00000000..4442f35c --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/RestAuthenticationEntryPoint.java @@ -0,0 +1,46 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.dto.ErrorResponse; +import com.example.mtusi_messenger.web.RequestIdFilter; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.MediaType; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.web.AuthenticationEntryPoint; + +import java.io.IOException; + +public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { + private final ObjectMapper mapper; + private final String challenge; + + public RestAuthenticationEntryPoint(ObjectMapper mapper, String challenge) { + this.mapper = mapper; + this.challenge = challenge; + } + + @Override + public void commence( + HttpServletRequest request, + HttpServletResponse response, + AuthenticationException exception + ) throws IOException { + String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE); + boolean unavailable = exception instanceof AuthenticationServiceException; + response.setStatus(unavailable + ? HttpServletResponse.SC_SERVICE_UNAVAILABLE + : HttpServletResponse.SC_UNAUTHORIZED); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + if (!unavailable) { + response.setHeader("WWW-Authenticate", challenge); + } + mapper.writeValue(response.getOutputStream(), new ErrorResponse( + new ErrorResponse.ErrorBody( + unavailable ? "unavailable" : "unauthorized", + unavailable ? "Authentication service temporarily unavailable" : "Authentication required", + requestId))); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/security/SessionPrincipal.java b/src/main/java/com/example/mtusi_messenger/security/SessionPrincipal.java new file mode 100644 index 00000000..03c39516 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/security/SessionPrincipal.java @@ -0,0 +1,14 @@ +package com.example.mtusi_messenger.security; + +import com.example.mtusi_messenger.model.User; + +public record SessionPrincipal(User user, byte[] tokenHash) { + public SessionPrincipal { + tokenHash = tokenHash.clone(); + } + + @Override + public byte[] tokenHash() { + return tokenHash.clone(); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/AuthenticationService.java b/src/main/java/com/example/mtusi_messenger/service/AuthenticationService.java new file mode 100644 index 00000000..42abab99 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/AuthenticationService.java @@ -0,0 +1,104 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.cache.UserCache; +import com.example.mtusi_messenger.model.Session; +import com.example.mtusi_messenger.model.User; +import com.example.mtusi_messenger.repository.SessionRepository; +import com.example.mtusi_messenger.repository.UserRepository; +import com.example.mtusi_messenger.security.SessionPrincipal; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.stereotype.Service; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.UUID; + +@Service +public class AuthenticationService { + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + + private final UserRepository users; + private final SessionRepository sessions; + private final UserCache userCache; + private final long ttlSeconds; + + public AuthenticationService( + UserRepository users, + SessionRepository sessions, + UserCache userCache, + @Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds + ) { + if (ttlSeconds <= 0) { + throw new IllegalArgumentException("Session TTL must be positive"); + } + this.users = users; + this.sessions = sessions; + this.userCache = userCache; + this.ttlSeconds = ttlSeconds; + } + + public IssuedSession issueSession(User user) { + String token = newToken(); + Instant createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS); + Instant expiresAt = createdAt.plusSeconds(ttlSeconds); + sessions.save(new Session( + UUID.randomUUID(), + user.id(), + hashToken(token), + createdAt, + expiresAt)); + return new IssuedSession(token, expiresAt, user); + } + + public SessionPrincipal authenticateBearer(String token) { + byte[] tokenHash = hashToken(token); + try { + UUID userId = sessions.findActiveUserId(tokenHash) + .orElseThrow(() -> new BadCredentialsException("Invalid or expired session")); + User user = userCache.find(userId).orElseGet(() -> { + User loaded = users.findById(userId) + .orElseThrow(() -> new BadCredentialsException("Invalid or expired session")); + userCache.put(loaded); + return loaded; + }); + return new SessionPrincipal(user, tokenHash); + } catch (DataAccessException e) { + throw new AuthenticationServiceException("Authentication database is unavailable", e); + } + } + + public void revoke(SessionPrincipal principal) { + try { + if (!sessions.revoke(principal.tokenHash())) { + throw new BadCredentialsException("Invalid or expired session"); + } + } catch (DataAccessException e) { + throw new AuthenticationServiceException("Authentication database is unavailable", e); + } + } + + private String newToken() { + byte[] bytes = new byte[32]; + SECURE_RANDOM.nextBytes(bytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private byte[] hashToken(String token) { + try { + return MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(StandardCharsets.US_ASCII)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + } + + public record IssuedSession(String token, Instant expiresAt, User user) {} +} diff --git a/src/main/java/com/example/mtusi_messenger/service/ChatService.java b/src/main/java/com/example/mtusi_messenger/service/ChatService.java new file mode 100644 index 00000000..38eeff2d --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/ChatService.java @@ -0,0 +1,38 @@ +package com.example.mtusi_messenger.service; + +import org.springframework.stereotype.Service; +import com.example.mtusi_messenger.dto.CreateChatRequest; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.Chat; +import com.example.mtusi_messenger.repository.ChatRepository; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.*; + +@Service +public class ChatService { + private final ChatRepository chats; private final UserService users; private final CursorService cursors; + public ChatService(ChatRepository chats, UserService users, CursorService cursors) { this.chats=chats; this.users=users; this.cursors=cursors; } + public Chat create(CreateChatRequest r, UUID caller) { + Set ids = new LinkedHashSet<>(r.member_ids()); + if (ids.size() != r.member_ids().size() || !ids.contains(caller)) throw ApiExceptions.invalid("Invalid member_ids"); + for (UUID id : ids) if (id == null || !users.exists(id)) throw ApiExceptions.invalid("Invalid member_ids"); + return chats.save(new Chat(UUID.randomUUID(), r.title(), List.copyOf(ids), + Instant.now().truncatedTo(ChronoUnit.MICROS))); + } + public Chat getAccessible(UUID chatId, UUID userId) { + users.get(userId); + if (!chats.isMember(chatId, userId)) throw ApiExceptions.notFound("Chat not found"); + return chats.findById(chatId).orElseThrow(() -> ApiExceptions.notFound("Chat not found")); + } + public List page(UUID userId, int limit, String cursor) { + CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "chats", userId); + return chats.findPageForUser(userId, c == null ? null : c.id(), c == null ? null : c.createdAt(), limit + 1); + } + public String nextCursor(UUID userId, + Chat last, + boolean hasNext + ) { + return hasNext ? cursors.encode("chats", userId, last.createdAt(), last.id()) : null; + } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/CursorService.java b/src/main/java/com/example/mtusi_messenger/service/CursorService.java new file mode 100644 index 00000000..87cd7ffb --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/CursorService.java @@ -0,0 +1,40 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.exception.ApiException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.stereotype.Service; +import com.example.mtusi_messenger.exception.ApiExceptions; +import java.time.Instant; +import java.util.Base64; +import java.util.UUID; + +@Service +public class CursorService { + private final ObjectMapper mapper; + public CursorService(ObjectMapper mapper) { this.mapper = mapper; } + + public String encode(String resource, UUID resourceId, Instant createdAt, UUID id) { + try { + byte[] json = mapper.writeValueAsBytes(new CursorPayload(1, resource, resourceId, createdAt.toString(), id)); + return Base64.getUrlEncoder().withoutPadding().encodeToString(json); + } catch (Exception e) { throw new IllegalStateException(e); } + } + public Cursor decode(String raw, String resource, UUID resourceId) { + if (raw == null || raw.isBlank()) throw ApiExceptions.invalid("Invalid cursor"); + try { + CursorPayload p = mapper.readValue(Base64.getUrlDecoder().decode(raw), CursorPayload.class); + if (p.v != 1 + || !resource.equals(p.resource) + || !Objects.equals(resourceId, p.resourceId) + || p.createdAt() == null + || p.createdAt().isBlank() + || p.id() == null + ) throw ApiExceptions.invalid("Invalid cursor"); + return new Cursor(Instant.parse(p.createdAt), p.id); + } catch (ApiException e) { throw e; } + catch (Exception e) { throw ApiExceptions.invalid("Invalid cursor"); } + } + public record Cursor(Instant createdAt, UUID id) {} + private record CursorPayload(int v, String resource, UUID resourceId, String createdAt, UUID id) {} + private static final class Objects { static boolean equals(Object a, Object b) { return java.util.Objects.equals(a,b); } } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/MessageService.java b/src/main/java/com/example/mtusi_messenger/service/MessageService.java new file mode 100644 index 00000000..a618ff46 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/MessageService.java @@ -0,0 +1,89 @@ +package com.example.mtusi_messenger.service; + +import com.github.f4b6a3.uuid.UuidCreator; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.IdempotentMessage; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.example.mtusi_messenger.dto.CreateMessageRequest; +import com.example.mtusi_messenger.model.Message; +import com.example.mtusi_messenger.repository.MessageRepository; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +@Service +public class MessageService { + private static final String METHOD = "POST"; + private final MessageRepository messages; + private final ChatService chats; + private final CursorService cursors; + private final Duration idempotencyTtl; + + public MessageService( + MessageRepository messages, + ChatService chats, + CursorService cursors, + @Value("${messenger.idempotency.ttl-seconds:86400}") long idempotencyTtlSeconds + ) { + if (idempotencyTtlSeconds < 86400) { + throw new IllegalArgumentException("Idempotency TTL must be at least 24 hours"); + } + this.messages = messages; + this.chats = chats; + this.cursors = cursors; + this.idempotencyTtl = Duration.ofSeconds(idempotencyTtlSeconds); + } + + @Transactional + public Message create(UUID chatId, UUID senderId, CreateMessageRequest r, String idempotencyKey) { + chats.getAccessible(chatId, senderId); + String path = "/api/v1/chats/" + chatId + "/messages"; + byte[] requestHash = hash(r.text()); + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + + // The transaction-scoped PostgreSQL advisory lock serializes the same + // idempotency scope across every API replica. A hash collision only + // causes harmless extra serialization; the full scope is still checked. + messages.lockIdempotencyScope(senderId, METHOD, path, idempotencyKey); + messages.deleteExpiredIdempotency( + senderId, METHOD, path, idempotencyKey, now.minus(idempotencyTtl)); + + var existing = messages.findIdempotent(senderId, METHOD, path, idempotencyKey); + if (existing.isPresent()) { + IdempotentMessage value = existing.get(); + if (!Arrays.equals(value.requestHash(), requestHash)) { + throw ApiExceptions.conflict("Idempotency-Key was already used with another request body"); + } + return value.message(); + } + + Message message = messages.save(new Message( + UuidCreator.getTimeOrderedEpochPlus1(), chatId, senderId, r.text(), now)); + messages.saveIdempotency( + senderId, METHOD, path, idempotencyKey, requestHash, message.id(), now); + return message; + } + + private static byte[] hash(String text) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + return digest.digest(text.getBytes(StandardCharsets.UTF_8)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + } + public List page(UUID chatId, UUID userId, int limit, String cursor) { + chats.getAccessible(chatId, userId); + CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "messages", chatId); + return messages.findPage(chatId, c == null ? null : c.createdAt(), c == null ? null : c.id(), limit + 1); + } + public String nextCursor(UUID chatId, Message last, boolean hasNext) { return hasNext ? cursors.encode("messages", chatId, last.createdAt(), last.id()) : null; } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/UserService.java b/src/main/java/com/example/mtusi_messenger/service/UserService.java new file mode 100644 index 00000000..c8bed8b4 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/UserService.java @@ -0,0 +1,34 @@ +package com.example.mtusi_messenger.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.security.crypto.password.PasswordEncoder; +import com.example.mtusi_messenger.dto.CreateUserRequest; +import com.example.mtusi_messenger.exception.ApiExceptions; +import com.example.mtusi_messenger.model.User; +import com.example.mtusi_messenger.repository.UserRepository; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +@Service +@RequiredArgsConstructor +public class UserService { + private final UserRepository users; + private final PasswordEncoder passwordEncoder; + + public User create(CreateUserRequest r) { + String username = r.username(); String display = r.display_name(); + if (users.findByUsername(username).isPresent()) throw ApiExceptions.conflict("Username is already taken"); + String passwordHash = passwordEncoder.encode(r.password()); + try { + return users.save(new User(UUID.randomUUID(), username, display, + Instant.now().truncatedTo(ChronoUnit.MICROS)), passwordHash); + } catch (DuplicateKeyException e) { + throw ApiExceptions.conflict("Username is already taken"); + } + } + public User get(UUID id) { return users.findById(id).orElseThrow(() -> ApiExceptions.unauthorized("Unknown user identity")); } + public boolean exists(UUID id) { return users.findById(id).isPresent(); } +} diff --git a/src/main/java/com/example/mtusi_messenger/service/UuidValidator.java b/src/main/java/com/example/mtusi_messenger/service/UuidValidator.java new file mode 100644 index 00000000..ea292fee --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/service/UuidValidator.java @@ -0,0 +1,27 @@ +package com.example.mtusi_messenger.service; + +import com.example.mtusi_messenger.exception.ApiExceptions; + +import java.util.UUID; +import java.util.regex.Pattern; + +public final class UuidValidator { + + private static final Pattern UUID_PATTERN = Pattern.compile( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" + ); + + private UuidValidator() {} + + public static UUID parse(String value) { + if (value == null || !UUID_PATTERN.matcher(value).matches()) { + throw ApiExceptions.invalid("Invalid UUID"); + } + + try { + return UUID.fromString(value); + } catch (IllegalArgumentException e) { + throw ApiExceptions.invalid("Invalid UUID"); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/web/GlobalExceptionHandler.java b/src/main/java/com/example/mtusi_messenger/web/GlobalExceptionHandler.java new file mode 100644 index 00000000..2e77439e --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/GlobalExceptionHandler.java @@ -0,0 +1,48 @@ +package com.example.mtusi_messenger.web; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.dao.DataAccessException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import com.example.mtusi_messenger.dto.ErrorResponse; +import com.example.mtusi_messenger.exception.ApiException; + +@RestControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(ApiException.class) + ResponseEntity api(ApiException e, HttpServletRequest req) { + var body = body(e.code(), e.getMessage(), req); + var builder = ResponseEntity.status(e.status()); + if (e.status() == HttpStatus.UNAUTHORIZED && e.authenticate() != null) { + builder.header("WWW-Authenticate", e.authenticate()); + } + return builder.body(body); + } + @ExceptionHandler({MethodArgumentNotValidException.class, MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class}) + ResponseEntity bad(Exception e, HttpServletRequest req) { return ResponseEntity.badRequest().body(body("invalid_request", "Invalid request", req)); } + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + ResponseEntity unsupported(HttpServletRequest req) { return ResponseEntity.status(415).body(body("unsupported_media_type", "Unsupported media type", req)); } + @ExceptionHandler(DataAccessException.class) + ResponseEntity unavailable(DataAccessException e, HttpServletRequest req) { + return ResponseEntity.status(503).body(body("unavailable", "Storage temporarily unavailable", req)); + } + @ExceptionHandler(Exception.class) + ResponseEntity internal(Exception e, HttpServletRequest req) { return ResponseEntity.status(500).body(body("internal_error", "Internal server error", req)); } + private ErrorResponse body( + String code, + String message, + HttpServletRequest req + ) { + String id = (String) req.getAttribute(RequestIdFilter.ATTRIBUTE); + + return new ErrorResponse( + new ErrorResponse.ErrorBody(code, message, id) + ); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/InstanceIdFilter.java b/src/main/java/com/example/mtusi_messenger/web/InstanceIdFilter.java new file mode 100644 index 00000000..9c56a393 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/InstanceIdFilter.java @@ -0,0 +1,47 @@ +package com.example.mtusi_messenger.web; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.UUID; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE + 1) +public class InstanceIdFilter extends OncePerRequestFilter { + public static final String HEADER = "X-Instance-Id"; + private final String instanceId; + + public InstanceIdFilter() { + String configured = System.getenv("INSTANCE_ID"); + this.instanceId = configured == null || configured.isBlank() + ? localHostOrRandom() + : configured; + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + response.setHeader(HEADER, instanceId); + filterChain.doFilter(request, response); + } + + private static String localHostOrRandom() { + try { + return InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + return "api-" + UUID.randomUUID(); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/NotUnicodeBlank.java b/src/main/java/com/example/mtusi_messenger/web/NotUnicodeBlank.java new file mode 100644 index 00000000..a4213fc7 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/NotUnicodeBlank.java @@ -0,0 +1,21 @@ +package com.example.mtusi_messenger.web; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Documented +@Constraint(validatedBy = UnicodeBlankValidator.class) +@Target({ FIELD, PARAMETER, RECORD_COMPONENT, ANNOTATION_TYPE }) +@Retention(RUNTIME) +public @interface NotUnicodeBlank { + String message() default "must not be blank"; + Class[] groups() default {}; + Class[] payload() default {}; +} diff --git a/src/main/java/com/example/mtusi_messenger/web/RequestIdFilter.java b/src/main/java/com/example/mtusi_messenger/web/RequestIdFilter.java new file mode 100644 index 00000000..2b991b7a --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/RequestIdFilter.java @@ -0,0 +1,40 @@ +package com.example.mtusi_messenger.web; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.web.filter.OncePerRequestFilter; +import java.io.IOException; +import java.util.UUID; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class RequestIdFilter extends OncePerRequestFilter { + + public static final String HEADER = "X-Request-Id"; + public static final String ATTRIBUTE = "request_id"; + + @Override + protected void doFilterInternal( + HttpServletRequest req, + HttpServletResponse res, + FilterChain chain + ) throws ServletException, IOException { + + String id = UUID.randomUUID().toString(); + + req.setAttribute(ATTRIBUTE, id); + res.setHeader(HEADER, id); + + try { + chain.doFilter(req, res); + } finally { + MDC.remove(ATTRIBUTE); + } + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/UnicodeBlankValidator.java b/src/main/java/com/example/mtusi_messenger/web/UnicodeBlankValidator.java new file mode 100644 index 00000000..59893614 --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/UnicodeBlankValidator.java @@ -0,0 +1,23 @@ +package com.example.mtusi_messenger.web; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +public class UnicodeBlankValidator + implements ConstraintValidator { + + @Override + public boolean isValid( + String value, + ConstraintValidatorContext context) { + + if (value == null || value.isEmpty()) { + return false; + } + + return value.codePoints().anyMatch(codePoint -> + !Character.isWhitespace(codePoint) + && !Character.isSpaceChar(codePoint) + ); + } +} diff --git a/src/main/java/com/example/mtusi_messenger/web/UnicodeSize.java b/src/main/java/com/example/mtusi_messenger/web/UnicodeSize.java new file mode 100644 index 00000000..dde7ca9a --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/UnicodeSize.java @@ -0,0 +1,35 @@ +package com.example.mtusi_messenger.web; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Documented +@Constraint(validatedBy = UnicodeSizeValidator.class) +@Target({ + FIELD, + METHOD, + PARAMETER, + ANNOTATION_TYPE +}) +@Retention(RUNTIME) +public @interface UnicodeSize { + + String message() default "size must be between {min} and {max} Unicode code points"; + + int min() default 0; + + int max() default Integer.MAX_VALUE; + + Class[] groups() default {}; + + Class[] payload() default {}; +} \ No newline at end of file diff --git a/src/main/java/com/example/mtusi_messenger/web/UnicodeSizeValidator.java b/src/main/java/com/example/mtusi_messenger/web/UnicodeSizeValidator.java new file mode 100644 index 00000000..f978d54d --- /dev/null +++ b/src/main/java/com/example/mtusi_messenger/web/UnicodeSizeValidator.java @@ -0,0 +1,32 @@ +package com.example.mtusi_messenger.web; + +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +public class UnicodeSizeValidator + implements ConstraintValidator { + + private int min; + private int max; + + @Override + public void initialize(UnicodeSize annotation) { + this.min = annotation.min(); + this.max = annotation.max(); + } + + @Override + public boolean isValid( + String value, + ConstraintValidatorContext context + ) { + if (value == null) { + return true; + } + + int codePointCount = value.codePointCount(0, value.length()); + + return codePointCount >= min + && codePointCount <= max; + } +} \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 00000000..0846c221 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,62 @@ +spring: + application: + name: mtusi-messenger + + datasource: + url: ${DATABASE_URL:jdbc:postgresql://localhost:5432/messenger} + username: ${DATABASE_USER:messenger} + password: ${DATABASE_PASSWORD:messenger} + hikari: + maximum-pool-size: ${DATABASE_POOL_SIZE:10} + minimum-idle: ${DATABASE_MIN_IDLE:2} + connection-timeout: 5000 + validation-timeout: 2000 + idle-timeout: 600000 + max-lifetime: 1800000 + + data: + redis: + host: ${REDIS_HOST:localhost} + port: ${REDIS_PORT:6379} + connect-timeout: ${REDIS_CONNECT_TIMEOUT:1s} + timeout: ${REDIS_COMMAND_TIMEOUT:500ms} + lettuce: + pool: + max-active: ${REDIS_POOL_MAX_ACTIVE:8} + max-idle: ${REDIS_POOL_MAX_IDLE:8} + min-idle: ${REDIS_POOL_MIN_IDLE:0} + max-wait: ${REDIS_POOL_MAX_WAIT:500ms} + + jdbc: + template: + query-timeout: ${DATABASE_QUERY_TIMEOUT_SECONDS:5} + + transaction: + default-timeout: ${DATABASE_TRANSACTION_TIMEOUT_SECONDS:5} + + flyway: + # API replicas never race one another for migrations. Compose runs the + # same image once as the dedicated migrate service with this overridden. + enabled: ${FLYWAY_ENABLED:false} + locations: classpath:db/migration + + jackson: + deserialization: + fail-on-unknown-properties: true + + lifecycle: + timeout-per-shutdown-phase: 10s + +server: + address: ${APP_HOST:0.0.0.0} + port: ${APP_PORT:8080} + shutdown: graceful + +messenger: + storage: postgres + session: + ttl-seconds: ${SESSION_TTL_SECONDS:3600} + cache: + user-ttl-seconds: ${USER_CACHE_TTL_SECONDS:300} + idempotency: + ttl-seconds: ${IDEMPOTENCY_TTL_SECONDS:86400} diff --git a/src/main/resources/db/migration/V1__create_messenger_schema.sql b/src/main/resources/db/migration/V1__create_messenger_schema.sql new file mode 100644 index 00000000..06885a1c --- /dev/null +++ b/src/main/resources/db/migration/V1__create_messenger_schema.sql @@ -0,0 +1,60 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username varchar(32) NOT NULL, + display_name text NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT users_username_uk UNIQUE (username), + CONSTRAINT users_username_format_chk + CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_name_length_chk + CHECK (char_length(display_name) BETWEEN 1 AND 100) +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT chats_title_length_chk + CHECK (char_length(title) BETWEEN 1 AND 100) +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL, + user_id uuid NOT NULL, + joined_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT chat_members_pk PRIMARY KEY (chat_id, user_id), + CONSTRAINT chat_members_chat_fk + FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE, + CONSTRAINT chat_members_user_fk + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE RESTRICT +); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL, + sender_id uuid NOT NULL, + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT messages_text_length_chk + CHECK (char_length(text) BETWEEN 1 AND 4000), + CONSTRAINT messages_sender_membership_fk + FOREIGN KEY (chat_id, sender_id) + REFERENCES chat_members(chat_id, user_id) + ON DELETE RESTRICT +); + +CREATE INDEX chat_members_user_chat_idx + ON chat_members (user_id, chat_id); + +CREATE INDEX chats_created_id_idx + ON chats (created_at, id); + +CREATE INDEX messages_chat_created_id_idx + ON messages (chat_id, created_at, id); + +CREATE INDEX messages_sender_created_idx + ON messages (sender_id, created_at); diff --git a/src/main/resources/db/migration/V2__add_credentials_and_sessions.sql b/src/main/resources/db/migration/V2__add_credentials_and_sessions.sql new file mode 100644 index 00000000..d5d74279 --- /dev/null +++ b/src/main/resources/db/migration/V2__add_credentials_and_sessions.sql @@ -0,0 +1,28 @@ +ALTER TABLE users + ADD COLUMN password_hash text; + +ALTER TABLE users + ALTER COLUMN password_hash SET NOT NULL; + +CREATE TABLE sessions ( + id uuid PRIMARY KEY, + user_id uuid NOT NULL, + token_hash bytea NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at timestamptz NOT NULL, + revoked_at timestamptz, + + CONSTRAINT sessions_user_fk + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + CONSTRAINT sessions_token_hash_uk UNIQUE (token_hash), + CONSTRAINT sessions_token_hash_length_chk + CHECK (octet_length(token_hash) = 32), + CONSTRAINT sessions_expiry_chk + CHECK (expires_at > created_at), + CONSTRAINT sessions_revocation_chk + CHECK (revoked_at IS NULL OR revoked_at >= created_at) +); + +CREATE INDEX sessions_active_expiry_idx + ON sessions (expires_at) + WHERE revoked_at IS NULL; diff --git a/src/main/resources/db/migration/V3__add_message_idempotency.sql b/src/main/resources/db/migration/V3__add_message_idempotency.sql new file mode 100644 index 00000000..dfa127ca --- /dev/null +++ b/src/main/resources/db/migration/V3__add_message_idempotency.sql @@ -0,0 +1,25 @@ +CREATE TABLE message_idempotency ( + user_id uuid NOT NULL, + method varchar(8) NOT NULL, + request_path text NOT NULL, + idempotency_key varchar(128) NOT NULL, + request_hash bytea NOT NULL, + message_id uuid NOT NULL, + created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT message_idempotency_pk + PRIMARY KEY (user_id, method, request_path, idempotency_key), + CONSTRAINT message_idempotency_user_fk + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + CONSTRAINT message_idempotency_message_fk + FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE, + CONSTRAINT message_idempotency_method_chk + CHECK (method = 'POST'), + CONSTRAINT message_idempotency_key_format_chk + CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'), + CONSTRAINT message_idempotency_hash_length_chk + CHECK (octet_length(request_hash) = 32) +); + +CREATE INDEX message_idempotency_created_idx + ON message_idempotency (created_at); diff --git a/src/test/java/com/example/mtusi_messenger/MtusiMessengerApplicationTests.java b/src/test/java/com/example/mtusi_messenger/MtusiMessengerApplicationTests.java new file mode 100644 index 00000000..6a71efe7 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/MtusiMessengerApplicationTests.java @@ -0,0 +1,368 @@ +package com.example.mtusi_messenger; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest +@AutoConfigureMockMvc +class MtusiMessengerApplicationTests { + + private static final String USERS_URL = "/api/v1/users"; + private static final String CHATS_URL = "/api/v1/chats"; + private static final String SESSIONS_URL = "/api/v1/auth/sessions"; + private static final String TEST_PASSWORD = "correct horse battery staple"; + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + private User alice; + private User bob; + private User eve; + + @BeforeEach + void setUp() throws Exception { + String suffix = UUID.randomUUID() + .toString() + .replace("-", "") + .substring(0, 12); + + alice = registerUser("alice_" + suffix, "Alice"); + bob = registerUser("bob_" + suffix, "Bob"); + eve = registerUser("eve_" + suffix, "Eve"); + } + + @Test + void shouldReturn400WhenJsonIsMalformed() throws Exception { + mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content("{ \"username\": ")) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldReturn400WhenPasswordContainsOnlyWhitespace() throws Exception { + String requestBody = objectMapper.writeValueAsString( + Map.of( + "username", "blank_password_" + UUID.randomUUID().toString().substring(0, 8), + "display_name", "Blank password probe", + "password", " " + ) + ); + + mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldNotAllowNonMemberToReadChatMessages() throws Exception { + String chatId = createChat(alice, bob); + + mockMvc.perform(get(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(eve)) + .param("limit", "10")) + .andExpect(status().isNotFound()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("not_found")); + } + + @Test + void shouldNotAllowNonMemberToSendMessage() throws Exception { + String chatId = createChat(alice, bob); + + String requestBody = """ + { + "text": "Hello from Eve" + } + """; + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(eve)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isNotFound()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("not_found")); + } + + @Test + void shouldReturn400WhenMessageTextIsEmpty() throws Exception { + String chatId = createChat(alice, bob); + + String requestBody = """ + { + "text": "" + } + """; + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(alice)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldReturn400WhenMessageTextIsMissing() throws Exception { + String chatId = createChat(alice, bob); + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(alice)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content("{}")) + .andExpect(status().isBadRequest()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("invalid_request")); + } + + @Test + void shouldReturn409WhenUsernameAlreadyExists() throws Exception { + String requestBody = """ + { + "username": "%s", + "display_name": "Another Alice", + "password": "correct horse battery staple" + } + """.formatted(alice.username()); + + mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isConflict()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.error.code") + .value("conflict")); + } + + @Test + void shouldReturnAllMessagesAcrossMultiplePagesWithoutDuplicates() + throws Exception { + + String chatId = createChat(alice, bob); + + int messageCount = 5; + int pageSize = 2; + int expectedPageCount = 3; + + List expectedTexts = new ArrayList<>(); + + for (int i = 1; i <= messageCount; i++) { + String text = "Message " + i; + sendMessage(chatId, alice, text); + expectedTexts.add(text); + } + + List actualIds = new ArrayList<>(); + List actualTexts = new ArrayList<>(); + + String cursor = null; + int pageCount = 0; + + while (true) { + var request = get(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(alice)) + .param("limit", String.valueOf(pageSize)); + + if (cursor != null) { + request.param("cursor", cursor); + } + + MvcResult result = mockMvc.perform(request) + .andExpect(status().isOk()) + .andExpect(header().exists("X-Request-Id")) + .andExpect(jsonPath("$.items").isArray()) + .andReturn(); + + JsonNode response = objectMapper.readTree( + result.getResponse().getContentAsString() + ); + + JsonNode items = response.get("items"); + + assertNotNull(items); + assertTrue(items.size() <= pageSize); + + for (JsonNode item : items) { + actualIds.add(item.get("id").asText()); + actualTexts.add(item.get("text").asText()); + } + + pageCount++; + + JsonNode nextCursor = response.get("next_cursor"); + + if (nextCursor.isNull()) { + break; + } + + cursor = nextCursor.asText(); + + assertFalse(cursor.isBlank(), + "next_cursor must not be blank when more pages exist"); + + assertTrue(pageCount <= messageCount, + "Pagination did not terminate"); + } + + assertEquals(expectedPageCount, pageCount); + + assertEquals(messageCount, actualIds.size()); + assertEquals(messageCount, actualTexts.size()); + + assertEquals(actualIds.size(), new HashSet<>(actualIds).size()); + + assertEquals(expectedTexts, actualTexts); + } + + @Test + void shouldIgnoreXUserIdForProtectedEndpoints() throws Exception { + mockMvc.perform(get(USERS_URL + "/me") + .header("X-User-Id", alice.id())) + .andExpect(status().isUnauthorized()) + .andExpect(header().string("WWW-Authenticate", "Bearer realm=\"messenger\"")); + } + + @Test + void shouldRevokeCurrentSession() throws Exception { + mockMvc.perform(delete(SESSIONS_URL + "/current") + .header("Authorization", bearer(alice))) + .andExpect(status().isNoContent()); + + mockMvc.perform(get(USERS_URL + "/me") + .header("Authorization", bearer(alice))) + .andExpect(status().isUnauthorized()) + .andExpect(header().string("WWW-Authenticate", "Bearer realm=\"messenger\"")); + } + + @Test + void shouldRejectWrongPasswordWithBasicChallenge() throws Exception { + String basic = Base64.getEncoder().encodeToString( + (alice.username() + ":definitely-wrong-password") + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + + mockMvc.perform(post(SESSIONS_URL) + .header("Authorization", "Basic " + basic)) + .andExpect(status().isUnauthorized()) + .andExpect(header().string( + "WWW-Authenticate", + "Basic realm=\"messenger\", charset=\"UTF-8\"")); + } + + private User registerUser(String username, String displayName) + throws Exception { + + String requestBody = objectMapper.writeValueAsString( + Map.of( + "username", username, + "display_name", displayName, + "password", TEST_PASSWORD + ) + ); + + MvcResult result = mockMvc.perform(post(USERS_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isCreated()) + .andExpect(header().exists("X-Request-Id")) + .andReturn(); + + JsonNode response = objectMapper.readTree( + result.getResponse().getContentAsString() + ); + + String basic = Base64.getEncoder().encodeToString( + (username + ":" + TEST_PASSWORD).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + MvcResult loginResult = mockMvc.perform(post(SESSIONS_URL) + .header("Authorization", "Basic " + basic)) + .andExpect(status().isCreated()) + .andReturn(); + JsonNode session = objectMapper.readTree(loginResult.getResponse().getContentAsString()); + + return new User( + response.get("id").asText(), + response.get("username").asText(), + session.get("token").asText() + ); + } + + private String createChat(User owner, User member) + throws Exception { + + String requestBody = objectMapper.writeValueAsString( + java.util.Map.of( + "title", "Test chat " + UUID.randomUUID(), + "member_ids", List.of(owner.id(), member.id()) + ) + ); + + MvcResult result = mockMvc.perform(post(CHATS_URL) + .header("Authorization", bearer(owner)) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isCreated()) + .andExpect(header().exists("X-Request-Id")) + .andReturn(); + + JsonNode response = objectMapper.readTree( + result.getResponse().getContentAsString() + ); + + return response.get("id").asText(); + } + + private void sendMessage(String chatId, User sender, String text) + throws Exception { + + String requestBody = objectMapper.writeValueAsString( + java.util.Map.of("text", text) + ); + + mockMvc.perform(post(CHATS_URL + "/" + chatId + "/messages") + .header("Authorization", bearer(sender)) + .header("Idempotency-Key", UUID.randomUUID().toString()) + .contentType(MediaType.APPLICATION_JSON) + .content(requestBody)) + .andExpect(status().isCreated()) + .andExpect(header().exists("X-Request-Id")); + } + + private static String bearer(User user) { + return "Bearer " + user.token(); + } + + private record User(String id, String username, String token) { + } +} diff --git a/src/test/java/com/example/mtusi_messenger/cache/UserCacheTest.java b/src/test/java/com/example/mtusi_messenger/cache/UserCacheTest.java new file mode 100644 index 00000000..fdc05347 --- /dev/null +++ b/src/test/java/com/example/mtusi_messenger/cache/UserCacheTest.java @@ -0,0 +1,31 @@ +package com.example.mtusi_messenger.cache; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; + +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class UserCacheTest { + + @Test + void shouldEvictJsonNullAndReturnCacheMiss() { + UUID userId = UUID.randomUUID(); + String key = "messenger:user:" + userId; + StringRedisTemplate redis = mock(StringRedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations values = mock(ValueOperations.class); + when(redis.opsForValue()).thenReturn(values); + when(values.get(key)).thenReturn("null"); + UserCache cache = new UserCache(redis, new ObjectMapper(), 300); + + assertTrue(cache.find(userId).isEmpty()); + verify(redis).delete(key); + } +} diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 00000000..0dfa3f89 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,57 @@ +# Публичные проверки + +Python **3.9+**, стандартная библиотека. Сервер уже должен быть запущен; проверки не создают готовое приложение и сами не управляют Docker. `make check` можно выполнить на исходном skeleton, `make test` — только после реализации API. Полная OpenAPI-валидация отдельно: `make validate` после установки `requirements-dev.txt` в venv. + +```sh +make check +make test BASE_URL=http://localhost:8080 +# без make: +python3 tests/smoke.py --base-url http://localhost:8080 +``` + +`smoke.py` выполняет **один сквозной сценарий**, автоматически выбирая профиль из `lab.json`: health → три пользователя → вход с lab2 → чат → сообщения → пагинация → ошибки доступа → идемпотентность с lab3 → файл с lab4 → thumbnail с lab5 → logout. Он проверяет JSON по используемому подмножеству схемы, коды/headers, Unicode, SHA-256 оригинала и фактические JPEG-размеры thumbnail. Это публичный минимум, не полный fuzz/security/load suite. + +Каждый запуск создаёт уникальных синтетических пользователей, чат и сообщения. Данные автоматически не удаляются: в API курса нет delete. Для чистого повтора используйте отдельный тестовый стенд/volume и осознанный сброс своего окружения. Session tokens хранятся только в памяти процесса и не печатаются/не сохраняются. + +## Проверка сохранности, lab2+ + +Скопируйте `scripts/restart.example.sh` в `scripts/restart.sh`, реализуйте перезапуск **API и всех используемых хранилищ** с сохранением volumes и задайте executable bit. Скрипт может опираться на ваш compose.yaml или stack.yaml. Он не должен удалять volumes, повторно seed-ить БД или менять тестовые данные. + +```sh +chmod +x scripts/restart.sh +make test-persistence ACTION_SCRIPT=scripts/restart.sh +``` + +Тест создаёт данные и сессию, запускает указанный файл без shell interpolation, ожидает готовности и проверяет те же данные **с прежним токеном**. В lab4+ также проверяется исходный файл. Hook может работать до 90 секунд, готовность затем ожидается до 90 секунд. TTL сессии для этого теста — минимум 300 секунд. Успех не доказывает, что hook действительно перезапустил БД: приложите команды/состояния контейнеров до и после. + +## Проверка отказа, lab3+ + +Реализуйте `scripts/stop-one.sh` на основе примера. `TARGET_INSTANCE_ID` в окружении содержит alias обслужившей тест API-реплики: сопоставьте его своему контейнеру/Swarm task и остановите именно его. Скрипт должен быстро вернуть 0 и **оставить эту реплику остановленной**; восстановление выполняйте отдельно. Swarm может создать новую task с другим ID — это допустимо. + +```sh +chmod +x scripts/stop-one.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +``` + +Перед отказом тест наблюдает ≥2 API-реплики; 15 секунд отправляет сообщения параллельно выполнению hook, повторяет неопределённый POST с тем же ключом, проверяет восстановление записи за ≤10 секунд, отсутствие остановленной реплики в последних ответах, сохранность подтверждённых сообщений и отсутствие дублей. Ошибки переходного периода учитываются. Затем восстановите реплику и повторите для другой. Скрипт — проверка одного отказа API, не гарантия HA БД/LB/host. Вывод hook скрыт, чтобы не утекли секреты; отлаживайте его отдельно с безопасным выводом. + +## Нагрузка + +```sh +python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json +``` + +Это простой **closed-loop** генератор POST сообщений; он ограничен производительностью клиента и страдает coordinated omission. Он выдаёт successful RPS, ошибки и p50/p95/p99 **только успешных запросов**. Во время нагрузки нет прозрачных retry; timeout мог скрыть совершённую запись, поэтому это throughput HTTP-подтверждений, не точный счётчик COMMIT. Изменение размера истории входит в профиль. Для серьёзного исследования используйте k6/Locust/wrk либо свой обоснованный генератор, а не выводите максимальную пропускную способность из одного запуска этого скрипта. Для нагрузки pipeline изображений нужен отдельный сценарий студента. + +## HTTPS, lab7 + +```sh +make test BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt +make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt +``` + +Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. TLS-тест сначала проверяет рабочее доверенное соединение, затем намеренно пустой trust store и именно ошибку проверки сертификата; network timeout не засчитывается как правильный отказ. **Внутреннее mTLS, identity/authorization, OpenBao policy и hardening проверяют отдельные тесты студента** по trust matrix. Клиентский сертификат внешнему учебному REST-клиенту не требуется: mTLS находится на внутренних связях. + +## Что ещё остаётся доказать + +Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production. diff --git a/tests/client.py b/tests/client.py new file mode 100644 index 00000000..f0499a29 --- /dev/null +++ b/tests/client.py @@ -0,0 +1,217 @@ +"""HTTP helpers for public black-box tests; Python 3.9+, standard library only.""" +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import ssl +import time +import urllib.error +import urllib.request +import uuid + +ROOT = Path(__file__).resolve().parents[1] +LAB = json.loads((ROOT / 'lab.json').read_text())['number'] +SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text()) + +class Failure(AssertionError): + pass + +def check(condition, message): + if not condition: + raise Failure(message) + +def timestamp(value): + check(isinstance(value, str) and value.endswith('Z'), 'timestamp must be UTC ending in Z') + try: + return dt.datetime.fromisoformat(value[:-1] + '+00:00') + except ValueError as exc: + raise Failure('invalid RFC3339 timestamp') from exc + +def validate(value, schema, where='response'): + """Validate the JSON Schema subset used by the supplied contract, not arbitrary OpenAPI.""" + if '$ref' in schema: + target = SPEC + for part in schema['$ref'].split('/')[1:]: + target = target[part] + return validate(value, target, where) + kinds = schema.get('type', []) + if isinstance(kinds, str): + kinds = [kinds] + matches = {'null':value is None, 'boolean':isinstance(value,bool), 'integer':isinstance(value,int) and not isinstance(value,bool), 'number':isinstance(value,(int,float)) and not isinstance(value,bool), 'string':isinstance(value,str), 'array':isinstance(value,list), 'object':isinstance(value,dict)} + if kinds: + check(any(matches.get(k,False) for k in kinds), where + ': incorrect type') + if 'enum' in schema: + check(value in schema['enum'], where + ': invalid enum') + if 'const' in schema: + check(value == schema['const'], where + ': invalid const') + if isinstance(value,dict): + props = schema.get('properties',{}) + check(all(k in value for k in schema.get('required',[])), where + ': missing required fields') + if schema.get('additionalProperties') is False: + check(not set(value).difference(props), where + ': unexpected fields') + for key, sub in props.items(): + if key in value: + validate(value[key], sub, where + '.' + key) + if isinstance(value,list): + check(len(value) >= schema.get('minItems',0), where + ': too few items') + check(len(value) <= schema.get('maxItems',float('inf')), where + ': too many items') + if schema.get('uniqueItems'): + encoded = [json.dumps(x,sort_keys=True) for x in value] + check(len(encoded)==len(set(encoded)), where + ': duplicate items') + if 'items' in schema: + for item in value: + validate(item, schema['items'], where + '[]') + if isinstance(value,str): + check(len(value) >= schema.get('minLength',0), where + ': too short') + check(len(value) <= schema.get('maxLength',float('inf')), where + ': too long') + if 'pattern' in schema: + check(re.search(schema['pattern'], value) is not None, where + ': pattern mismatch') + if schema.get('format') == 'uuid': + try: + uuid.UUID(value) + except ValueError as exc: + raise Failure(where + ': invalid UUID') from exc + if schema.get('format') == 'date-time': + timestamp(value) + if isinstance(value,(int,float)) and not isinstance(value,bool): + check(value >= schema.get('minimum',-float('inf')), where + ': below minimum') + check(value <= schema.get('maximum',float('inf')), where + ': above maximum') + if 'anyOf' in schema: + for alternative in schema['anyOf']: + try: + validate(value, alternative, where) + break + except Failure: + pass + else: + raise Failure(where + ': no anyOf branch matches') + +def shape(value, name): + validate(value, SPEC['components']['schemas'][name]) + return value + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + +class Client: + def __init__(self, base_url=None, ca_file=None, timeout=10): + self.base = (base_url or os.environ.get('BASE_URL') or ('https://localhost:8443' if LAB==7 else 'http://localhost:8080')).rstrip('/') + check(self.base.startswith(('http://','https://')), 'BASE_URL must be HTTP(S)') + check(LAB != 7 or self.base.startswith('https://'), 'lab7 requires HTTPS') + self.timeout = timeout + context = ssl.create_default_context(cafile=ca_file or os.environ.get('CA_FILE') or None) + self.opener = urllib.request.build_opener(NoRedirect(), urllib.request.HTTPSHandler(context=context)) + + def call(self, method, path, expected=200, body=None, actor=None, headers=None, raw=None, schema=None): + h = {'Accept':'application/json'} + if actor: + h['X-User-Id' if LAB==1 else 'Authorization'] = actor['id'] if LAB==1 else 'Bearer ' + actor['token'] + if body is not None: + raw = json.dumps(body,ensure_ascii=False).encode('utf-8') + h['Content-Type'] = 'application/json' + h.update(headers or {}) + req = urllib.request.Request(self.base + path, data=raw, headers=h, method=method) + start = time.monotonic() + try: + response = self.opener.open(req, timeout=self.timeout) + except urllib.error.HTTPError as error: + response = error + except (urllib.error.URLError,TimeoutError,OSError) as exc: + # Do not print URL query, headers, request body, or credentials. + raise Failure(method + ' ' + path.split('?')[0] + ': connection/TLS failure (' + type(exc).__name__ + ')') from None + with response: + status = response.code + rh = response.headers + data = response.read(16*1024*1024 + 1) + check(len(data) <= 16*1024*1024, 'response exceeds test safety limit') + allowed = [expected] if isinstance(expected,int) else expected + check(status in allowed, method + ' ' + path.split('?')[0] + ': expected ' + str(allowed) + ', received ' + str(status)) + check(bool(rh.get('X-Request-Id')), 'missing X-Request-Id') + if LAB>=3: + check(bool(rh.get('X-Instance-Id')), 'missing X-Instance-Id') + payload = None + if schema or status>=400: + check(rh.get_content_type()=='application/json', 'expected application/json') + try: + payload = json.loads(data) + except (ValueError,UnicodeError): + raise Failure('invalid response JSON') from None + shape(payload, 'Error' if status>=400 else schema) + if status>=400: + check(payload['error']['request_id']==rh.get('X-Request-Id'),'error request_id differs from header') + if status==401 and LAB>=2: + scheme = 'Basic' if path=='/api/v1/auth/sessions' else 'Bearer' + check(rh.get('WWW-Authenticate','').lower().startswith(scheme.lower()), 'incorrect WWW-Authenticate challenge') + if status==204: + check(not data, '204 must not contain body') + return {'status':status,'headers':rh,'json':payload,'bytes':data,'elapsed':time.monotonic()-start} + + def user(self, label): + username = 'u_' + label + '_' + uuid.uuid4().hex[:12] + password = 'T3st-' + uuid.uuid4().hex + body = {'username':username,'display_name':'Студент ' + label} + if LAB>=2: + body['password'] = password + user = self.call('POST','/api/v1/users',201,body=body,schema='User')['json'] + check(user['username']==username,'username changed') + actor = {'id':user['id'],'user':user,'registration':body} + if LAB>=2: + credential = base64.b64encode((username+':'+password).encode()).decode() + session = self.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')['json'] + check(session['user']==user,'session user mismatch') + check(timestamp(session['expires_at']) > dt.datetime.now(dt.timezone.utc),'session already expired') + actor['token'] = session['token'] + return actor + + def bootstrap(self): + self.call('GET','/health/live',schema='Health') + self.call('GET','/health/ready',schema='Health') + alice, bob, eve = (self.user(label) for label in ('alice','bob','eve')) + chat = self.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Контрактный тест','member_ids':[alice['id'],bob['id']]},schema='Chat')['json'] + check(set(chat['member_ids'])=={alice['id'],bob['id']},'chat member mismatch') + return alice,bob,eve,chat + + def message(self, actor, chat, text, key=None, attachments=None): + body = {'text':text} + if attachments is not None: + body['attachment_ids'] = attachments + headers = {'Idempotency-Key':key or uuid.uuid4().hex} if LAB>=3 else {} + return self.call('POST','/api/v1/chats/'+chat['id']+'/messages',201,actor=actor,body=body,headers=headers,schema='Message') + + def attachment(self, actor, chat): + content = (ROOT / 'tests/fixtures/sample.png').read_bytes() + att = self.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png',201 if LAB==4 else 202,actor=actor,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')['json'] + check(att['status']==('ready' if LAB==4 else 'queued'),'incorrect upload status') + check(att['chat_id']==chat['id'] and att['owner_id']==actor['id'],'attachment ownership mismatch') + check(att['sha256']==hashlib.sha256(content).hexdigest() and att['size_bytes']==len(content),'original checksum/size mismatch') + return att,content + + def wait_ready(self, actor, att, wait_seconds=60): + deadline = time.monotonic()+wait_seconds + while time.monotonic()= 2, 'expected at least two API replicas') + targets = targets[:2] + summaries = [] + + for target in targets: + check(target in observe_instances(client, alice), + 'target replica is not observable before stop') + env = dict(os.environ) + env['TARGET_INSTANCE_ID'] = target + process = subprocess.Popen( + [str(action)], env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + started = time.monotonic() + first_recovery = None + reads = writes = failures = 0 + confirmed = [] + key = uuid.uuid4().hex + text = 'failover-each-' + target + '-' + key + + while time.monotonic() - started < args.window: + try: + if (reads + writes) % 2 == 0: + response = client.message(alice, chat, text, key=key) + confirmed.append(response['json']) + writes += 1 + key = uuid.uuid4().hex + text = 'failover-each-' + target + '-' + key + else: + client.call('GET', '/api/v1/users/me', actor=bob, schema='User') + reads += 1 + if process.poll() == 0 and first_recovery is None: + first_recovery = time.monotonic() - started + except Failure: + failures += 1 + time.sleep(0.05) + + check(process.wait(timeout=5) == 0, 'stop-one action failed') + elapsed = time.monotonic() - started + check(first_recovery is not None and first_recovery <= 10, + 'recovery exceeded 10 seconds') + history = message_history(client, bob, chat['id']) + history_ids = {message['id'] for message in history} + check(all(message['id'] in history_ids for message in confirmed), + 'confirmed message disappeared after failover') + + summaries.append({ + 'target_instance_id': target, + 'window_seconds': round(elapsed, 3), + 'successful_reads': reads, + 'successful_writes': writes, + 'failed_attempts': failures, + 'successful_rps': round((reads + writes) / elapsed, 3), + 'first_recovery_seconds': round(first_recovery, 3), + }) + + check(subprocess.run( + [str(restore)], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, timeout=100).returncode == 0, + 'restore action failed') + check(target in observe_instances(client, alice), + 'stopped replica did not return after restore') + + report = { + 'scenario': 'sequential failover of each API replica', + 'replicas': len(targets), + 'results': summaries, + } + output = json.dumps(report, ensure_ascii=False, indent=2) + if args.output: + destination = Path(args.output) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(output + '\n', encoding='utf-8') + print(output) + + +if __name__ == '__main__': + run(main) diff --git a/tests/idempotency_concurrent.py b/tests/idempotency_concurrent.py new file mode 100644 index 00000000..4ba04abd --- /dev/null +++ b/tests/idempotency_concurrent.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Prove that one idempotency scope is shared across API replicas.""" +from concurrent.futures import ThreadPoolExecutor +import uuid + +from client import Client, arguments, check, run + + +def main(): + args = arguments('Concurrent cross-replica idempotency check') + bootstrap = Client(args.base_url, args.ca_file, timeout=5) + alice, _, _, chat = bootstrap.bootstrap() + key = uuid.uuid4().hex + text = 'Один результат для всех реплик ' + key + path = '/api/v1/chats/' + chat['id'] + '/messages' + + def send(_): + client = Client(args.base_url, args.ca_file, timeout=10) + return client.call( + 'POST', + path, + 201, + actor=alice, + body={'text': text}, + headers={'Idempotency-Key': key}, + schema='Message') + + with ThreadPoolExecutor(max_workers=16) as pool: + responses = list(pool.map(send, range(32))) + + messages = [response['json'] for response in responses] + instances = { + response['headers']['X-Instance-Id'] for response in responses + } + check(all(message == messages[0] for message in messages), + 'same key returned different messages') + check(len(instances) >= 2, + 'requests did not exercise at least two API replicas') + + page = bootstrap.call( + 'GET', path + '?limit=100', actor=alice, schema='MessagePage')['json'] + matches = [item for item in page['items'] if item['id'] == messages[0]['id']] + check(len(matches) == 1, 'idempotent message is missing or duplicated') + print('PASS: 32 concurrent requests used ' + str(len(instances)) + + ' replicas and created one message') + + +if __name__ == '__main__': + run(main) diff --git a/tests/load.py b/tests/load.py new file mode 100644 index 00000000..ad81d596 --- /dev/null +++ b/tests/load.py @@ -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()=2,'persistence requires lab2+') + check(args.mode!='failover' or LAB>=3,'failover requires lab3+') + script = Path(args.action_script).expanduser().resolve() + check(script.is_file() and os.access(script,os.X_OK),'action script must exist and be executable (chmod +x)') + check('.example.' not in script.name,'copy and implement the example hook first') + c = Client(args.base_url,args.ca_file,timeout=2) + alice,bob,eve,chat = c.bootstrap() + sent = c.message(alice,chat,'Сохранить при отказе') + original = sent['json'] + target = sent['headers'].get('X-Instance-Id','') + attachment = content = None + if LAB>=4: + attachment,content = c.attachment(alice,chat) + if LAB>=5: + attachment = c.wait_ready(alice,attachment) + env = dict(os.environ) + env['TARGET_INSTANCE_ID'] = target + observed = set() + if args.mode=='failover': + for _ in range(40): + observed.add(c.call('GET','/api/v1/users/me',actor=alice,schema='User')['headers']['X-Instance-Id']) + check(len(observed)>=2,'less than two API instances observed before failure; verify LB/session affinity') + print('Executing explicit '+args.mode+' hook; hook output suppressed to avoid leaking secrets.') + # No shell interpolation and no Docker commands in this test. + proc = subprocess.Popen([str(script)],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + started = time.monotonic() + successes,failures,after_instances = [],0,[] + try: + if args.mode=='persistence': + try: + code = proc.wait(timeout=90) + except subprocess.TimeoutExpired: + raise Failure('restart hook exceeded 90 seconds') from None + check(code==0,'restart hook failed (inspect your script locally)') + deadline = time.monotonic()+90 + while True: + try: + c.call('GET','/health/ready',schema='Health') + c.call('GET','/api/v1/users/me',actor=alice,schema='User') + break + except Failure: + check(time.monotonic()=5,'too few successful writes after stop') + check(target not in after_instances[-5:],'target replica still serves requests; hook must leave it stopped') + duration = time.monotonic()-started + print(json.dumps({'observed_instances_before':len(observed),'successful_writes':len(successes),'failed_attempts':failures,'successful_rps':round(len(successes)/duration,3),'first_recovery_seconds':round(first_recovery,3)},ensure_ascii=False)) + # Existing token, no re-login. Read all confirmations and reject duplicates. + messages = history(c,bob,chat) + ids = [m['id'] for m in messages] + check(len(ids)==len(set(ids)),'duplicated message IDs in history') + check(any(m==original for m in messages),'confirmed pre-failure message lost or altered') + for msg in successes: + check(any(m==msg for m in messages),'confirmed in-flight message lost or altered') + # Bodies are unique in this scenario: an uncertain request may exist once, never twice. + texts = [m['text'] for m in messages] + check(len(texts)==len(set(texts)),'uncertain retry created duplicate message') + if attachment: + c.call('GET','/api/v1/attachments/'+attachment['id'],actor=bob,schema='Attachment') + downloaded = c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=bob) + check(downloaded['bytes']==content,'attachment lost or changed across failure') + print('PASS: '+args.mode+' preserved confirmed data and existing session. Hook scope needs operator evidence.') + finally: + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + +if __name__=='__main__': + run(main) diff --git a/tests/rolling_update.py b/tests/rolling_update.py new file mode 100644 index 00000000..b90d34ce --- /dev/null +++ b/tests/rolling_update.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Run closed-loop writes while API replicas are replaced one at a time.""" +from concurrent.futures import ThreadPoolExecutor +import json +import math +import os +from pathlib import Path +import subprocess +import threading +import time + +from client import Client, Failure, arguments, check, run + + +def main(): + def configure(parser): + parser.add_argument('--action-script', required=True) + parser.add_argument('--duration', type=float, default=180) + parser.add_argument('--concurrency', type=int, default=4) + parser.add_argument('--output', default=None) + args = arguments('Rolling replacement under write load', configure) + check(30 <= args.duration <= 300, 'duration must be 30..300 seconds') + check(1 <= args.concurrency <= 32, 'concurrency must be 1..32') + action = Path(args.action_script).expanduser().resolve() + check(action.is_file() and os.access(action, os.X_OK), + 'action script must be executable') + bootstrap = Client(args.base_url, args.ca_file, timeout=5) + alice, _, _, chat = bootstrap.bootstrap() + barrier = threading.Barrier(args.concurrency + 1) + + def worker(worker_id): + client = Client(args.base_url, args.ca_file, timeout=5) + barrier.wait() + deadline = time.monotonic() + args.duration + latencies = [] + errors = 0 + instances = set() + index = 0 + while time.monotonic() < deadline: + started = time.monotonic() + try: + response = client.message( + alice, chat, 'rolling-%s-%s' % (worker_id, index)) + latencies.append(time.monotonic() - started) + instances.add(response['headers']['X-Instance-Id']) + except Failure: + errors += 1 + index += 1 + return latencies, errors, instances + + started = time.monotonic() + with ThreadPoolExecutor(max_workers=args.concurrency) as pool: + futures = [pool.submit(worker, number) + for number in range(args.concurrency)] + barrier.wait() + time.sleep(3) + action_started = time.monotonic() + process = subprocess.run( + [str(action)], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, timeout=args.duration - 5) + action_seconds = time.monotonic() - action_started + check(process.returncode == 0, 'rolling action failed') + results = [future.result() for future in futures] + + elapsed = time.monotonic() - started + latencies = sorted(value for values, _, _ in results for value in values) + errors = sum(value for _, value, _ in results) + instances = set().union(*(value for _, _, value in results)) + total = len(latencies) + errors + + def percentile(fraction): + if not latencies: + return None + index = max(0, math.ceil(fraction * len(latencies)) - 1) + return round(1000 * latencies[index], 3) + + report = { + 'scenario': 'sequential API replacement under closed-loop writes', + 'requested_duration_seconds': args.duration, + 'elapsed_seconds': round(elapsed, 3), + 'rolling_action_seconds': round(action_seconds, 3), + 'concurrency': args.concurrency, + 'observed_instance_ids': sorted(instances), + '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': 'Closed-loop result on one host; success latency excludes failures.', + } + output = json.dumps(report, ensure_ascii=False, indent=2) + if args.output: + destination = Path(args.output) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(output + '\n', encoding='utf-8') + print(output) + check(bool(latencies), 'no successful writes') + check(len(instances) >= 3, + 'rolling replacement did not expose replacement instance IDs') + + +if __name__ == '__main__': + run(main) diff --git a/tests/smoke.py b/tests/smoke.py new file mode 100644 index 00000000..4cbfa558 --- /dev/null +++ b/tests/smoke.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""One complete public acceptance scenario, cumulative by lab number.""" +import base64 +import hashlib +import uuid +from client import Client, LAB, arguments, check, run, timestamp + + +def main(): + args = arguments('Messenger public smoke; creates synthetic users and messages') + c = Client(args.base_url,args.ca_file) + alice,bob,eve,chat = c.bootstrap() + path = '/api/v1/chats/'+chat['id'] + c.call('POST','/api/v1/users',409,body=alice['registration']) + c.call('GET','/api/v1/users/me',401) + c.call('GET',path,404,actor=eve) + me = c.call('GET','/api/v1/users/me',actor=alice,schema='User')['json'] + check(me==alice['user'],'current user mismatch') + listed = c.call('GET','/api/v1/chats?limit=100',actor=bob,schema='ChatPage')['json'] + check(any(x['id']==chat['id'] for x in listed['items']),'member cannot list chat') + hidden = c.call('GET','/api/v1/chats?limit=100',actor=eve,schema='ChatPage')['json'] + check(all(x['id']!=chat['id'] for x in hidden['items']),'chat leaks to outsider') + key = uuid.uuid4().hex + first = c.message(alice,chat,'Привет, мир 👋',key=key)['json'] + second = c.message(bob,chat,'Сообщение Боба')['json'] + check(first['sender_id']==alice['id'] and second['sender_id']==bob['id'],'sender was not derived from actor') + check(first['chat_id']==second['chat_id']==chat['id'],'wrong chat in message') + check(first['text']=='Привет, мир 👋' and second['text']=='Сообщение Боба','message text changed') + page1 = c.call('GET',path+'/messages?limit=1',actor=bob,schema='MessagePage')['json'] + check(len(page1['items'])==1 and page1['next_cursor'],'first page must have one item and cursor') + from urllib.parse import quote + page2 = c.call('GET',path+'/messages?limit=1&cursor='+quote(page1['next_cursor'],safe=''),actor=alice,schema='MessagePage')['json'] + check(len(page2['items'])==1 and page2['next_cursor'] is None,'second page must finish history') + ordered = sorted([first,second],key=lambda x:(timestamp(x['created_at']),uuid.UUID(x['id']).int)) + check(page1['items']+page2['items']==ordered,'pagination lost, duplicated or reordered a message') + h = {'Idempotency-Key':uuid.uuid4().hex} if LAB>=3 else {} + c.call('POST',path+'/messages',400,actor=alice,body={'text':''},headers=h) + c.call('POST',path+'/messages',404,actor=eve,body={'text':'чужое'},headers=h) + c.call('GET',path+'/messages?limit=0',400,actor=alice) + if LAB>=2: + bad = base64.b64encode((alice['registration']['username']+':wrong-password').encode()).decode() + c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':'Basic '+bad}) + good = base64.b64encode((alice['registration']['username']+':'+alice['registration']['password']).encode()).decode() + c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Basic '+good}) + c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':alice['id']}) + me = c.call('GET','/api/v1/users/me',actor=alice,headers={'X-User-Id':eve['id']},schema='User')['json'] + check(me['id']==alice['id'],'X-User-Id overrode bearer identity') + if LAB>=3: + replay = c.message(alice,chat,first['text'],key=key)['json'] + check(replay==first,'idempotency replay differs') + c.call('POST',path+'/messages',409,actor=alice,body={'text':'другой body'},headers={'Idempotency-Key':key}) + c.call('POST',path+'/messages',400,actor=alice,body={'text':'без ключа'}) + if LAB>=4: + att,content = c.attachment(alice,chat) + # A queued attachment must already be linkable to its own chat. + attached = c.message(alice,chat,'',attachments=[att['id']])['json'] + check(attached['attachment_ids']==[att['id']],'message lost attachment') + ready = c.wait_ready(bob,att) if LAB>=5 else att + check(ready['error_code'] is None,'ready attachment has an error') + download = c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob) + check(download['bytes']==content,'download differs from original') + check(download['headers'].get_content_type()=='image/png','original content type mismatch') + for suffix in ('','/content'): + c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=eve) + if LAB>=5: + variants = [x for x in ready['variants'] if x['name']=='thumbnail'] + check(len(variants)==1,'expected exactly one thumbnail') + v = variants[0] + check((v['width'],v['height'])==(256,160),'thumbnail metadata has wrong dimensions') + thumb = c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',actor=bob) + check(thumb['headers'].get_content_type()=='image/jpeg','thumbnail content type mismatch') + check(len(thumb['bytes'])==v['size_bytes'] and hashlib.sha256(thumb['bytes']).hexdigest()==v['sha256'],'thumbnail checksum mismatch') + from image_probe import jpeg_size + check(jpeg_size(thumb['bytes'])==(256,160),'actual JPEG dimensions mismatch') + if LAB>=2: + c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice) + c.call('GET','/api/v1/users/me',401,actor=alice) + c.call('DELETE','/api/v1/auth/sessions/current',401,actor=alice) + print('PASS: lab%d public API scenario; infrastructure and grading evidence remain separate.' % LAB) + +if __name__=='__main__': + run(main)