commit a9af58a083f6bf7b3cbc95ee2e8125b11003b834 Author: papapevagemabody Date: Fri Nov 6 13:57:17 2026 +0300 lab4 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..40d419e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +* +!Dockerfile +!requirements.txt +!src/ +!src/** +!migrations/ +!migrations/** +!research/ +!research/** +**/__pycache__/ +**/*.py[cod] diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e441d33 --- /dev/null +++ b/.env.example @@ -0,0 +1,22 @@ +# Copy to .env for your LOCAL synthetic test environment; never commit .env. +# These are logical interface suggestions; map actual framework names in REPORT.md. +APP_HOST=0.0.0.0 +APP_PORT=8080 +APP_ENV=lab +HOST_PORT=8080 +SESSION_TTL_SECONDS=3600 +# Choose credentials locally. File paths contain no secret values. +DATABASE_URL_FILE=/run/secrets/database_url +# Shared sessions carried over from lab3 use Valkey. +SESSION_STORE=valkey +CACHE_URL_FILE=/run/secrets/cache_url +API_REPLICAS=2 +IDEMPOTENCY_TTL_SECONDS=86400 +S3_ENDPOINT=http://s3:9000 +S3_REGION=us-east-1 +S3_BUCKET=messenger-attachments +S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id +S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key +MAX_UPLOAD_BYTES=10485760 +MAX_IMAGE_PIXELS=40000000 +UPLOAD_CLEANUP_GRACE_SECONDS=3600 diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..1bec547 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,18 @@ +## Лабораторная 4 + +Автор / группа: TODO +Целевая оценка (3/4/5): TODO +Трек 5, если заявлен: TODO + +Что реализовано и что перенесено: TODO +Команды запуска из чистого clone: TODO +Результаты проверок и ссылка на REPORT.md: TODO +Ограничения / известные ошибки: TODO +Источники и использование ИИ: TODO + +- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. +- [ ] Контракт и публичные тесты не ослаблены. +- [ ] make check и make test выполнены; приложен реальный вывод. +- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. +- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. +- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. diff --git a/.github/workflows/application.yml b/.github/workflows/application.yml new file mode 100644 index 0000000..4527c4a --- /dev/null +++ b/.github/workflows/application.yml @@ -0,0 +1,24 @@ +name: Application +on: [push, pull_request] +permissions: + contents: read + +jobs: + docker: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - run: python -m venv .venv + - run: .venv/bin/python -m pip install -r requirements.txt + - run: ./scripts/check-docker.sh + - uses: actions/upload-artifact@v4 + if: always() + with: + name: lab4-evidence + path: | + evidence/lab4-checks.txt + evidence/lab4-checks.json diff --git a/.github/workflows/contracts.yml b/.github/workflows/contracts.yml new file mode 100644 index 0000000..11cf289 --- /dev/null +++ b/.github/workflows/contracts.yml @@ -0,0 +1,16 @@ +name: Skeleton contracts +on: [push, pull_request] +permissions: + contents: read +jobs: + contracts: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -r requirements-dev.txt + - run: make check validate PYTHON=python +# This job validates the skeleton, not a student solution. +# Add build, readiness and make test in a separate application job. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b5a7189 --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +# Local/private state +.env +.env.* +!.env.example +secrets/ +certs/private/ +*.key +*.p12 +*.pfx +*.jks +*.pem +*.tfstate* +volumes/ +data/ +backups/ +# Runtime/build artifacts +.venv/ +__pycache__/ +*.py[cod] +node_modules/ +dist/ +build/ +target/ +bin/ +obj/ +coverage/ +*.log +.DS_Store +.idea/ +.vscode/ +# Keep small, sanitized evidence summaries in evidence/ under version control. +# Inspect git diff --cached: ignore rules are not a secret scanner. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..ee5533d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# Работа через fork и pull request + +1. После публикации преподавателем сделайте fork репозитория **текущей** лабораторной в своём аккаунте и clone своего fork. URL преподаватель выдаёт отдельно. +2. Создайте ветку `solution/-` от исходной ветки skeleton. Ветка преподавателя и файлы контракта остаются основой проверки. +3. Для lab2–7 перенесите из своей предыдущей лабы только исходники, миграции, собственные тесты, Dockerfile и нужные конфигурации. Не копируйте `.git`, `.env`, credentials, volumes, `README.md`, `COURSE.md`, публичные `tests/` и `contracts/` поверх новой версии. Сначала сравните изменения API в `COURSE.md`. +4. Реализуйте задание, добавьте свою инструкцию запуска и заполните `REPORT.md`. Публичные проверки дополняйте отдельными тестами, не ослабляйте assertions. +5. Выполните `make check`, запустите свой стенд, затем `make test`. Выполните сценарии отказов текущей лабы. Их запуск всегда явный: scaffold сам не останавливает контейнеры. +6. Commit и push делайте в свой fork. Откройте PR в исходный репозиторий преподавателя, заголовок: `ЛР N — Группа — Фамилия — на 3/4/5`. Выберите правильную базовую ветку и заполните шаблон. +7. После замечаний обновляйте тот же PR. Чужие решения не переносите без указания источника и согласованных правил курса. + +Платформа может называть PR «merge request» — процесс тот же. `.github/` содержит необязательные удобства для GitHub; проверки локально от платформы не зависят. Инициализация и публикация исходных Git-репозиториев выполняются преподавателем отдельно. + +## Правила изменения skeleton + +Не удаляйте обязательные endpoint, поля, рубрику и публичные проверки. Изменение контракта согласуйте отдельным комментарием/PR; обход тестов не является решением. Код приложения размещайте в `src/` либо в принятой для языка структуре. Собственные тесты — `student-tests/` или штатный каталог фреймворка. Ссылки на результаты проверки и команды запуска должны переживать clone на другой машине. + +## CI + +Готовый GitHub workflow проверяет целостность контракта и синтаксис Python-проверок. Он **не запускает отсутствующее приложение** и **не подтверждает оценку**. Студент добавляет сборку своего приложения, запуск/готовность стенда и `make test` в отдельный job. Не используйте `pull_request_target` для запуска кода из fork, не выдавайте CI секреты или доступ к общему Docker-host. diff --git a/COURSE.md b/COURSE.md new file mode 100644 index 0000000..b02172b --- /dev/null +++ b/COURSE.md @@ -0,0 +1,53 @@ +# Сквозной проект: мессенджер под нагрузкой + +Семь самостоятельных репозиториев содержат задания и проверяемые контракты одной системы. Вы переносите собственную реализацию между лабораторными. Язык, фреймворк и библиотеки выбираете сами. Web UI, WebSocket, редактирование/удаление сообщений, публичный поиск пользователей и Kubernetes не входят в обязательный минимум: достаточно REST API. + +| Лаба | Новая инженерная задача | Что появляется в системе | +| --- | --- | --- | +| 1 | Контракт, процессы и контейнер | In-memory API, Dockerfile, HTTP smoke | +| 2 | Сохранность и идентификация | PostgreSQL, Basic → сессия; Redis/Valkey на 4 | +| 3 | Горизонтальное масштабирование | Балансировщик, ≥2 API-реплики, общие сессии, идемпотентность | +| 4 | Бинарные данные | Приватное S3-совместимое хранилище и вложения | +| 5 | Фоновая работа | Брокер, worker, состояния вложений и преобразование изображений | +| 6 | Диагностика | OTel Collector, хранилища сигналов, Grafana | +| 7 | Защита и эксплуатация | Argon2id, TLS/mTLS, OpenBao, минимальные привилегии | + +## Как оценивать + +Оценки накопительные **внутри лабораторной**: 4 = весь уровень 3 + весь уровень 4; 5 = весь уровень 4 + **один** полностью выполненный трек 5 на выбор. Несколько недоделанных треков не заменяют один завершённый. Условие «весь уровень» включает реализацию, проверку и объяснение на защите. Красивые схемы и дополнительные технологии не компенсируют неработающий обязательный сценарий. + +Для начала следующей лабы достаточно обязательного минимума предыдущей. Сохраняются предыдущие обязательные возможности, с явно описанными переходами API ниже. Не требуется сначала получить 5 за все ранние лабы. Можно исправлять свою базу по ходу курса; такие исправления выделяйте в PR. Реализация на 3 работоспособна, но не претендует на промышленную готовность. Даже 5 в lab7 — учебная доказанная защита в заявленной модели угроз, а не сертификат полной безопасности. + +На 3 студент самостоятельно собирает рабочую систему. На 4 показывает практики, ожидаемые от стажёра/джуна в команде: воспроизводимость, диагностику, обработку ошибок и проверки отказов. На 5 формулирует гипотезу, ставит эксперимент, приводит измерения и обсуждает границы решения — это предмет конкретной похвалы магистранту. + +## Контракт и совместимость + +`contracts/openapi.json` — OpenAPI 3.1.0, `contracts/README.md` — нормативная семантика. Контракт каждого репозитория самодостаточен; соседние папки на машине преподавателя не нужны. `tests/` — публичные проверки, а не эталонное решение. Контракт, рубрика и публичные тесты имеют приоритет над случайным поведением библиотек. При противоречии создайте вопрос преподавателю; не подгоняйте тест под приложение. + +Три объявленных изменения обязательного API: + +1. **1 → 2:** регистрация требует `password`; `X-User-Id` заменяется Bearer. Basic используется только при создании сессии. +2. **2 → 3:** `Idempotency-Key` обязателен для отправки сообщения; ответы API содержат `X-Instance-Id`. +3. **4 → 5:** загрузка вложения возвращает `202` вместо `201`, состояние становится асинхронным. Клиент опрашивает метаданные. Старое текстовое сообщение остаётся валидным: `attachment_ids` по умолчанию `[]`. + +У lab7 меняется транспорт на HTTPS, бизнес-эндпоинты остаются прежними. Внутреннее mTLS не заменяет пользовательскую сессию. Новые возможности на 4/5 добавляйте обратно совместимо, в отдельном `contracts/extensions.openapi.json` или документе; обязательный контракт сохраняйте. + +## Общая предметная модель + +Пользователь (`username`, `display_name`) состоит в чатах. Список участников задаётся при создании чата и в обязательном API не изменяется. В чате отправляются сообщения, с lab4 — со ссылками на вложения этого чата. Сервер назначает UUID и время. Порядок истории — `(created_at, id)` по возрастанию. Для защиты достаточно показать взаимодействие нескольких API-клиентов; фронтенд не требуется. + +С lab2 данные PostgreSQL — источник истины. Сессии могут храниться в PostgreSQL или Redis/Valkey, если выполняют контракт срока жизни и перезапуска. Файлы с lab4 живут в S3, метаданные — в PostgreSQL. Redis и Valkey — альтернативы: оба одновременно не нужны. Аналогично выбирается одно S3-хранилище, один брокер и один основной путь оркестрации. + +## Воспроизводимость и честные измерения + +- Укажите версии runtime и контейнерных образов, аппаратную конфигурацию, CPU/RAM-лимиты, команду запуска и время прогрева. Для образов используйте явный тег версии или digest, не `latest`. +- Все тестовые пользователи и изображения синтетические. `make test` создаёт данные: запускайте его на учебном стенде. Не публикуйте пароли, токены, приватные ключи, персональные данные или подписанные URL. +- Минимальный отчёт о нагрузке: длительность, конкуренция/интенсивность, успешные RPS, доля ошибок, p50/p95/p99, CPU/RAM, размер набора данных. Универсального проходного RPS для разных ноутбуков нет. +- Сравнивайте одинаковые запросы при одинаковых ресурсах. Успешный `/health/live` не доказывает сохранность сообщений, а HTTP `202` — окончание обработки. +- Один Docker-host не обеспечивает отказоустойчивость к потере этого host. Несколько API-процессов не делают единственную БД или LB высокодоступными. Отдельно называйте, какие отказы выдерживает эксперимент. + +## Что сдавать + +Исходники, Dockerfile, нужные манифесты и конфигурации, миграции, собственные тесты, заполненный `REPORT.md`, сведения об использовании внешнего кода и ИИ. Уметь объяснить и изменить своё решение на защите обязательно. Приложите команды и текстовые результаты; скриншоты — дополнение, а не единственное доказательство. + +PR должен собираться из чистого clone по инструкции автора. Секреты создаются отдельно; тестовые fixtures и открытые конфигурации хранятся в репозитории. Перенос кода между лабами описан в [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..64af548 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,28 @@ +FROM python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3 + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + APP_HOST=0.0.0.0 \ + APP_PORT=8080 + +WORKDIR /app + +COPY requirements.txt . +RUN python -m pip install --no-cache-dir -r requirements.txt \ + && python -m pip check + +RUN groupadd --gid 10001 app \ + && useradd --uid 10001 --gid app --no-create-home app + +COPY src/ ./src/ +COPY migrations/ ./migrations/ +COPY research/ ./research/ + +USER 10001:10001 +EXPOSE 8080 +STOPSIGNAL SIGTERM + +HEALTHCHECK --interval=2s --timeout=3s --start-period=5s --retries=3 \ + CMD ["python", "-m", "src.healthcheck"] + +CMD ["python", "-m", "src"] diff --git a/Dockerfile.example b/Dockerfile.example new file mode 100644 index 0000000..e333a12 --- /dev/null +++ b/Dockerfile.example @@ -0,0 +1,8 @@ +# Teaching outline, not a runnable Dockerfile. Implement your own Dockerfile. +# 1. Choose a runtime/toolchain version and pin the base image tag/digest. +# 2. Copy dependency manifests first; install from the language lockfile. +# 3. Copy source and build. For compiled languages use a separate runtime stage. +# 4. Run the HTTP process as PID 1; listen on 0.0.0.0:8080. +# 5. Add non-root, signals and healthcheck according to the current rubric. +# 6. Pass runtime config/secrets at startup, never COPY .env or secret files. +# This file deliberately has no FROM/CMD: selecting/implementing them is the task. diff --git a/MAINTAINERS.md b/MAINTAINERS.md new file mode 100644 index 0000000..bb10fed --- /dev/null +++ b/MAINTAINERS.md @@ -0,0 +1,38 @@ +# Памятка преподавателю — лабораторная 4 + +## Что подготовлено + +Язык реализации не задан. README содержит накопительные уровни 3/4/5, сценарий защиты и вопросы. В каждой лабе собственная полная версия OpenAPI, поэтому fork не зависит от соседних каталогов. Публичный HTTP smoke не содержит реализации сервера; Dockerfile.example и compose.example.yaml (если есть) — задания/ориентиры, не готовый deployment. + +## Перед публикацией + +1. Выберите GitHub/GitLab и организацию, опубликуйте каждый каталог как отдельный template/skeleton repository, сообщите студентам URL и правила именования PR/MR. Эти материалы не публикуют репозитории автоматически. +2. Задайте default branch, защиту исходных материалов и правила приёма. `.github/` уже содержит шаблон PR и CI контракта; в GitLab перенесите эквивалентные настройки, локальные Makefile-команды одинаковы. +3. Сообщите, индивидуальная работа или командная, сроки, правила использования стороннего кода/ИИ и ресурсы демонстрационного стенда. Эти организационные решения намеренно не выдуманы в задании. +4. Уточните ограничения площадки (например доступна ли виртуализация/несколько узлов). Для 5 предусмотрено по два трека: один можно выполнить без настоящего multi-node cloud. Универсальный проходной RPS не установлен. + +## Что проверять + +| Проверка | Что подтверждает | Чего не подтверждает | +| --- | --- | --- | +| make check | Структура файлов, JSON, локальные refs, синтаксис Python | Реализация/запуск API | +| make validate | Полная OpenAPI 3.1, JSON Schema и примеры | Поведение сервера | +| make test | Один сквозной контрактный сценарий текущей лабы | Все ошибки, persistence, HA, security | +| test-persistence (lab2+) | Данные/прежний токен после вызова restart hook | Реальный перезапуск, если hook — no-op | +| test-failover (lab3+) | Смена обслуживающей реплики, сохранность, retry без дубля | Несколько физических узлов, HA DB/LB | +| test-security (lab7) | Доверенный HTTPS и отказ недоверенного CA | Внутреннее mTLS/identity/ACL/OpenBao | +| Защита и тесты студента | Реальность инфраструктуры и критерии выбранного уровня | Неограниченная промышленная безопасность | + +Проверяйте реальные контейнеры/логи процессов и данные до/после отказа: одного X-Instance-Id недостаточно. Для 4 требуются все пункты 3+4, для 5 — все пункты 3+4 и один **завершённый** трек 5. Сравнивайте подтверждённые результаты со сформулированными критериями, а не количество установленных сервисов. + +## Приём PR + +Проверка запускается на изолированном учебном окружении с синтетическими secrets, не на общей production БД. Студенческие Dockerfile/hooks/CI — выполняемый код: обычный fork workflow без секретов и без доступа к общему Docker socket. Не запускайте PR через pull_request_target с привилегиями преподавателя. + +Исходные README/контракт/публичные tests сохраняются, реализация переносится студентом между лабами через собственные исходники и миграции. Исправление общей спецификации публикуйте отдельным изменением, объясняя влияние на все затронутые лабораторные. + +## Проверка этой версии skeleton + +На 2026-09-10 выполнены структурные проверки и полная валидация всех семи OpenAPI/JSON Schema, проверка локальных Markdown-ссылок/YAML и декодирование PNG fixture. HTTP-клиенты проверены на временном изолированном тестовом стенде: позитивный smoke 1–7, отрицательные варианты неправильного sender, pagination, ACL, logout, bytes и пустого API; также пути persistence/failover/load и внешнего TLS. + +Временный стенд не включён в студенческие каталоги и не является эталонным решением. Реальное приложение, Compose, PostgreSQL/S3/broker и mTLS/OpenBao в skeleton отсутствуют: их работоспособность не заявляется. Docker CLI в среде подготовки не был доступен. Это проверка материалов и тестовых драйверов, не приёмка будущих решений студентов. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5d86d17 --- /dev/null +++ b/Makefile @@ -0,0 +1,30 @@ +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 load test-persistence test-failover + +help: + @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + +check: + $(PYTHON) scripts/check_contract.py + +validate: + $(PYTHON) scripts/validate_openapi.py + +test: + $(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +load: + $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-persistence: + @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) + $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-failover: + @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) + $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) diff --git a/README.md b/README.md new file mode 100644 index 0000000..947094c --- /dev/null +++ b/README.md @@ -0,0 +1,105 @@ +# Лабораторная 4. S3-хранилище и вложения + +Разделить метаданные и бинарное содержимое, добавить изображения в сообщения и сохранить доступ к ним при переключении 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) + +## Откуда начинаем + +Перенесите минимум lab3. Дополняются поля сообщения и endpoint вложений; прежние текстовые POST остаются валидными. + +**Архитектура:** Клиент → LB → API × 2+ → PostgreSQL (метаданные) + приватное S3-хранилище (байты). + +## Что сделать + +1. Выберите один S3-совместимый сервер: MinIO, SeaweedFS или RustFS. Закрепите проверенную версию образа и опишите создание приватного bucket. +2. Спроектируйте Attachment и связь с чатом/сообщением. S3 object key назначает сервер, filename используется только для отображения. +3. Реализуйте синхронный binary upload PNG/JPEG с ограничениями, сохранение метаданных и авторизованный download через API. +4. Включите S3 и persistent volumes в общий Compose/Swarm. Проверьте, что другая API-реплика скачивает файл после остановки загрузившей. +5. Проверьте недоступность S3, чужой чат и restart всего стенда. + +## Оценка «3»: работающий минимум + +- Все обязательные возможности lab3 сохранены. S3-сервер находится в общем стенде; метаданные вложений живут в PostgreSQL, байты — в приватном bucket, не в БД или локальном каталоге API. +- POST вложения возвращает 201 ready после сохранения; оригинал скачивается побайтно. Message с attachment_ids читается участниками чата. Публичный smoke проверяет checksum и отсутствие доступа у постороннего. +- Принимаются реальные PNG/JPEG ≤10 MiB и ≤40 млн пикселей; MIME проверяется по содержимому, опасные filename отклоняются, лимиты применяются до неограниченного чтения/декодирования. +- Upload → остановка обслужившей API-реплики → download через другую возвращает тот же файл. Restart с сохранением volumes сохраняет метаданные и оригинал. + +## Оценка «4»: уровень стажёра/джуна + +Весь уровень 3 **и все** пункты ниже: + +- Тесты покрывают слишком большой файл, повреждённое изображение, подмену MIME, чужое attachment_id и привязку файла другого чата. Пользовательская ошибка не превращается в 500. +- Прерывание загрузки и отказ между записью S3/БД не оставляют вечных неучтённых объектов: есть документированный механизм компенсации/сверки/очистки с безопасным grace period. +- Лимиты/таймауты и потоковая обработка не позволяют одной загрузке занять неограниченную RAM. Проведён эксперимент ≥10 одновременных загрузок с измерением пика памяти. +- Bucket bootstrap идемпотентен; API использует отдельные S3 credentials с ограниченными правами. Административная консоль не открыта в общей сети. Есть проверка private bucket вне API. + +## Оценка «5»: исследование и доказанный результат + +Весь уровень 4 **и один законченный трек на выбор**. Приведите гипотезу, повторяемую методику, результаты и ограничения. + +**Трек 1. Прямой upload.** Добавьте отдельный безопасный presigned-upload flow: короткая подпись, уникальный ключ, проверка принадлежности, размера/checksum при complete, обработка незавершённой загрузки. Сохраните обязательный proxy endpoint. Сравните трафик и RAM API при ≥2 размерах файлов, покажите негативные сценарии. + +**Трек 2. Согласованность двух хранилищ.** Разработайте повторяемый reconciler для orphan/missing объектов и метаданных. Внедрите ошибки на обеих сторонах, покажите обнаружение и безопасное исправление с dry-run/повторным запуском. Докажите, что свежие и используемые вложения не удаляются; измерьте стоимость обхода. + +## Как начать и проверить + +```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. Загрузить fixture, отправить message с attachment_ids, скачать как второй участник и сравнить SHA-256. +2. С третьим пользователем получить 404 для метаданных и bytes; direct unauthenticated S3 GET не отдаёт объект. +3. Выполнить persistence и failover: общий тест начиная с lab4 сохраняет и повторно читает оригинал через API. +4. Показать, что на API нет обязательного локального файла оригинала. Для 4/5 — отказы и эксперименты. + +## Что должно быть в PR + +Дополненный стенд, настройка bucket/политики, миграции Attachment, тесты файлов, описание согласованности БД/S3 и результаты. + +Заполните `REPORT.md` и [шаблон PR](.github/pull_request_template.md), укажите целевую оценку/трек. Не меняйте обязательный контракт и публичные tests ради зелёного результата. Сохраняйте возможности предыдущих лабораторных в пределах [объявленных переходов](COURSE.md). + +## Вопросы на защите + +- Почему файл в Docker volume одной API-реплики не равен объектному хранилищу? +- Когда можно честно вернуть 201? +- Что произойдёт, если S3 PUT прошёл, а COMMIT в PostgreSQL — нет? +- Почему случайный object key и приватный bucket не заменяют ACL приложения? + +## Первичные материалы + +- [S3 object uploads](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html) +- [Presigned URLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html) +- [MinIO](https://github.com/minio/minio) +- [SeaweedFS](https://github.com/seaweedfs/seaweedfs) +- [RustFS](https://docs.rustfs.com/) diff --git a/REPORT.md b/REPORT.md new file mode 100644 index 0000000..78abc40 --- /dev/null +++ b/REPORT.md @@ -0,0 +1,218 @@ +# Отчёт — лабораторная 4 + +- Автор, группа: Боцоев Арсен, БВТ2303. +- Целевая оценка: **4** — все требования уровней 3 и 4. Исследовательские треки оценки 5 не заявлены. +- Стенд: Docker Compose, HAProxy, две реплики FastAPI, PostgreSQL, Valkey, SeaweedFS с приватным S3 bucket. +- Commit/PR: после публикации. В этой копии нет git-репозитория, поэтому evidence/lab4-checks.json содержит source_commit=null и working_tree=null. +- Источники и помощь: официальные материалы перечислены в конце; код и проверки подготовлены с помощью Codex, результаты получены запуском Docker-стенда. + +## Запуск из чистого clone + +Нужны Docker Engine с Compose v2, Python 3.11, Bash и make; для demo.sh — curl и jq. Проверенная среда записана в evidence/lab4-checks.json. Все команды выполняются из корня этого репозитория, внешние установленные БД или S3 не нужны. + +```sh +python3 -m venv .venv +.venv/bin/python -m pip install -r requirements.txt -r requirements-dev.txt +make check validate PYTHON=.venv/bin/python +./scripts/start.sh +./scripts/check.sh +``` + +Адрес API: http://localhost:8080. start.sh генерирует локальные .env и secrets/, собирает образ, поднимает хранилища, выполняет миграции и bootstrap bucket, запускает API, LB и cleaner. Возврат из скрипта означает готовность обеих API-реплик через LB. Существующие пароли и настройки не перезаписываются. Локальный IAM-конфиг S3 собирается из тех же secret-файлов. Каталог secrets имеет права 0700; файлы 0444 позволяют UID 10001 контейнера читать смонтированные Docker secrets. .env, secrets и .venv игнорируются Git; Docker build context содержит только необходимые исходники. + +Если 8080 занят другим стендом, сохраните HOST_PORT=8081 в .env и используйте BASE_URL=http://localhost:8081 для HTTP-проверок. Либо передайте HOST_PORT=8081 в окружении start.sh. Compose project mtusi-lab4 и его volumes отделены от lab3. + +```sh +docker compose ps -a +./scripts/demo.sh +./scripts/restart.sh # перезапуск всех постоянных процессов; volumes сохраняются +./scripts/stop.sh # удаление контейнеров/сетей; volumes сохраняются +./scripts/start.sh # повторный запуск с прежними данными + +# Только для намеренного удаления учебных данных текущего Compose project: +docker compose down --volumes +``` + +Закреплены Python 3.11.15-slim-bookworm с digest в Dockerfile, PostgreSQL 17.6-bookworm, Valkey 8.1.3, HAProxy 3.2.6-alpine, SeaweedFS 3.85 с digest sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a. Версии Python-библиотек зафиксированы в requirements.txt; добавлены MinIO Python SDK 7.2.20 и Pillow 13.0.0. SDK работает с S3 API SeaweedFS; сервер MinIO не требуется. + +## Архитектура и перенос из lab3 + +```text +Клиент → HAProxy :8080 → API × 2 → PostgreSQL (метаданные, сообщения, идемпотентность) + → Valkey (серверные Bearer-сессии) + → S3 gateway :9000 → SeaweedFS storage → s3_data +Одноразовые migrate → PostgreSQL; s3-bootstrap → приватный bucket +Постоянный cleanup → журнал PostgreSQL + DELETE незавершённых объектов S3 +``` + +Из lab3 сохранены пользователи, Argon2id, Basic-вход и Bearer-сессии, ACL чатов, текстовые сообщения, keyset-пагинация, X-Request-Id/X-Instance-Id, общая идемпотентность, миграции, LB, ограничения ресурсов и скрипты отказа/замены реплик. Предыдущие отчёты — REPORT.lab2.md и REPORT.lab3.md. Актуальные доказательства этой работы — evidence/lab4-checks.json, evidence/lab4-checks.txt и evidence/postgres-pause.json. + +Добавлена миграция 003: attachments, message_attachments, attachment_uploads и request_attachment_ids в таблице идемпотентности. Миграции 001/002 не изменены. Старые сообщения читаются с attachment_ids=[]. Новый POST сообщения принимает до 10 уникальных attachment_ids; чужой/неизвестный ID или ID другого чата даёт 404. Весь список проверяется до вставки сообщения в одной транзакции. Пустой/пробельный text допустим только при наличии вложений. Любой участник может использовать вложение своего чата. Порядок списка сохраняется; при повторе ключа сравниваются text и список UUID. Пропущенный список и [] равнозначны. + +Бинарного содержимого в PostgreSQL нет. Случайный object_key вида attachments/ назначает сервер; filename используется только для отображения и Content-Disposition. В API нет endpoint удаления/изменения вложения. Ready-метаданные и связи сообщений постоянны, локальный файл API для чтения оригинала не нужен. Детали FK, индексов и транзакций — в docs/schema.md. + +| Настройка .env.example | Реальное использование | +| --- | --- | +| APP_HOST, APP_PORT | 0.0.0.0:8080 внутри API | +| HOST_PORT | Публичный порт LB на 127.0.0.1 | +| APP_ENV | Учебная метка, не переключает поведение | +| SESSION_STORE, SESSION_TTL_SECONDS | Valkey; TTL сессии, по умолчанию 3600 s | +| DATABASE_URL_FILE, CACHE_URL_FILE | Пути Docker secrets PostgreSQL и Valkey | +| API_REPLICAS | Две реплики по умолчанию; LB рассчитан на 10 | +| IDEMPOTENCY_TTL_SECONDS | Не меньше 86400 s; одинаковый ответ при повторе | +| S3_ENDPOINT, S3_REGION, S3_BUCKET | http://s3:9000, us-east-1, messenger-attachments | +| S3_ACCESS_KEY_ID_FILE, S3_SECRET_ACCESS_KEY_FILE | Только ограниченные credentials приложения | +| MAX_UPLOAD_BYTES, MAX_IMAGE_PIXELS | 10485760 bytes, 40000000 pixels; повышение выше контракта запрещено | +| UPLOAD_CLEANUP_GRACE_SECONDS | 3600 s, минимум 60 s; защита свежих/незавершённых загрузок | + +## Приватный bucket и bootstrap + +Выбран один S3-совместимый сервер — SeaweedFS. Два сервиса одного продукта разделяют его S3 gateway и внутренние master/volume/filer. s3-storage и его административные HTTP/gRPC-интерфейсы находятся только в закрытой сети s3-internal; API к ней не подключены. Только S3 gateway соединяет эту сеть с сетью приложения. Наружу опубликован лишь LB: ни 9000, ни UI, ни внутренние API-порты не опубликованы. + +init_local.py создаёт отдельные случайные root и application credentials. S3 загружает статическую IAM-конфигурацию из secret s3_config, без anonymous identity. Администратор используется только одноразовым s3-bootstrap; тот проверяет наличие bucket и создаёт его при отсутствии. Повторный bootstrap сохраняет bucket и объекты. Root secrets/IAM-файл не монтируются в API или cleaner. + +Приложению разрешены Read и List только своего bucket и Write только prefix attachments/*. В терминах SeaweedFS Write включает PUT/DELETE объектов; административных действий и записи вне prefix нет. Тест напрямую, вне API приложения, проверяет anonymous GET=403, запрет создания другого bucket и записи вне prefix, недоступность административных портов и изоляцию storage-сети. Приватность S3 дополняется ACL приложения: запрос без Bearer даёт 401, посторонний участнику чата пользователь — 404 как для metadata, так и для content. + +## Приём, проверка и скачивание + +POST /api/v1/chats/{id}/attachments?filename=... принимает сырые bytes PNG/JPEG. Сначала выполняются аутентификация и проверка чата, затем валидация имени и MIME. Запрещены slash, backslash, NUL, управляющие символы, пустое/пробельное имя и длина более 255 code points. + +Content-Length свыше лимита отклоняется до чтения тела. Независимо от заголовка, включая chunked upload, счётчик проверяется при каждом полученном фрагменте до записи в TemporaryFile: больше 10 MiB — 413. Тело не собирается через request.body(). Временный файл закрывается и удаляется при успехе, ошибке, прерывании клиента и завершении процесса; он не является постоянным хранилищем оригинала. + +Pillow открывает только PNG/JPEG, проверяет реальный формат и число пикселей до load(), затем verify() и полное декодирование обнаруживают повреждения. Подмена MIME/чужой формат/повреждённое изображение — 415; превышение pixels — 413. DecompressionBombWarning считается ошибкой. Оригинал не перекодируется, SHA-256 считается по исходному потоку. + +На одну API-реплику приходится одна активная загрузка/декодирование; остальные запросы ждут слот до 20 s с обратным давлением ASGI, далее получают 503. Приём тела ограничен 30 s. S3 имеет connect timeout 1 s, read timeout 3 s и отключённые автоматические повторы. Один оригинал ≤10 MiB отправляется одним PUT, без multipart и его незавершённых частей. SDK может держать до 10 MiB для PUT; декодирование ограничено 40 млн pixels и одним изображением. Каждый API имеет лимит 384 MiB и 1 CPU; количество загрузок не умножает число полных декодирований на реплике. + +201 ready отправляется только после сохранения S3 и COMMIT metadata. variants=[], error_code=null. GET metadata/content снова проверяет членство в чате. Content идёт через API без redirect, порциями 64 KiB с истинным Content-Type, Content-Length, безопасным Content-Disposition и nosniff. Файл не читается целиком в RAM при скачивании; S3-соединение закрывается в finally. SHA-256 и size_bytes описывают исходные bytes. + +/health/ready проверяет PostgreSQL, Valkey и существование S3 bucket подписанным HEAD. /health/live проверяет процесс. При отказе S3 обязательные upload/download получают 503; LB исключает неготовые API. После отправки части download последующий сетевой обрыв означает неполный HTTP download: статус уже не заменяется, клиент может повторить безопасный GET. + +### Пауза PostgreSQL и клиентский таймаут + +Помимо connect_timeout=2 s, ожидания пула 2 s и серверного statement_timeout=3 s, каждое ожидание PostgreSQL I/O ограничено на стороне приложения двумя секундами. TimedConnection использует timeout метода wait() закреплённой версии Psycopg 3.3.6. Это распространяется на проверку соединения из пула, выполнение SQL, COMMIT и ROLLBACK, даже когда процесс PostgreSQL приостановлен и серверный таймер не работает. + +При OperationalError соединение закрывается до выхода из контекста транзакции. API возвращает 503 unavailable в обычном формате, не ожидая отмены запроса или ROLLBACK от приостановленного сервера. Зависших потоков и выданных навсегда соединений не остаётся; пул создаёт замену. После docker compose unpause postgres readiness и запросы с прежними сессиями восстанавливаются без перезапуска API. + +Регрессионная проверка получает соединение до pause и отключает серверный statement_timeout, чтобы отдельно проверить клиентское ограничение SQL. Затем держит настоящую PostgreSQL на pause не менее 12 s, проверяет прямой /health/ready, 10 параллельных повторов и /health/live внутри API-контейнера, минуя LB. После unpause сверяются неизменные ID/StartedAt API, действующая сессия и сохранённое сообщение. Сценарий включён в check-docker.sh; отдельно запускается в своём временном стенде: + +```sh +./scripts/build.sh +.venv/bin/python student-tests/postgres_pause.py +``` + +Результат отдельного запуска: [evidence/postgres-pause.json](evidence/postgres-pause.json). Полный прогон сохраняет этот сценарий в поле postgres_pause файла lab4-checks.json. + +Фактическая проверка 06.11.2026, project lab4-pg-pause-6c3e872952: SQL без серверного таймера прерван за 2.0 s, соединение закрыто; прямой readiness вернул 503 за 2.012 s. Все 10 параллельных readiness-запросов вернули 503, максимум 2.197 s. PostgreSQL оставалась на pause 14.918 s; live отвечал 200. После unpause действующая сессия и сообщение доступны через LB за 1.355 s, без restart API. + +## Согласованность S3 и PostgreSQL на уровне 4 + +1. После приёма и проверки файла отдельный COMMIT сохраняет attachment_uploads с ID и object_key. +2. Следующая транзакция берёт advisory lock object_key, выполняет S3 PUT, вставляет attachments и удаляет журнал. Только после COMMIT отправляется 201. +3. При обрыве клиентского тела до проверки S3/журнал ещё не затрагиваются. При ошибке PUT или отказе БД после PUT сохраняется долговечное намерение. Если исход COMMIT неизвестен, немедленного DELETE нет: ready-метаданные могли сохраниться. +4. Cleaner каждые 30 s выбирает до 100 записей старше grace period, пробует ту же advisory lock и повторно проверяет возраст и наличие ready-метаданных. Активный lock означает пропуск. Если ready существует, очищается только журнал. Иначе выполняются идемпотентный S3 DELETE и удаление журнала. +5. Ошибка S3/БД откладывает проход. Если DELETE уже прошёл, а COMMIT удаления журнала нет, повторный DELETE безопасен. При восстановлении зависимостей worker продолжает работу. + +По умолчанию grace=1 час существенно больше таймаутов загрузки; минимальное значение — 60 s. Транзакция записи имеет idle timeout 30 s. Свежие и активные загрузки защищены возрастом и блокировкой, ready-объекты не удаляются даже без привязки к сообщению. После восстановления сервисов журнал не остаётся без обработчика. + +```sh +# Ручной дополнительный проход; постоянный cleanup-service уже работает: +docker compose run --rm --no-deps cleanup python -m src.cleanup --once +``` + +Это ограниченная компенсация операций приложения. Полный reconciler, presigned upload, варианты изображений и фоновая обработка из следующих лабораторных не добавлялись. + +## Команды проверки и доказательства критериев + +```sh +make check validate PYTHON=.venv/bin/python +./scripts/check.sh +make test-persistence PYTHON=.venv/bin/python ACTION_SCRIPT=scripts/restart.sh +make test-failover PYTHON=.venv/bin/python ACTION_SCRIPT=scripts/stop-one.sh +docker compose start api +./scripts/wait-ready.sh + +# Полный повторяемый прогон уровня 4 в отдельном временном Compose project: +./scripts/check-docker.sh +``` + +check-docker.sh выбирает отдельное имя lab4-check- и свободный порт, создаёт только синтетические данные. В finally удаляет только свои контейнеры и volumes; обычный mtusi-lab4 остаётся доступным. Моделирование отказа БД использует временный trigger в тестовой БД; trigger удаляется в finally. Рабочий API не содержит fault-injection endpoint или специального заголовка. + +| Критерий README | Команда/сценарий | Наблюдение и evidence | +| --- | --- | --- | +| Сохранены возможности lab3, две реплики, общая сессия/идемпотентность | check.sh, повтор ключа через реплики, повтор после рестарта, SIGTERM, rolling update под нагрузкой | api_tests, persistence, sigterm, failovers, rolling_update | +| S3 в общем стенде; metadata в PostgreSQL, bytes в приватном bucket | Docker inspect, прямой S3 GET, проверки прав | containers, attachments.private_bucket | +| 201 ready, Message с attachment_ids, SHA-256 и побайтный download | Публичный smoke и test_attachments | lab4-checks.txt; api_tests | +| Реальные PNG/JPEG, MIME, 10 MiB и 40 MP, опасные filename | test_png_and_jpeg_originals, corruption_and_mime_spoof, pixel_limit_before_decode, filename_rejected_before_storage | 39 собственных тестов; lab4-checks.txt | +| Upload → остановка загрузившей реплики → download другой | Сопоставление X-Instance-Id и Docker ID, реальная stop-one | attachments.upload_replica_failover | +| Restart сохраняет metadata/bytes/действующую сессию | Публичный persistence, StartedAt всех процессов до/после | persistence | +| Слишком большой файл, повреждение, подмена MIME, чужой ID/другой чат не дают 500 | Отдельные негативные HTTP-тесты, включая chunked без Content-Length | test_attachments; lab4-checks.txt | +| Прерывание загрузки и сбой между S3/БД не оставляют вечные неучтённые объекты | Обрыв сокета; trigger отказывает после PUT; затем ручной и автоматический cleaner | attachments.interrupted_body, compensation | +| Безопасный grace period, защита активных/готовых объектов, повторная очистка | Свежий журнал, backdate, удержание advisory lock, ready-ссылка, повтор DELETE | compensation.fresh_kept/active_locked_kept/ready_kept/repeat_safe/automatic_worker | +| Ограничены RAM/таймауты; ≥10 одновременных загрузок с замером памяти | Barrier на 10 клиентах, настоящие PNG 1600×1200, cgroup каждые 20 ms, SHA-256 всех downloads | attachments.parallel_uploads | +| Идемпотентный bootstrap и ограниченные S3 credentials; закрытая администрация | Два bootstrap, запрещённые S3 операции, TCP-пробы из API | attachments.private_bucket | +| Недоступность S3 и восстановление | Остановка настоящего s3-service, запросы внутри API в обход исключившего backend LB | attachments.s3_outage; dependency_readiness | +| PostgreSQL на pause: ограниченный прямой readiness и восстановление без restart API | postgres_pause.py: SQL без серверного таймера, pause ≥12 s, 10 параллельных запросов, unpause | postgres_pause; evidence/postgres-pause.json | + +Все актуальные результаты — [evidence/lab4-checks.txt](evidence/lab4-checks.txt) и [evidence/lab4-checks.json](evidence/lab4-checks.json). Токены, пароли и исходные тела запросов туда не сохраняются. PASS публичного smoke сам по себе не считается доказательством всех критериев. + +## Эксперимент памяти и отказы + +Гипотеза: десять одновременных загрузок не вызывают десять полных декодирований на API; слот и лимиты удерживают RAM ниже контейнерного лимита, оригиналы сохраняются без изменений. Методика: один случайный несжимаемый RGB PNG 1600×1200 (~5.5 MiB), десять потоков с общим barrier, две API-реплики; после каждого 201 второй участник скачивает оригинал, проверяется SHA-256. Монитор в каждой API читает cgroup v2 memory.current каждые 20 ms. Сохраняются исходные временные ряды, memory.peak за всю жизнь контейнера и лимит, duration, successful RPS, p50/p95, число ошибок и OOMKilled. Файл генерируется заново при каждом запуске; его точный размер/checksum записаны в JSON. + +Замер включает Python-процесс монитора и файловый cache cgroup; это консервативная оценка контейнерной памяти, а не чистый RSS приложения. Пик выборки может пропустить события короче 20 ms; memory.peak дополнительно показывает пик за жизнь контейнера. Это один ограниченный учебный прогон с 10 клиентами, без поиска предельной производительности. p50/p95 относятся к успешным HTTP upload; coordinated omission и влияние клиента остаются ограничениями. + +### Результат фактического прогона 06.11.2026 + +Среда: Linux x86_64 в WSL; Docker 29.4.2 x86_64 CPUs=16 RAM=8019410944; Compose 5.1.3. Две API-реплики, по 1 CPU и 384 MiB. Прогрев — полный smoke и 39 тестов до эксперимента; накопившаяся память отражена в baseline. Временный project: lab4-check-1ad8ecf540. + +| Показатель | Наблюдение | +| --- | --- | +| Параллельные uploads | 10 из 10, ошибок 0 | +| Один PNG | 5769329 bytes, 1600×1200 RGB | +| Длительность / успешные upload/s | 1.119 s / 8.934 | +| p50 / p95 HTTP upload | 639.1 / 1104.59 ms | +| Оригиналы | 10 download, все SHA-256 совпали | +| OOM | Нет | + +| API instance | Baseline cgroup, MiB | Пик выборки во время uploads, MiB | Пик cgroup за жизнь контейнера, MiB | Лимит, MiB | +| --- | ---: | ---: | ---: | ---: | +| 330027f55a61 | 200.83 | 223.73 | 225.47 | 384 | +| 27e984eebdb7 | 66.77 | 100.57 | 158.78 | 384 | + +Различие baseline между репликами возникло после предыдущих проверок и аллокаций; сравнение не трактуется как чистое измерение стоимости одного декодирования. Пик за жизнь контейнера включает более ранние тесты. Гипотеза о соблюдении лимита в этом профиле подтверждена; универсальная производительность или поведение при произвольном числе клиентов не выводятся. + +| Воздействие | Наблюдение | Восстановление / потеря подтверждённых данных | +| --- | --- | --- | +| Остановлена загрузившая API-реплика 27e984eebdb7 | Download обслужила 330027f55a61; исходный SHA-256 совпал | 2.093 s от начала stop; потерь нет | +| Прервано HTTP-тело | Metadata и журнал не созданы; S3 PUT не начинался | Очистка временного файла; ready-объектов не затрагивает | +| БД отказала после S3 PUT | HTTP 503; объект существует вместе с журналом; ready-metadata отсутствует | Свежий/активный объект сохранён; после искусственного старения безопасно удалён; worker проверен отдельно | +| S3 service остановлен | live=200, ready/upload/download=503 в едином формате API | После старта прежний токен и оригинал работают; downtime отдельно не измерялся | +| PostgreSQL на pause 14.737 s | Прямой ready=503 за 2.01 s; 10 повторов, максимум 2.197 s; live=200 | После unpause 2.2 s; API не перезапущены, сессия и сообщение сохранены | +| Restart всего стенда с volumes | StartedAt всех постоянных процессов изменились; сессия, metadata, bytes и повтор сообщения сохранены | Уложилось в бюджет ожидания 90 s; потерь нет | +| SIGTERM с незавершённым POST | Новые соединения прекращены за 0.26 s; exit code 0, без OOM | Выход за 6.036 s, меньше 8 s | + +Дополнительно сохранены результаты отказа каждой реплики и поочерёдной замены под нагрузкой: + +| Сценарий | Длительность, s | Успешные HTTP/s | Переходные ошибки | Макс. пауза POST / GET, s | Потери / дубли | +| --- | ---: | ---: | ---: | --- | --- | +| stop 27e984eebdb7 | 16.032 | 68.86 | 4 | 1.99 / 1.937 | 0 / 0 | +| stop 330027f55a61 | 16.105 | 70.91 | 4 | 1.997 / 2.0 | 0 / 0 | +| sequential API replacement | 30.186 | 71.16 | 8 | 1.995 / 2.146 | 0 / 0 | + +Этот профиль из lab3 использует четыре закрытых клиента: POST сообщения и GET истории, пауза 50 ms. При неопределённом POST повторяется тот же ключ/тело. Длительность включает 1 s прогрева и воздействие; исходные посекундные счётчики есть в JSON. Это проверка восстановления и отсутствия потерь, а не поиск предельного RPS. + +## Ограничения и следующие шаги + +Гарантируется сохранность при проверенном обычном restart с volumes и отказе одной API-реплики при доступных зависимостях. PostgreSQL, Valkey, S3 и LB остаются отдельными точками отказа; HA хранилищ, отказ хоста/электропитания и backup этой работы не заявлены. HEAD bucket в readiness не является тестом записи каждого объекта. Потеря или удаление volumes уничтожает соответствующие данные. + +После 201 данные доступны всем участникам через любую готовую реплику. Неопределённый ответ upload может привести к ещё одному готовому вложению при повторе: идемпотентность upload контрактом не предусмотрена. Cleaner удаляет только незавершённые журналируемые операции; потеря одновременно БД/журнала или ручная запись посторонних объектов требует работы оператора. При длительной недоступности S3/БД очистка откладывается до восстановления. + +Слоты и ресурсные лимиты ограничивают память, но не обещают отсутствие 503 при произвольной нагрузке. Временный spool хранится на ephemeral disk API только во время запроса. Для удалённого стенда нужен TLS; текущий HTTP привязан к localhost и использует синтетические учебные данные. + +## Первичные источники + +- [SeaweedFS 3.85: команды сервера](https://github.com/seaweedfs/seaweedfs/blob/3.85/weed/command/server.go). +- [SeaweedFS 3.85: IAM и ограничения действий](https://github.com/seaweedfs/seaweedfs/blob/3.85/weed/s3api/auth_credentials.go). +- [MinIO Python SDK](https://minio-py.min.io/). +- [Pillow Image: open, verify, load и лимиты](https://pillow.readthedocs.io/en/stable/reference/Image.html). +- [Psycopg 3.3.6: клиентский timeout ожидания I/O](https://github.com/psycopg/psycopg/blob/3.3.6/psycopg/psycopg/connection.py). diff --git a/compose.example.yaml b/compose.example.yaml new file mode 100644 index 0000000..76a785f --- /dev/null +++ b/compose.example.yaml @@ -0,0 +1,12 @@ +# 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: 4 +x-required-roles: + - api + - postgres + - load_balancer + - s3 +# TODO: implement real images/builds, network wiring, volumes, healthchecks, +# credentials and bootstrap. Details: contracts/infrastructure.json and README.md. +services: {} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..3835171 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,165 @@ +name: mtusi-lab4 + +x-application: &application + image: mtusi-messenger:lab4 + env_file: .env + cpus: 1 + mem_limit: 384m + +x-postgres: &postgres + image: postgres:17.6-bookworm + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: [postgres_password] + cpus: 1 + mem_limit: 512m + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 2s + timeout: 3s + retries: 30 + +services: + postgres: + <<: *postgres + volumes: [postgres_data:/var/lib/postgresql/data] + + valkey: + image: valkey/valkey:8.1.3 + command: ["valkey-server", "--appendonly", "yes", "--appendfsync", "always", "--save", "", "--maxmemory", "64mb", "--maxmemory-policy", "noeviction"] + volumes: [valkey_data:/data] + cpus: 0.5 + mem_limit: 128m + healthcheck: + test: ["CMD", "valkey-cli", "ping"] + interval: 2s + timeout: 3s + retries: 30 + + api: + <<: *application + build: . + deploy: + replicas: ${API_REPLICAS:-2} + environment: + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + secrets: [database_url, cache_url, s3_access_key_id, s3_secret_access_key] + depends_on: + postgres: {condition: service_healthy} + valkey: {condition: service_healthy} + migrate: {condition: service_completed_successfully} + s3: {condition: service_healthy} + s3-bootstrap: {condition: service_completed_successfully} + stop_grace_period: 8s + + migrate: + <<: *application + command: ["python", "-m", "src.migrate"] + secrets: [database_url] + healthcheck: + disable: true + depends_on: + postgres: {condition: service_healthy} + + s3: + image: chrislusf/seaweedfs:3.85@sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a + command: ["s3", "-filer=s3-storage:8888", "-ip.bind=0.0.0.0", "-port=9000", "-config=/run/secrets/s3_config"] + secrets: [s3_config] + networks: [default, s3-internal] + depends_on: + s3-storage: {condition: service_healthy} + cpus: 0.5 + mem_limit: 256m + healthcheck: + test: ["CMD", "nc", "-z", "127.0.0.1", "9000"] + interval: 2s + timeout: 2s + retries: 30 + + s3-storage: + image: chrislusf/seaweedfs:3.85@sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a + command: ["server", "-dir=/data", "-ip=s3-storage", "-ip.bind=0.0.0.0", "-filer", "-master.volumeSizeLimitMB=64", "-volume.max=64", "-volume.preStopSeconds=0"] + volumes: [s3_data:/data] + networks: [s3-internal] + cpus: 1 + mem_limit: 512m + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8888/"] + interval: 2s + timeout: 2s + retries: 30 + + s3-bootstrap: + <<: *application + command: ["python", "-m", "src.bootstrap_s3"] + environment: + S3_ROOT_USER_FILE: /run/secrets/s3_root_user + S3_ROOT_PASSWORD_FILE: /run/secrets/s3_root_password + secrets: [s3_root_user, s3_root_password] + cpus: 0.5 + mem_limit: 128m + healthcheck: + disable: true + depends_on: + s3: {condition: service_healthy} + + cleanup: + <<: *application + command: ["python", "-m", "src.cleanup"] + secrets: [database_url, s3_access_key_id, s3_secret_access_key] + restart: unless-stopped + healthcheck: + disable: true + depends_on: + migrate: {condition: service_completed_successfully} + s3-bootstrap: {condition: service_completed_successfully} + + lb: + image: haproxy:3.2.6-alpine + ports: ["127.0.0.1:${HOST_PORT:-8080}:8080"] + volumes: [./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro] + cpus: 0.5 + mem_limit: 64m + depends_on: + api: {condition: service_healthy} + stop_grace_period: 10s + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"] + interval: 2s + timeout: 2s + retries: 3 + + postgres-restore: + <<: *postgres + profiles: [research] + volumes: [restore_data:/var/lib/postgresql/data] + +volumes: + postgres_data: + valkey_data: + restore_data: + s3_data: + +networks: + s3-internal: + internal: true + +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + cache_url: + file: ./secrets/cache_url + s3_root_user: + file: ./secrets/s3_root_user + s3_root_password: + file: ./secrets/s3_root_password + s3_access_key_id: + file: ./secrets/s3_access_key_id + s3_secret_access_key: + file: ./secrets/s3_secret_access_key + s3_config: + file: ./secrets/s3_config diff --git a/contracts/README.md b/contracts/README.md new file mode 100644 index 0000000..8c58b32 --- /dev/null +++ b/contracts/README.md @@ -0,0 +1,61 @@ +# Семантика API + +Этот текст дополняет [openapi.json](openapi.json). Обязательный API соответствует уровню 3 текущей лабораторной. Факультативный crop или rate limiting не становятся обязательными только из-за наличия допустимого имени варианта или кода ошибки в схеме. + +## Формат и ошибки + +- JSON — UTF-8, `Content-Type: application/json`. UUID — строка; время — RFC 3339 UTC с `Z`, назначается сервером. Часы не считаются уникальным ID. +- Каждый ответ API, включая ошибки и health, содержит непустой `X-Request-Id`. Тело ошибки: `{"error":{"code":"invalid_request","message":"...","request_id":"..."}}`; `request_id` совпадает с заголовком. Сообщение ошибки не раскрывает stack trace, SQL, credentials или наличие чужого объекта. +- Обязательные строки не состоят только из пробельных символов. `username` строго `[a-z0-9_]{3,32}`, уникален; `display_name` — 1–100 Unicode code points. JSON с лишними полями или неверными типами — `400`; malformed JSON также `400`. +- `400 invalid_request` — неверные поля, UUID, cursor, limit; `401 unauthorized` — нет действительной идентификации/сессии; `404 not_found` — объекта нет или он чужой; `409 conflict` — username занят, повторный ключ с другим сообщением, объект ещё не готов; `413 payload_too_large`; `415 unsupported_media_type`; `429 rate_limited`; `503 unavailable`. Неожиданное исключение — `500 internal_error` без внутренних деталей. +- Сначала аутентификация, затем доступ к конкретному ресурсу. Любой аутентифицированный участник чата может читать его историю и вложения и писать в него; посторонний получает `404`. Списки содержат только доступные объекты. Не используйте `403` для раскрытия существования чужого чата. +- `GET /health/live` проверяет только жизнь процесса, возвращает `200 {"status":"ok"}`. `GET /health/ready` возвращает 200, если приложение может безопасно обслуживать обязательный синхронный путь; иначе 503 в общем формате ошибки. Какие зависимости критичны, зафиксируйте в отчёте; недоступность Grafana не должна останавливать API. + +## Пользователи, чаты и сообщения + +- `POST /users` публичен; возвращает `201 User`. Пароль/его hash и сессионные данные никогда не входят в User. +- `POST /chats` принимает title и явный список существующих `member_ids`, включая вызывающего. Дубликаты, неизвестные участники и отсутствие вызывающего — 400. Чат создаётся атомарно. GET списка чатов сортируется по `(created_at, id)` по возрастанию. +- Отправитель сообщения выводится из текущей идентификации, поле `sender_id` в запросе не принимается. Текст — до 4000 Unicode code points. Нельзя отправить пустой/пробельный текст без вложений. +- История использует keyset cursor: `(created_at, id)`, по возрастанию; `limit` — целое 1–100, по умолчанию 50. Ответ `{"items":[...],"next_cursor":null}`. Непустой cursor — непрозрачная для клиента строка; последний элемент предыдущей страницы не повторяется. Cursor привязан к ресурсу/запросу: от другого чата — 400. Изменять `limit` при продолжении можно. +- `next_cursor` равен null, если на момент чтения следующей записи нет. Гарантируется отсутствие повторов при обходе неизменной истории; snapshot изоляция между несколькими HTTP-запросами не требуется. При конкурентных вставках опишите выбранную семантику и ограничения часов. +- Подтверждённое сообщение видно следующему чтению через любую API-реплику. Допускается кэш, но он не должен возвращать устаревшую историю после успешной записи. Удаление и изменение участников в обязательный API не входят. + +## Идентификация и сессии + +**Lab1:** защищённые endpoint требуют `X-User-Id: `; отсутствие/неизвестный ID — 401. Это учебный выбор пользователя: любой клиент может выдать себя за другого. + +**Lab2–7:** `POST /auth/sessions` принимает только `Authorization: Basic `, без JSON body. Username ограничен ASCII; пароль кодируется UTF-8, 12–128 code points, двоеточие в пароле допустимо. Неверные credentials — одинаковый 401 и `WWW-Authenticate: Basic realm="messenger", charset="UTF-8"`. + +Вход возвращает `201 {"token":"...","token_type":"Bearer","expires_at":"...Z","user":{...}}`. Токен — непрозрачное случайное значение, не username/UUID и не обязательный JWT; энтропия не менее 256 бит. Храните серверную сессию с expiry; TTL задаётся `SESSION_TTL_SECONDS`, по умолчанию 3600 (в тесте истечения можно 2). В обычном smoke TTL должен быть не менее 300. + +Все защищённые endpoint принимают только `Authorization: Bearer `. Истёкший/отозванный/неизвестный токен — 401 с `WWW-Authenticate: Bearer realm="messenger"`. Basic на бизнес-endpoint — 401. `X-User-Id` с lab2 игнорируется: он не меняет владельца сессии и сам по себе не даёт доступ. `DELETE /auth/sessions/current` отзывает текущий токен и возвращает 204 без тела; повтор с отозванным токеном — 401. + +Пользователи, чаты, сообщения и ещё действительные сессии переживают перезапуск приложения и используемых хранилищ с сохранёнными volumes. TTL не продлевается из-за рестарта. Пароли уже с lab2 хешируются библиотечным password KDF (Argon2id, scrypt или bcrypt с учётом ограничений библиотеки), не SHA-256 и не plaintext. Если bcrypt не поддерживает весь диапазон UTF-8 паролей без усечения, выберите другую библиотечную схему. В lab7 обязателен Argon2id. + +Basic — это кодирование, не шифрование. HTTP lab1–6 допускается только для локального изолированного стенда с синтетическими данными; для удалённой демонстрации нужен TLS. Lab7 использует HTTPS обязательно. См. [RFC 7617](https://www.rfc-editor.org/info/rfc7617/). + +## Балансировка и повторная отправка (с lab3) + +- Каждый ответ, созданный API, содержит `X-Instance-Id`; значение стабильно для жизни процесса. Ошибки соединения, созданные самим LB, могут не иметь этого заголовка. В lab7 используйте случайный alias реплики без раскрытия hostname/IP. +- Для POST сообщения обязателен `Idempotency-Key` (ASCII `[A-Za-z0-9._:-]{1,128}`). Нет/неверный ключ — 400. Область уникальности: текущий пользователь + HTTP-метод + путь чата + ключ. +- При повторе того же валидного JSON в течение 24 часов сервер возвращает тот же код 201 и то же Message. Порядок ключей JSON и отсутствующий `attachment_ids` вместо `[]` семантически равны. Другой body при том же ключе — 409. Разные пользователи/чаты могут использовать одинаковый ключ независимо. +- Одновременные повторы через разные реплики создают ровно одно сообщение. Повтор снова проверяет действительность сессии и доступ. Транзиентные 5xx не фиксируются как окончательный результат; побочный эффект и запись результата должны быть атомарны. +- Ключ обязателен только для сообщений. Самостоятельный retry загрузки файла или создания чата может создать ещё один объект; не добавляйте прозрачные повторы этих POST без расширения контракта. + +## Вложения (с lab4) + +- `POST /chats/{chat_id}/attachments?filename=photo.png`: сырые bytes одного PNG/JPEG; `Content-Type: image/png` или `image/jpeg`. Не multipart. Максимум **10 MiB = 10 485 760 байт**. MIME проверяется по содержимому; заведомо повреждённые/чужие форматы — 415, превышение bytes — 413. Не более 40 миллионов декодированных пикселей (превышение — 413). Устанавливайте лимит до полной распаковки изображения. +- `filename` — отображаемое имя (1–255 code points). Не используйте его как путь/ключ S3. Имя с `/`, `\`, NUL или управляющими символами — 400. Bucket приватен; object key генерирует сервер. Оригинал возвращается побайтно, его lowercase SHA-256 и размер соответствуют исходному файлу. +- Lab4 возвращает `201 Attachment` со `status=ready`, `variants=[]`, `error_code=null` только после сохранения оригинала и метаданных. Lab5–7 возвращают `202 Attachment` со снимком `status=queued`; готовность определяется последующим GET метаданных. Быстрый worker может закончить до первого GET — это нормально. +- Файл заранее привязан к чату. В POST сообщения добавляется `attachment_ids` (0–10 уникальных ID, по умолчанию []). Можно отправить `text=""` с хотя бы одним вложением. Все вложения должны принадлежать этому чату; чужое/неизвестное — 404. Любой участник может ссылаться на доступное вложение чата. Failed-вложение прикреплять нельзя (409); queued/processing с lab5 можно. +- `GET /attachments/{id}` и `/content` доступны только участникам чата. Download возвращает байты с истинным Content-Type, через авторизованный API, **без redirect** в обязательном контракте. Приватный bucket сам по себе не заменяет эту проверку. `variant` по умолчанию original. Для queued/processing content — 409; для failed — 409. Отсутствующий вариант ready-объекта — 404. +- В ready-метаданных `error_code=null`. В failed — краткий машинный код (например `invalid_image`, `processing_failed`, `retry_exhausted`), без stack trace. `size_bytes`, `sha256`, `content_type` всегда описывают оригинал; у вариантов отдельные поля. Публичный API не раскрывает ключи бакета, внутренние адреса и credentials. +- Прямой upload/download по временной подписи — факультативное расширение. Его дополняют ограничение срока/размера, уникальный ключ и подтверждение реально загруженного объекта; он не заменяет стандартный endpoint. Особенности подписанных URL: [S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html). + +## Фоновая обработка (с lab5) + +До 202 все байты приняты в **устойчивый staging**, а намерение обработать файл надёжно сохранено. HTTP-передача клиента не исчезает и не становится мгновенной. Staging — приватный S3-prefix либо общий persistent volume, доступный worker; локальная память/API ephemeral disk не подходит. Worker асинхронно переносит/публикует оригинал в конечный S3-prefix и создаёт варианты; если staging уже в S3, опишите эту границу честно. + +Обязательный thumbnail: JPEG, изображение вписано в 256×256 с сохранением пропорций, без увеличения маленьких исходников, EXIF orientation применяется; alpha компонуется на белый. Размеры округляются вниз, минимум 1 px. Fixture 320×200 должен дать 256×160. Статус ready ставится после сохранения оригинала и thumbnail. Crop на 4: JPEG, центрированный квадрат 128×128 (для маленьких исходников допускается увеличение). Optimized на 4: WebP, вписан в 1280×1280 без увеличения, параметры качества и удаления EXIF документируются; не обещайте уменьшение каждого маленького файла. + +Допустимые состояния и события описаны в `jobs.schema.json` и `attachment-states.md`. Доставка — at least once; обработка идемпотентна, повторы не размножают варианты. Финальные ошибки наблюдаемы, бесконечный немой retry недопустим. Обязательный smoke ждёт ready до 60 секунд; это бюджет локального smoke для одного файла при свободном worker, не универсальный production SLA. В очередь идут ссылки/ID, не бинарное содержимое. diff --git a/contracts/examples.json b/contracts/examples.json new file mode 100644 index 0000000..060abd0 --- /dev/null +++ b/contracts/examples.json @@ -0,0 +1,60 @@ +{ + "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", + "attachment_ids": [] + }, + "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", + "attachment_ids": [] + } + ], + "next_cursor": null + }, + "Error": { + "error": { + "code": "not_found", + "message": "Объект не найден", + "request_id": "example-request-id" + } + } +} diff --git a/contracts/infrastructure.json b/contracts/infrastructure.json new file mode 100644 index 0000000..dd2edf2 --- /dev/null +++ b/contracts/infrastructure.json @@ -0,0 +1,46 @@ +{ + "lab": 4, + "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 + }, + { + "role": "s3", + "choose_one": [ + "MinIO", + "SeaweedFS", + "RustFS" + ], + "private_bucket": true, + "persistent_volume": true + } + ], + "optional_components": [ + { + "role": "redis_or_valkey", + "required_for_lab2_grade4": true, + "note": "Choose one; if only store of sessions, configure durable persistence." + } + ], + "rules": [ + "Choose Compose or Swarm for lab3+; do not need both.", + "Never publish internal API replica ports in bypass of LB from lab3.", + "Versions/digests must be fixed in implementation.", + "Do not remove volumes in restart/failover checks.", + "Document service names, healthchecks, bootstrap/migrations and credentials." + ] +} diff --git a/contracts/openapi.json b/contracts/openapi.json new file mode 100644 index 0000000..138f07c --- /dev/null +++ b/contracts/openapi.json @@ -0,0 +1,3506 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "MTUSI Messenger — лабораторная 4", + "version": "1.4.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" + } + } + } + } + } + } + }, + "/api/v1/chats/{chat_id}/attachments": { + "post": { + "operationId": "uploadAttachment", + "summary": "Принять один PNG/JPEG, до 10 MiB", + "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/Attachment" + } + } + } + }, + "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" + } + } + } + }, + "413": { + "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" + } + } + } + }, + "415": { + "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": "filename", + "in": "query", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 255 + } + } + ], + "requestBody": { + "required": true, + "description": "Сырые байты изображения, НЕ multipart и НЕ JSON/base64.", + "content": { + "image/png": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/jpeg": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + } + }, + "/api/v1/attachments/{attachment_id}": { + "get": { + "operationId": "getAttachment", + "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/Attachment" + } + } + } + }, + "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": "attachment_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ] + } + }, + "/api/v1/attachments/{attachment_id}/content": { + "get": { + "operationId": "downloadAttachment", + "summary": "Скачать байты через авторизованный API", + "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": { + "image/png": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/jpeg": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/webp": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "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": "attachment_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "variant", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "original" + ], + "default": "original" + } + } + ] + } + } + }, + "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", + "maxLength": 4000 + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "attachment_ids": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 10, + "uniqueItems": true + } + }, + "required": [ + "id", + "chat_id", + "sender_id", + "text", + "created_at", + "attachment_ids" + ], + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "text": { + "minLength": 1 + } + } + }, + { + "properties": { + "attachment_ids": { + "minItems": 1 + } + } + } + ], + "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", + "attachment_ids": [] + } + ] + }, + "CreateMessage": { + "type": "object", + "properties": { + "text": { + "type": "string", + "maxLength": 4000 + }, + "attachment_ids": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 10, + "uniqueItems": true, + "default": [] + } + }, + "required": [ + "text" + ], + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "text": { + "minLength": 1 + } + } + }, + { + "properties": { + "attachment_ids": { + "minItems": 1 + } + }, + "required": [ + "attachment_ids" + ] + } + ], + "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", + "attachment_ids": [] + } + ], + "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 + }, + "Variant": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "thumbnail", + "crop", + "optimized" + ] + }, + "content_type": { + "type": "string", + "enum": [ + "image/jpeg", + "image/png", + "image/webp" + ] + }, + "size_bytes": { + "type": "integer", + "minimum": 1 + }, + "width": { + "type": "integer", + "minimum": 1 + }, + "height": { + "type": "integer", + "minimum": 1 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + } + }, + "required": [ + "name", + "content_type", + "size_bytes", + "width", + "height", + "sha256" + ], + "additionalProperties": false + }, + "Attachment": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "chat_id": { + "type": "string", + "format": "uuid" + }, + "owner_id": { + "type": "string", + "format": "uuid" + }, + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "content_type": { + "type": "string", + "enum": [ + "image/png", + "image/jpeg" + ] + }, + "size_bytes": { + "type": "integer", + "minimum": 1, + "maximum": 10485760 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "status": { + "type": "string", + "enum": [ + "ready" + ] + }, + "variants": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Variant" + } + }, + "error_code": { + "type": [ + "string", + "null" + ] + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "updated_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "chat_id", + "owner_id", + "filename", + "content_type", + "size_bytes", + "sha256", + "status", + "variants", + "error_code", + "created_at", + "updated_at" + ], + "additionalProperties": false + } + } + } +} diff --git a/docs/schema.md b/docs/schema.md new file mode 100644 index 0000000..52143c8 --- /dev/null +++ b/docs/schema.md @@ -0,0 +1,33 @@ +# Схема и транзакции + +Лабораторная 4, оценка 4: клиент → HAProxy → FastAPI × 2 → PostgreSQL + Valkey + приватный S3 (SeaweedFS). + +| Таблица PostgreSQL | Назначение и ограничения | +| --- | --- | +| users | UUID PK; username UNIQUE; password_hash Argon2id; display_name; created_at | +| chats | UUID PK; title; created_at | +| chat_members | PK (chat_id, user_id); FK на chats и users | +| messages | UUID PK; FK на чат и членство отправителя; text до 4000 code points; created_at | +| message_attachments | FK на messages и attachments; до 10 позиций; UNIQUE(message_id, position); PK(message_id, attachment_id) | +| attachments | UUID PK; FK chat_id и (chat_id, owner_id); UNIQUE object_key; filename, content_type, size_bytes, sha256, created_at | +| attachment_uploads | UUID PK, UNIQUE object_key, created_at; долговечный журнал незавершённых PUT | +| message_idempotency | PK (user_id, chat_id, key); request_text, request_attachment_ids, message_id FK, expires_at | +| schema_migrations | Имя и SHA-256 применённой миграции; applied_at | + +В PostgreSQL нет bytes оригинала. `object_key=attachments/<случайный UUID>` назначает сервер; filename не участвует в ключе. В таблицу attachments попадают только ready-объекты; status=ready, variants=[], error_code=null формируются API. updated_at совпадает с created_at, поскольку API lab4 не изменяет вложения. + +Индексы: UNIQUE users(username); chat_members(user_id, chat_id); messages(chat_id, created_at, id); attachments(chat_id); attachment_uploads(created_at). Первичные/уникальные ключи индексируют поиск ID и object_key. + +Создание чата и его участников атомарно. Неизвестный участник откатывает весь чат. Сообщение проверяет членство и все attachment_ids в том же чате, затем одной транзакцией записывает messages, message_attachments и результат идемпотентности. Составной FK дополнительно запрещает отправителя вне чата. Пустой/пробельный text разрешён только с вложением: это проверяет модель запроса; FK таблицы message_attachments запрещают несуществующие ссылки. Удаления вложений в HTTP API нет. + +Общая advisory transaction lock сериализует область пользователь + POST + путь чата + Idempotency-Key. Сравниваются text и упорядоченный нормализованный список UUID; отсутствие attachment_ids эквивалентно []. Совпадение возвращает исходный 201 и Message, отличие — 409. TTL не меньше 24 часов. Чтение истории использует keyset (created_at,id), без кэша; на следующем запросе видны COMMIT любой реплики. При конкурентных вставках snapshot между страницами нет; запись с более ранними часами может оказаться до уже пройденного cursor. + +Upload сначала полностью принимает ограниченный поток во временный файл и проверяет PNG/JPEG. Затем отдельной транзакцией фиксирует attachment_uploads. В следующей транзакции берётся advisory lock object_key, выполняется S3 PUT, вставляются ready-метаданные и удаляется журнал. 201 отправляется после COMMIT. S3 и PostgreSQL не образуют распределённую транзакцию. + +Если PUT прошёл, а COMMIT нет, остаётся журнал. Если исход COMMIT неизвестен, немедленного удаления нет: ready-метаданные могли сохраниться. Cleaner раз в 30 секунд берёт до 100 записей старше grace period (по умолчанию 3600 s, минимум 60 s), пробует ту же advisory lock и повторно проверяет запись. Активная загрузка пропускается; при наличии ready-метаданных удаляется только запись журнала; иначе удаляется S3 object и затем журнал. DELETE объекта идемпотентен. Сбой S3/БД откладывает обработку; следующий проход повторяет её. Это компенсация журналируемых загрузок уровня 4, без полного обхода bucket. + +Миграции 001 и 002 сохранены. Миграция 003 добавляет вложения, связи, журнал и список вложений в ключе повтора; старые сообщения имеют пустой список. DDL выполняет один migrate-service под общей advisory lock; API проверяют версии и checksum. + +Valkey хранит только серверные сессии: session:SHA256(token) → user_id, expires_at, TTL. Включены AOF appendfsync always и постоянный volume. Сырой токен не записывается в evidence. PostgreSQL, Valkey и S3 bucket проверяются /health/ready; /health/live не обращается к зависимостям. + +Исходные отчёты и результаты lab2/lab3 сохранены отдельно. Актуальные команды, измерения и ограничения — в [REPORT.md](../REPORT.md). diff --git a/evidence/README.md b/evidence/README.md new file mode 100644 index 0000000..8df7001 --- /dev/null +++ b/evidence/README.md @@ -0,0 +1,5 @@ +# Доказательства + +Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки. + +Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно. diff --git a/evidence/lab4-checks.json b/evidence/lab4-checks.json new file mode 100644 index 0000000..81eb8eb --- /dev/null +++ b/evidence/lab4-checks.json @@ -0,0 +1,2403 @@ +{ + "utc": "2026-11-06T10:40:43.309379+00:00", + "project": "lab4-check-1ad8ecf540", + "base_url": "http://127.0.0.1:37173", + "host": "Linux x86_64", + "docker": "29.4.2 x86_64 CPUs=16 RAM=8019410944", + "profile": { + "workers": 4, + "pause_seconds": 0.05, + "operation": "POST message then GET history, same-key retry after uncertain POST" + }, + "compose_version": "5.1.3", + "source_commit": null, + "working_tree": null, + "containers": [ + { + "id": "27e984eebdb76456c9f743366e95d6bc21d2b7df61da990d6d1f3dbe962a390d", + "instance": "27e984eebdb7", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:41:14.456863952Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + } + ] + }, + { + "id": "330027f55a61e2a1205fe2ad0eead1233bfbf16822bfb79650c17c416991e85a", + "instance": "330027f55a61", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:41:14.71752364Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + } + ] + }, + { + "id": "c975208b61e656b210e69bfa8a4e30614c4f6dba569a3d8b2201b33aa88902ff", + "instance": "c975208b61e6", + "service": "cleanup", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:41:14.454565616Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + } + ] + }, + { + "id": "7b87f4779624fba0be45ec719a5e10f44b3ff9945f31209be7126727eda70e11", + "instance": "7b87f4779624", + "service": "lb", + "image": "sha256:3a819392f5a6af2a9203d1c63ff0feba74f0c940623a558511be06d7d85e361c", + "started_at": "2026-11-06T10:41:20.492175944Z", + "running": true, + "exit_code": 0, + "memory_bytes": 67108864, + "nano_cpus": 500000000, + "published_ports": { + "8080/tcp": [ + { + "HostIp": "127.0.0.1", + "HostPort": "37173" + } + ] + }, + "mounts": [ + { + "type": "bind", + "destination": "/usr/local/etc/haproxy/haproxy.cfg", + "name": null + } + ] + }, + { + "id": "7ca60edcf5eb061a78c25804d7b2a9402f6321b1772bffbb9ce447fee322837b", + "instance": "7ca60edcf5eb", + "service": "migrate", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:40:49.456776765Z", + "running": false, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + } + ] + }, + { + "id": "063c7053cc6de8d8bd420035c6dcc18e7c76a3b46193b36ad28d3bbc61b047df", + "instance": "063c7053cc6d", + "service": "postgres", + "image": "sha256:f3bd19c606e442c3d7bdfa8002e03fe260a1023351e0ea4598032022b68dd6e3", + "started_at": "2026-11-06T10:40:46.670500402Z", + "running": true, + "exit_code": 0, + "memory_bytes": 536870912, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/var/lib/postgresql/data", + "name": "lab4-check-1ad8ecf540_postgres_data" + }, + { + "type": "bind", + "destination": "/run/secrets/postgres_password", + "name": null + } + ] + }, + { + "id": "d904e73b40a580ce85840f555f8196a30cf1ef87d08eb0895f8451f49867583b", + "instance": "d904e73b40a5", + "service": "s3", + "image": "sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a", + "started_at": "2026-11-06T10:41:09.935893424Z", + "running": true, + "exit_code": 0, + "memory_bytes": 268435456, + "nano_cpus": 500000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_config", + "name": null + }, + { + "type": "volume", + "destination": "/data", + "name": "36b03f64548f3d2ebc2d7b177c27df6bb13970ee7977a4bcf332e77cdaa119f9" + } + ] + }, + { + "id": "4dd077142f753837860707c5671e16ad868b3a94d423a3a6208bc88669b4109e", + "instance": "4dd077142f75", + "service": "s3-bootstrap", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:41:12.697584219Z", + "running": false, + "exit_code": 0, + "memory_bytes": 134217728, + "nano_cpus": 500000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_root_password", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_root_user", + "name": null + } + ] + }, + { + "id": "278b40cca5cac2cdd0f9277d5b50a95fe85d6e05102d6c9234b573dfd76b0726", + "instance": "278b40cca5ca", + "service": "s3-storage", + "image": "sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a", + "started_at": "2026-11-06T10:40:46.660419196Z", + "running": true, + "exit_code": 0, + "memory_bytes": 536870912, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/data", + "name": "lab4-check-1ad8ecf540_s3_data" + } + ] + }, + { + "id": "1e5c416e81b1cb9b31411f8a5999cd81769e2fcc70dbb9be5196bf227c0721b5", + "instance": "1e5c416e81b1", + "service": "valkey", + "image": "sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571", + "started_at": "2026-11-06T10:40:46.672858743Z", + "running": true, + "exit_code": 0, + "memory_bytes": 134217728, + "nano_cpus": 500000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/data", + "name": "lab4-check-1ad8ecf540_valkey_data" + } + ] + } + ], + "api_tests": "public smoke + student unittest suite passed", + "attachments": { + "private_bucket": { + "anonymous_get": 403, + "create_bucket": "AccessDenied", + "write_outside_prefix": "AccessDenied", + "admin_ports_unreachable": [ + 9333, + 8888, + 8080 + ], + "storage_network_isolated": true, + "bootstrap_runs": 2 + }, + "upload_replica_failover": { + "uploaded_by": "27e984eebdb7", + "stopped_container": "27e984eebdb76456c9f743366e95d6bc21d2b7df61da990d6d1f3dbe962a390d", + "downloaded_by": "330027f55a61", + "sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75", + "recovery_seconds": 2.093 + }, + "interrupted_body": { + "metadata_or_journal_created": false + }, + "compensation": { + "failure_after_put": 503, + "orphan_recorded": true, + "fresh_kept": true, + "active_locked_kept": true, + "expired_removed": true, + "ready_kept": true, + "repeat_safe": true, + "automatic_worker": true + }, + "s3_outage": { + "live": 200, + "ready": 503, + "download": 503, + "upload": 503, + "original_preserved_after_recovery": true + }, + "parallel_uploads": { + "concurrency": 10, + "successful": 10, + "errors": 0, + "dimensions": [ + 1600, + 1200 + ], + "size_bytes": 5769329, + "sha256": "3df68dba26db2bb128d2d577450e985410eb65c13ef77f773a489aea59e03fcd", + "duration_seconds": 1.119, + "successful_rps": 8.934, + "p50_ms": 639.1, + "p95_ms": 1104.59, + "memory_sample_interval_seconds": 0.02, + "memory_includes_monitor_process": true, + "memory": [ + { + "baseline_bytes": 70008832, + "sample_peak_bytes": 105451520, + "lifetime_peak_bytes": 166494208, + "samples": [ + [ + 0.0, + 70008832 + ], + [ + 0.021, + 69951488 + ], + [ + 0.041, + 69951488 + ], + [ + 0.061, + 69648384 + ], + [ + 0.082, + 69648384 + ], + [ + 0.102, + 69648384 + ], + [ + 0.122, + 69648384 + ], + [ + 0.143, + 69648384 + ], + [ + 0.163, + 69648384 + ], + [ + 0.183, + 69648384 + ], + [ + 0.204, + 69648384 + ], + [ + 0.225, + 70131712 + ], + [ + 0.246, + 75517952 + ], + [ + 0.266, + 77246464 + ], + [ + 0.286, + 80584704 + ], + [ + 0.307, + 81231872 + ], + [ + 0.327, + 84316160 + ], + [ + 0.347, + 84402176 + ], + [ + 0.368, + 92360704 + ], + [ + 0.388, + 99250176 + ], + [ + 0.408, + 92250112 + ], + [ + 0.429, + 92053504 + ], + [ + 0.449, + 92053504 + ], + [ + 0.469, + 97955840 + ], + [ + 0.49, + 99782656 + ], + [ + 0.51, + 99758080 + ], + [ + 0.531, + 101466112 + ], + [ + 0.551, + 100970496 + ], + [ + 0.571, + 96636928 + ], + [ + 0.592, + 99078144 + ], + [ + 0.612, + 99819520 + ], + [ + 0.648, + 99995648 + ], + [ + 0.668, + 102461440 + ], + [ + 0.689, + 102785024 + ], + [ + 0.709, + 102473728 + ], + [ + 0.73, + 102252544 + ], + [ + 0.75, + 101994496 + ], + [ + 0.77, + 104087552 + ], + [ + 0.791, + 104669184 + ], + [ + 0.811, + 105193472 + ], + [ + 0.831, + 105451520 + ], + [ + 0.852, + 99680256 + ], + [ + 0.872, + 101928960 + ], + [ + 0.893, + 103428096 + ], + [ + 0.948, + 88752128 + ], + [ + 0.968, + 90595328 + ], + [ + 0.989, + 95051776 + ], + [ + 1.009, + 96251904 + ], + [ + 1.029, + 96063488 + ], + [ + 1.05, + 95809536 + ], + [ + 1.07, + 95555584 + ], + [ + 1.091, + 91021312 + ], + [ + 1.111, + 93081600 + ], + [ + 1.131, + 93331456 + ], + [ + 1.152, + 93331456 + ], + [ + 1.172, + 93634560 + ], + [ + 1.192, + 93634560 + ], + [ + 1.213, + 89067520 + ], + [ + 1.233, + 92651520 + ], + [ + 1.253, + 92844032 + ], + [ + 1.274, + 92839936 + ], + [ + 1.294, + 92901376 + ], + [ + 1.314, + 92639232 + ] + ], + "instance": "27e984eebdb7", + "limit_bytes": 402653184 + }, + { + "baseline_bytes": 210583552, + "sample_peak_bytes": 234598400, + "lifetime_peak_bytes": 236421120, + "samples": [ + [ + 0.0, + 210583552 + ], + [ + 0.021, + 210743296 + ], + [ + 0.042, + 211771392 + ], + [ + 0.063, + 214863872 + ], + [ + 0.083, + 217346048 + ], + [ + 0.103, + 219377664 + ], + [ + 0.124, + 224034816 + ], + [ + 0.144, + 227491840 + ], + [ + 0.164, + 230866944 + ], + [ + 0.185, + 227487744 + ], + [ + 0.205, + 227487744 + ], + [ + 0.225, + 223670272 + ], + [ + 0.246, + 227352576 + ], + [ + 0.266, + 227500032 + ], + [ + 0.286, + 227241984 + ], + [ + 0.307, + 231550976 + ], + [ + 0.327, + 229416960 + ], + [ + 0.348, + 227143680 + ], + [ + 0.368, + 226439168 + ], + [ + 0.388, + 226701312 + ], + [ + 0.409, + 222134272 + ], + [ + 0.429, + 224772096 + ], + [ + 0.449, + 226717696 + ], + [ + 0.47, + 226717696 + ], + [ + 0.49, + 226467840 + ], + [ + 0.511, + 228872192 + ], + [ + 0.531, + 225607680 + ], + [ + 0.551, + 220856320 + ], + [ + 0.572, + 223322112 + ], + [ + 0.592, + 225513472 + ], + [ + 0.612, + 226037760 + ], + [ + 0.633, + 226037760 + ], + [ + 0.653, + 227880960 + ], + [ + 0.674, + 225554432 + ], + [ + 0.694, + 221360128 + ], + [ + 0.715, + 222568448 + ], + [ + 0.735, + 227045376 + ], + [ + 0.755, + 231165952 + ], + [ + 0.776, + 232886272 + ], + [ + 0.796, + 234598400 + ], + [ + 0.817, + 234577920 + ], + [ + 0.837, + 234397696 + ], + [ + 0.873, + 228343808 + ], + [ + 0.893, + 229371904 + ], + [ + 0.914, + 229675008 + ], + [ + 0.934, + 229937152 + ], + [ + 0.954, + 232296448 + ], + [ + 0.975, + 232558592 + ], + [ + 0.995, + 232390656 + ], + [ + 1.015, + 233439232 + ], + [ + 1.036, + 233701376 + ], + [ + 1.056, + 219529216 + ], + [ + 1.077, + 219410432 + ], + [ + 1.097, + 219176960 + ], + [ + 1.117, + 219176960 + ], + [ + 1.138, + 219148288 + ] + ], + "instance": "330027f55a61", + "limit_bytes": 402653184 + } + ], + "all_original_checksums_verified": true, + "oom_killed": false + } + }, + "persistence": { + "before": [ + { + "id": "27e984eebdb76456c9f743366e95d6bc21d2b7df61da990d6d1f3dbe962a390d", + "instance": "27e984eebdb7", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:42:07.665483942Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + } + ] + }, + { + "id": "330027f55a61e2a1205fe2ad0eead1233bfbf16822bfb79650c17c416991e85a", + "instance": "330027f55a61", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:41:14.71752364Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + } + ] + }, + { + "id": "c975208b61e656b210e69bfa8a4e30614c4f6dba569a3d8b2201b33aa88902ff", + "instance": "c975208b61e6", + "service": "cleanup", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:42:47.022411313Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + } + ] + }, + { + "id": "7b87f4779624fba0be45ec719a5e10f44b3ff9945f31209be7126727eda70e11", + "instance": "7b87f4779624", + "service": "lb", + "image": "sha256:3a819392f5a6af2a9203d1c63ff0feba74f0c940623a558511be06d7d85e361c", + "started_at": "2026-11-06T10:41:20.492175944Z", + "running": true, + "exit_code": 0, + "memory_bytes": 67108864, + "nano_cpus": 500000000, + "published_ports": { + "8080/tcp": [ + { + "HostIp": "127.0.0.1", + "HostPort": "37173" + } + ] + }, + "mounts": [ + { + "type": "bind", + "destination": "/usr/local/etc/haproxy/haproxy.cfg", + "name": null + } + ] + }, + { + "id": "063c7053cc6de8d8bd420035c6dcc18e7c76a3b46193b36ad28d3bbc61b047df", + "instance": "063c7053cc6d", + "service": "postgres", + "image": "sha256:f3bd19c606e442c3d7bdfa8002e03fe260a1023351e0ea4598032022b68dd6e3", + "started_at": "2026-11-06T10:40:46.670500402Z", + "running": true, + "exit_code": 0, + "memory_bytes": 536870912, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/var/lib/postgresql/data", + "name": "lab4-check-1ad8ecf540_postgres_data" + }, + { + "type": "bind", + "destination": "/run/secrets/postgres_password", + "name": null + } + ] + }, + { + "id": "d904e73b40a580ce85840f555f8196a30cf1ef87d08eb0895f8451f49867583b", + "instance": "d904e73b40a5", + "service": "s3", + "image": "sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a", + "started_at": "2026-11-06T10:42:37.218199028Z", + "running": true, + "exit_code": 0, + "memory_bytes": 268435456, + "nano_cpus": 500000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_config", + "name": null + }, + { + "type": "volume", + "destination": "/data", + "name": "36b03f64548f3d2ebc2d7b177c27df6bb13970ee7977a4bcf332e77cdaa119f9" + } + ] + }, + { + "id": "278b40cca5cac2cdd0f9277d5b50a95fe85d6e05102d6c9234b573dfd76b0726", + "instance": "278b40cca5ca", + "service": "s3-storage", + "image": "sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a", + "started_at": "2026-11-06T10:40:46.660419196Z", + "running": true, + "exit_code": 0, + "memory_bytes": 536870912, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/data", + "name": "lab4-check-1ad8ecf540_s3_data" + } + ] + }, + { + "id": "1e5c416e81b1cb9b31411f8a5999cd81769e2fcc70dbb9be5196bf227c0721b5", + "instance": "1e5c416e81b1", + "service": "valkey", + "image": "sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571", + "started_at": "2026-11-06T10:40:46.672858743Z", + "running": true, + "exit_code": 0, + "memory_bytes": 134217728, + "nano_cpus": 500000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/data", + "name": "lab4-check-1ad8ecf540_valkey_data" + } + ] + } + ], + "after": [ + { + "id": "27e984eebdb76456c9f743366e95d6bc21d2b7df61da990d6d1f3dbe962a390d", + "instance": "27e984eebdb7", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:42:59.108716279Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + } + ] + }, + { + "id": "330027f55a61e2a1205fe2ad0eead1233bfbf16822bfb79650c17c416991e85a", + "instance": "330027f55a61", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:42:59.196843033Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + } + ] + }, + { + "id": "c975208b61e656b210e69bfa8a4e30614c4f6dba569a3d8b2201b33aa88902ff", + "instance": "c975208b61e6", + "service": "cleanup", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:43:06.36017379Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + } + ] + }, + { + "id": "7b87f4779624fba0be45ec719a5e10f44b3ff9945f31209be7126727eda70e11", + "instance": "7b87f4779624", + "service": "lb", + "image": "sha256:3a819392f5a6af2a9203d1c63ff0feba74f0c940623a558511be06d7d85e361c", + "started_at": "2026-11-06T10:42:58.889107235Z", + "running": true, + "exit_code": 0, + "memory_bytes": 67108864, + "nano_cpus": 500000000, + "published_ports": { + "8080/tcp": [ + { + "HostIp": "127.0.0.1", + "HostPort": "37173" + } + ] + }, + "mounts": [ + { + "type": "bind", + "destination": "/usr/local/etc/haproxy/haproxy.cfg", + "name": null + } + ] + }, + { + "id": "063c7053cc6de8d8bd420035c6dcc18e7c76a3b46193b36ad28d3bbc61b047df", + "instance": "063c7053cc6d", + "service": "postgres", + "image": "sha256:f3bd19c606e442c3d7bdfa8002e03fe260a1023351e0ea4598032022b68dd6e3", + "started_at": "2026-11-06T10:42:58.720784507Z", + "running": true, + "exit_code": 0, + "memory_bytes": 536870912, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/var/lib/postgresql/data", + "name": "lab4-check-1ad8ecf540_postgres_data" + }, + { + "type": "bind", + "destination": "/run/secrets/postgres_password", + "name": null + } + ] + }, + { + "id": "d904e73b40a580ce85840f555f8196a30cf1ef87d08eb0895f8451f49867583b", + "instance": "d904e73b40a5", + "service": "s3", + "image": "sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a", + "started_at": "2026-11-06T10:42:59.037172032Z", + "running": true, + "exit_code": 0, + "memory_bytes": 268435456, + "nano_cpus": 500000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_config", + "name": null + }, + { + "type": "volume", + "destination": "/data", + "name": "36b03f64548f3d2ebc2d7b177c27df6bb13970ee7977a4bcf332e77cdaa119f9" + } + ] + }, + { + "id": "278b40cca5cac2cdd0f9277d5b50a95fe85d6e05102d6c9234b573dfd76b0726", + "instance": "278b40cca5ca", + "service": "s3-storage", + "image": "sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a", + "started_at": "2026-11-06T10:42:58.597351707Z", + "running": true, + "exit_code": 0, + "memory_bytes": 536870912, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/data", + "name": "lab4-check-1ad8ecf540_s3_data" + } + ] + }, + { + "id": "1e5c416e81b1cb9b31411f8a5999cd81769e2fcc70dbb9be5196bf227c0721b5", + "instance": "1e5c416e81b1", + "service": "valkey", + "image": "sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571", + "started_at": "2026-11-06T10:42:58.961053906Z", + "running": true, + "exit_code": 0, + "memory_bytes": 134217728, + "nano_cpus": 500000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/data", + "name": "lab4-check-1ad8ecf540_valkey_data" + } + ] + } + ], + "passed": true, + "idempotency_replay_after_restart": true + }, + "sigterm": { + "instance": "27e984eebdb7", + "unfinished_request": true, + "shutdown_seconds": 6.036, + "new_connections_refused_seconds": 0.26, + "exit_code": 0, + "oom_killed": false + }, + "dependency_readiness": [ + { + "dependency": "valkey", + "api_live": 200, + "api_ready": 503, + "lb_ready": 503 + }, + { + "dependency": "postgres", + "api_live": 200, + "api_ready": 503, + "lb_ready": 503 + }, + { + "dependency": "s3", + "api_live": 200, + "api_ready": 503, + "lb_ready": 503 + } + ], + "postgres_pause": { + "sql_without_server_timeout": { + "elapsed_seconds": 2.0, + "connection_closed": true + }, + "direct_ready": { + "status": 503, + "elapsed_seconds": 2.01 + }, + "direct_live": { + "status": 200, + "elapsed_seconds": 0.009 + }, + "repeated_ready": [ + { + "status": 503, + "elapsed_seconds": 2.01 + }, + { + "status": 503, + "elapsed_seconds": 2.103 + }, + { + "status": 503, + "elapsed_seconds": 2.092 + }, + { + "status": 503, + "elapsed_seconds": 2.194 + }, + { + "status": 503, + "elapsed_seconds": 2.103 + }, + { + "status": 503, + "elapsed_seconds": 2.011 + }, + { + "status": 503, + "elapsed_seconds": 2.009 + }, + { + "status": 503, + "elapsed_seconds": 2.191 + }, + { + "status": 503, + "elapsed_seconds": 2.099 + }, + { + "status": 503, + "elapsed_seconds": 2.197 + } + ], + "ready_after_12_seconds": { + "status": 503, + "elapsed_seconds": 2.008 + }, + "live_after_repeated_requests": { + "status": 200, + "elapsed_seconds": 0.008 + }, + "paused_seconds": 14.737, + "recovered_ready": { + "status": 200, + "elapsed_seconds": 0.014 + }, + "recovery_seconds": 2.2, + "api_not_restarted": true, + "existing_session_and_message_preserved": true, + "passed": true + }, + "public_failover": { + "passed": true, + "containers_after": [ + { + "id": "27e984eebdb76456c9f743366e95d6bc21d2b7df61da990d6d1f3dbe962a390d", + "instance": "27e984eebdb7", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:43:34.600947249Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + } + ] + }, + { + "id": "330027f55a61e2a1205fe2ad0eead1233bfbf16822bfb79650c17c416991e85a", + "instance": "330027f55a61", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:42:59.196843033Z", + "running": false, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + } + ] + } + ] + }, + "failovers": [ + { + "label": "stop 27e984eebdb7", + "duration_seconds": 16.032, + "successful_requests": 1104, + "successful_writes": 551, + "errors": 4, + "successful_rps": 68.86, + "first_success_after_action_seconds": { + "POST": 0.027, + "GET": 0.026 + }, + "maximum_success_gap_seconds": { + "POST": 1.99, + "GET": 1.937 + }, + "action_start_seconds": 1.002, + "action_end_seconds": 2.378, + "p50_ms": 18.076, + "p95_ms": 80.838, + "confirmed_data_preserved": true, + "duplicate_messages": 0, + "instances": [ + "27e984eebdb7", + "330027f55a61" + ], + "per_second": [ + { + "second": 0, + "successes": 82, + "errors": 0 + }, + { + "second": 1, + "successes": 61, + "errors": 0 + }, + { + "second": 2, + "successes": 0, + "errors": 0 + }, + { + "second": 3, + "successes": 21, + "errors": 4 + }, + { + "second": 4, + "successes": 82, + "errors": 0 + }, + { + "second": 5, + "successes": 74, + "errors": 0 + }, + { + "second": 6, + "successes": 68, + "errors": 0 + }, + { + "second": 7, + "successes": 91, + "errors": 0 + }, + { + "second": 8, + "successes": 71, + "errors": 0 + }, + { + "second": 9, + "successes": 85, + "errors": 0 + }, + { + "second": 10, + "successes": 84, + "errors": 0 + }, + { + "second": 11, + "successes": 58, + "errors": 0 + }, + { + "second": 12, + "successes": 79, + "errors": 0 + }, + { + "second": 13, + "successes": 83, + "errors": 0 + }, + { + "second": 14, + "successes": 65, + "errors": 0 + }, + { + "second": 15, + "successes": 96, + "errors": 0 + }, + { + "second": 16, + "successes": 4, + "errors": 0 + } + ], + "error_samples": [ + [ + 3.706847135999851, + "GET", + "GET /api/v1/chats/6b68ba79-cf18-4bf0-b907-46d8b3f8c3ac/messages: connection/TLS failure (TimeoutError)" + ], + [ + 3.7168416449999313, + "POST", + "POST /api/v1/chats/6b68ba79-cf18-4bf0-b907-46d8b3f8c3ac/messages: connection/TLS failure (TimeoutError)" + ], + [ + 3.7768836010000086, + "POST", + "POST /api/v1/chats/6b68ba79-cf18-4bf0-b907-46d8b3f8c3ac/messages: connection/TLS failure (TimeoutError)" + ], + [ + 3.848646371999621, + "POST", + "POST /api/v1/chats/6b68ba79-cf18-4bf0-b907-46d8b3f8c3ac/messages: connection/TLS failure (TimeoutError)" + ] + ], + "action": { + "id": "27e984eebdb76456c9f743366e95d6bc21d2b7df61da990d6d1f3dbe962a390d", + "instance": "27e984eebdb7", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:43:34.600947249Z", + "running": false, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + } + ] + } + }, + { + "label": "stop 330027f55a61", + "duration_seconds": 16.105, + "successful_requests": 1142, + "successful_writes": 572, + "errors": 4, + "successful_rps": 70.91, + "first_success_after_action_seconds": { + "POST": 0.044, + "GET": 0.003 + }, + "maximum_success_gap_seconds": { + "POST": 1.997, + "GET": 2.0 + }, + "action_start_seconds": 1.002, + "action_end_seconds": 2.183, + "p50_ms": 17.395, + "p95_ms": 64.873, + "confirmed_data_preserved": true, + "duplicate_messages": 0, + "instances": [ + "27e984eebdb7", + "330027f55a61" + ], + "per_second": [ + { + "second": 0, + "successes": 97, + "errors": 0 + }, + { + "second": 1, + "successes": 48, + "errors": 0 + }, + { + "second": 2, + "successes": 0, + "errors": 0 + }, + { + "second": 3, + "successes": 43, + "errors": 4 + }, + { + "second": 4, + "successes": 78, + "errors": 0 + }, + { + "second": 5, + "successes": 61, + "errors": 0 + }, + { + "second": 6, + "successes": 92, + "errors": 0 + }, + { + "second": 7, + "successes": 92, + "errors": 0 + }, + { + "second": 8, + "successes": 66, + "errors": 0 + }, + { + "second": 9, + "successes": 93, + "errors": 0 + }, + { + "second": 10, + "successes": 74, + "errors": 0 + }, + { + "second": 11, + "successes": 87, + "errors": 0 + }, + { + "second": 12, + "successes": 85, + "errors": 0 + }, + { + "second": 13, + "successes": 49, + "errors": 0 + }, + { + "second": 14, + "successes": 84, + "errors": 0 + }, + { + "second": 15, + "successes": 86, + "errors": 0 + }, + { + "second": 16, + "successes": 7, + "errors": 0 + } + ], + "error_samples": [ + [ + 3.4685388349998902, + "POST", + "POST /api/v1/chats/3e316e2b-1d2a-4aa0-9cad-76a63d088e94/messages: connection/TLS failure (TimeoutError)" + ], + [ + 3.4784699329998148, + "GET", + "GET /api/v1/chats/3e316e2b-1d2a-4aa0-9cad-76a63d088e94/messages: connection/TLS failure (TimeoutError)" + ], + [ + 3.507695892999891, + "GET", + "GET /api/v1/chats/3e316e2b-1d2a-4aa0-9cad-76a63d088e94/messages: connection/TLS failure (TimeoutError)" + ], + [ + 3.5460884039998746, + "GET", + "GET /api/v1/chats/3e316e2b-1d2a-4aa0-9cad-76a63d088e94/messages: connection/TLS failure (TimeoutError)" + ] + ], + "action": { + "id": "330027f55a61e2a1205fe2ad0eead1233bfbf16822bfb79650c17c416991e85a", + "instance": "330027f55a61", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:44:49.76330043Z", + "running": false, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + } + ] + } + } + ], + "rolling_update": { + "label": "sequential API replacement", + "duration_seconds": 30.186, + "successful_requests": 2148, + "successful_writes": 1075, + "errors": 8, + "successful_rps": 71.16, + "first_success_after_action_seconds": { + "POST": 0.016, + "GET": 0.012 + }, + "maximum_success_gap_seconds": { + "POST": 1.995, + "GET": 2.146 + }, + "action_start_seconds": 1.002, + "action_end_seconds": 27.178, + "p50_ms": 15.574, + "p95_ms": 46.361, + "confirmed_data_preserved": true, + "duplicate_messages": 0, + "instances": [ + "27e984eebdb7", + "330027f55a61", + "7311a0e8c865", + "e68fad5a7a8d" + ], + "per_second": [ + { + "second": 0, + "successes": 93, + "errors": 0 + }, + { + "second": 1, + "successes": 89, + "errors": 0 + }, + { + "second": 2, + "successes": 79, + "errors": 0 + }, + { + "second": 3, + "successes": 71, + "errors": 0 + }, + { + "second": 4, + "successes": 95, + "errors": 0 + }, + { + "second": 5, + "successes": 97, + "errors": 0 + }, + { + "second": 6, + "successes": 74, + "errors": 0 + }, + { + "second": 7, + "successes": 94, + "errors": 0 + }, + { + "second": 8, + "successes": 83, + "errors": 0 + }, + { + "second": 9, + "successes": 24, + "errors": 0 + }, + { + "second": 10, + "successes": 0, + "errors": 0 + }, + { + "second": 11, + "successes": 4, + "errors": 4 + }, + { + "second": 12, + "successes": 59, + "errors": 0 + }, + { + "second": 13, + "successes": 77, + "errors": 0 + }, + { + "second": 14, + "successes": 93, + "errors": 0 + }, + { + "second": 15, + "successes": 95, + "errors": 0 + }, + { + "second": 16, + "successes": 78, + "errors": 0 + }, + { + "second": 17, + "successes": 95, + "errors": 0 + }, + { + "second": 18, + "successes": 32, + "errors": 0 + }, + { + "second": 19, + "successes": 0, + "errors": 0 + }, + { + "second": 20, + "successes": 44, + "errors": 4 + }, + { + "second": 21, + "successes": 15, + "errors": 0 + }, + { + "second": 22, + "successes": 99, + "errors": 0 + }, + { + "second": 23, + "successes": 89, + "errors": 0 + }, + { + "second": 24, + "successes": 99, + "errors": 0 + }, + { + "second": 25, + "successes": 89, + "errors": 0 + }, + { + "second": 26, + "successes": 84, + "errors": 0 + }, + { + "second": 27, + "successes": 87, + "errors": 0 + }, + { + "second": 28, + "successes": 91, + "errors": 0 + }, + { + "second": 29, + "successes": 102, + "errors": 0 + }, + { + "second": 30, + "successes": 17, + "errors": 0 + } + ], + "error_samples": [ + [ + 11.229902201000186, + "GET", + "GET /api/v1/chats/46df2f93-da6e-4f05-8275-fd23bbbcba43/messages: connection/TLS failure (TimeoutError)" + ], + [ + 11.237144330999854, + "POST", + "POST /api/v1/chats/46df2f93-da6e-4f05-8275-fd23bbbcba43/messages: connection/TLS failure (TimeoutError)" + ], + [ + 11.293951601000117, + "GET", + "GET /api/v1/chats/46df2f93-da6e-4f05-8275-fd23bbbcba43/messages: connection/TLS failure (TimeoutError)" + ], + [ + 11.305793702999836, + "GET", + "GET /api/v1/chats/46df2f93-da6e-4f05-8275-fd23bbbcba43/messages: connection/TLS failure (TimeoutError)" + ], + [ + 20.286787328000173, + "POST", + "POST /api/v1/chats/46df2f93-da6e-4f05-8275-fd23bbbcba43/messages: connection/TLS failure (TimeoutError)" + ] + ], + "action": { + "before": [ + { + "id": "27e984eebdb76456c9f743366e95d6bc21d2b7df61da990d6d1f3dbe962a390d", + "instance": "27e984eebdb7", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:45:15.986136897Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + } + ] + }, + { + "id": "330027f55a61e2a1205fe2ad0eead1233bfbf16822bfb79650c17c416991e85a", + "instance": "330027f55a61", + "service": "api", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:45:42.5500506Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + } + ] + }, + { + "id": "c975208b61e656b210e69bfa8a4e30614c4f6dba569a3d8b2201b33aa88902ff", + "instance": "c975208b61e6", + "service": "cleanup", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:43:06.36017379Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + } + ] + }, + { + "id": "7b87f4779624fba0be45ec719a5e10f44b3ff9945f31209be7126727eda70e11", + "instance": "7b87f4779624", + "service": "lb", + "image": "sha256:3a819392f5a6af2a9203d1c63ff0feba74f0c940623a558511be06d7d85e361c", + "started_at": "2026-11-06T10:42:58.889107235Z", + "running": true, + "exit_code": 0, + "memory_bytes": 67108864, + "nano_cpus": 500000000, + "published_ports": { + "8080/tcp": [ + { + "HostIp": "127.0.0.1", + "HostPort": "37173" + } + ] + }, + "mounts": [ + { + "type": "bind", + "destination": "/usr/local/etc/haproxy/haproxy.cfg", + "name": null + } + ] + }, + { + "id": "063c7053cc6de8d8bd420035c6dcc18e7c76a3b46193b36ad28d3bbc61b047df", + "instance": "063c7053cc6d", + "service": "postgres", + "image": "sha256:f3bd19c606e442c3d7bdfa8002e03fe260a1023351e0ea4598032022b68dd6e3", + "started_at": "2026-11-06T10:43:57.661378667Z", + "running": true, + "exit_code": 0, + "memory_bytes": 536870912, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/var/lib/postgresql/data", + "name": "lab4-check-1ad8ecf540_postgres_data" + }, + { + "type": "bind", + "destination": "/run/secrets/postgres_password", + "name": null + } + ] + }, + { + "id": "d904e73b40a580ce85840f555f8196a30cf1ef87d08eb0895f8451f49867583b", + "instance": "d904e73b40a5", + "service": "s3", + "image": "sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a", + "started_at": "2026-11-06T10:44:07.500844488Z", + "running": true, + "exit_code": 0, + "memory_bytes": 268435456, + "nano_cpus": 500000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_config", + "name": null + }, + { + "type": "volume", + "destination": "/data", + "name": "36b03f64548f3d2ebc2d7b177c27df6bb13970ee7977a4bcf332e77cdaa119f9" + } + ] + }, + { + "id": "278b40cca5cac2cdd0f9277d5b50a95fe85d6e05102d6c9234b573dfd76b0726", + "instance": "278b40cca5ca", + "service": "s3-storage", + "image": "sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a", + "started_at": "2026-11-06T10:42:58.597351707Z", + "running": true, + "exit_code": 0, + "memory_bytes": 536870912, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/data", + "name": "lab4-check-1ad8ecf540_s3_data" + } + ] + }, + { + "id": "1e5c416e81b1cb9b31411f8a5999cd81769e2fcc70dbb9be5196bf227c0721b5", + "instance": "1e5c416e81b1", + "service": "valkey", + "image": "sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571", + "started_at": "2026-11-06T10:43:48.093254233Z", + "running": true, + "exit_code": 0, + "memory_bytes": 134217728, + "nano_cpus": 500000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/data", + "name": "lab4-check-1ad8ecf540_valkey_data" + } + ] + } + ], + "after": [ + { + "id": "e68fad5a7a8d4a491216849a294a7bc1bf842c90758888f3864f1159ca439dec", + "instance": "e68fad5a7a8d", + "service": "api", + "image": "sha256:c8960ea2adbe77df50a4e81d5a39cdde43c004ac67ba07023d54e3ae7ec6a02e", + "started_at": "2026-11-06T10:46:00.639591875Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + } + ] + }, + { + "id": "7311a0e8c8650438a5fea82b74f45cbeab3a4793db79499ebcbda3f10b44c620", + "instance": "7311a0e8c865", + "service": "api", + "image": "sha256:c8960ea2adbe77df50a4e81d5a39cdde43c004ac67ba07023d54e3ae7ec6a02e", + "started_at": "2026-11-06T10:46:09.728306391Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/cache_url", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + } + ] + }, + { + "id": "c975208b61e656b210e69bfa8a4e30614c4f6dba569a3d8b2201b33aa88902ff", + "instance": "c975208b61e6", + "service": "cleanup", + "image": "sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75", + "started_at": "2026-11-06T10:43:06.36017379Z", + "running": true, + "exit_code": 0, + "memory_bytes": 402653184, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_access_key_id", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/s3_secret_access_key", + "name": null + }, + { + "type": "bind", + "destination": "/run/secrets/database_url", + "name": null + } + ] + }, + { + "id": "7b87f4779624fba0be45ec719a5e10f44b3ff9945f31209be7126727eda70e11", + "instance": "7b87f4779624", + "service": "lb", + "image": "sha256:3a819392f5a6af2a9203d1c63ff0feba74f0c940623a558511be06d7d85e361c", + "started_at": "2026-11-06T10:42:58.889107235Z", + "running": true, + "exit_code": 0, + "memory_bytes": 67108864, + "nano_cpus": 500000000, + "published_ports": { + "8080/tcp": [ + { + "HostIp": "127.0.0.1", + "HostPort": "37173" + } + ] + }, + "mounts": [ + { + "type": "bind", + "destination": "/usr/local/etc/haproxy/haproxy.cfg", + "name": null + } + ] + }, + { + "id": "063c7053cc6de8d8bd420035c6dcc18e7c76a3b46193b36ad28d3bbc61b047df", + "instance": "063c7053cc6d", + "service": "postgres", + "image": "sha256:f3bd19c606e442c3d7bdfa8002e03fe260a1023351e0ea4598032022b68dd6e3", + "started_at": "2026-11-06T10:43:57.661378667Z", + "running": true, + "exit_code": 0, + "memory_bytes": 536870912, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/var/lib/postgresql/data", + "name": "lab4-check-1ad8ecf540_postgres_data" + }, + { + "type": "bind", + "destination": "/run/secrets/postgres_password", + "name": null + } + ] + }, + { + "id": "d904e73b40a580ce85840f555f8196a30cf1ef87d08eb0895f8451f49867583b", + "instance": "d904e73b40a5", + "service": "s3", + "image": "sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a", + "started_at": "2026-11-06T10:44:07.500844488Z", + "running": true, + "exit_code": 0, + "memory_bytes": 268435456, + "nano_cpus": 500000000, + "published_ports": {}, + "mounts": [ + { + "type": "bind", + "destination": "/run/secrets/s3_config", + "name": null + }, + { + "type": "volume", + "destination": "/data", + "name": "36b03f64548f3d2ebc2d7b177c27df6bb13970ee7977a4bcf332e77cdaa119f9" + } + ] + }, + { + "id": "278b40cca5cac2cdd0f9277d5b50a95fe85d6e05102d6c9234b573dfd76b0726", + "instance": "278b40cca5ca", + "service": "s3-storage", + "image": "sha256:49312939c00c01e5ee6afbd7d728b18027821d3764c35a797a72acd4fdf3296a", + "started_at": "2026-11-06T10:42:58.597351707Z", + "running": true, + "exit_code": 0, + "memory_bytes": 536870912, + "nano_cpus": 1000000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/data", + "name": "lab4-check-1ad8ecf540_s3_data" + } + ] + }, + { + "id": "1e5c416e81b1cb9b31411f8a5999cd81769e2fcc70dbb9be5196bf227c0721b5", + "instance": "1e5c416e81b1", + "service": "valkey", + "image": "sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571", + "started_at": "2026-11-06T10:43:48.093254233Z", + "running": true, + "exit_code": 0, + "memory_bytes": 134217728, + "nano_cpus": 500000000, + "published_ports": {}, + "mounts": [ + { + "type": "volume", + "destination": "/data", + "name": "lab4-check-1ad8ecf540_valkey_data" + } + ] + } + ] + } + }, + "passed": true +} diff --git a/evidence/lab4-checks.txt b/evidence/lab4-checks.txt new file mode 100644 index 0000000..a355e22 --- /dev/null +++ b/evidence/lab4-checks.txt @@ -0,0 +1,557 @@ +Command: ./scripts/check-docker.sh; project: lab4-check-1ad8ecf540 +Docker: 29.4.2 x86_64 CPUs=16 RAM=8019410944 +Local .env and secrets are ready; values are not printed + Image mtusi-messenger:lab4 Building +#1 [internal] load local bake definitions +#1 reading from stdin 585B done +#1 DONE 0.0s + +#2 [internal] load build definition from Dockerfile +#2 transferring dockerfile: 733B 0.1s done +#2 DONE 0.1s + +#3 [internal] load metadata for docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3 +#3 DONE 0.0s + +#4 [internal] load .dockerignore +#4 transferring context: 32B +#4 transferring context: 167B 0.0s done +#4 DONE 0.1s + +#5 [1/8] FROM docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3 +#5 resolve docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3 0.0s done +#5 DONE 0.0s + +#6 [internal] load build context +#6 transferring context: 1.01kB 0.1s done +#6 DONE 0.2s + +#7 [7/8] COPY migrations/ ./migrations/ +#7 CACHED + +#8 [2/8] WORKDIR /app +#8 CACHED + +#9 [3/8] COPY requirements.txt . +#9 CACHED + +#10 [4/8] RUN python -m pip install --no-cache-dir -r requirements.txt && python -m pip check +#10 CACHED + +#11 [5/8] RUN groupadd --gid 10001 app && useradd --uid 10001 --gid app --no-create-home app +#11 CACHED + +#12 [6/8] COPY src/ ./src/ +#12 CACHED + +#13 [8/8] COPY research/ ./research/ +#13 CACHED + +#14 exporting to image +#14 exporting layers done +#14 exporting manifest sha256:6f1ead7285b0b8ce31023565fd9947f9056fe386b4bb9d560cc374a859d57257 0.0s done +#14 exporting config sha256:c839d8ac2a7ee1b756f2be85e5d96c5503965c2119c85ebe1041b73b4db64133 0.0s done +#14 exporting attestation manifest sha256:51ddc135889d95e4ad77fc4d24e36cac6576bd4bdedda79ea78db5ea3418e74d 0.0s done +#14 exporting manifest list sha256:e2acb8a9a99c5e45c97ce6e8fb7b5e50b6309a353a33089bae1bc3a9da637b75 0.0s done +#14 naming to docker.io/library/mtusi-messenger:lab4 done +#14 unpacking to docker.io/library/mtusi-messenger:lab4 0.0s done +#14 DONE 0.2s + +#15 resolving provenance for metadata file +#15 DONE 0.0s + Image mtusi-messenger:lab4 Built + Network lab4-check-1ad8ecf540_default Creating + Network lab4-check-1ad8ecf540_default Created + Network lab4-check-1ad8ecf540_s3-internal Creating + Network lab4-check-1ad8ecf540_s3-internal Created + Volume lab4-check-1ad8ecf540_postgres_data Creating + Volume lab4-check-1ad8ecf540_postgres_data Created + Volume lab4-check-1ad8ecf540_valkey_data Creating + Volume lab4-check-1ad8ecf540_valkey_data Created + Volume lab4-check-1ad8ecf540_s3_data Creating + Volume lab4-check-1ad8ecf540_s3_data Created + Container lab4-check-1ad8ecf540-postgres-1 Creating + Container lab4-check-1ad8ecf540-valkey-1 Creating + Container lab4-check-1ad8ecf540-s3-storage-1 Creating + Container lab4-check-1ad8ecf540-valkey-1 Created + Container lab4-check-1ad8ecf540-s3-storage-1 Created + Container lab4-check-1ad8ecf540-s3-1 Creating + Container lab4-check-1ad8ecf540-postgres-1 Created + Container lab4-check-1ad8ecf540-migrate-1 Creating + Container lab4-check-1ad8ecf540-s3-1 Created + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Creating + Container lab4-check-1ad8ecf540-migrate-1 Created + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Created + Container lab4-check-1ad8ecf540-cleanup-1 Creating + Container lab4-check-1ad8ecf540-api-1 Creating + Container lab4-check-1ad8ecf540-api-2 Creating + Container lab4-check-1ad8ecf540-api-2 Created + Container lab4-check-1ad8ecf540-cleanup-1 Created + Container lab4-check-1ad8ecf540-api-1 Created + Container lab4-check-1ad8ecf540-lb-1 Creating + Container lab4-check-1ad8ecf540-lb-1 Created + Container lab4-check-1ad8ecf540-postgres-1 Starting + Container lab4-check-1ad8ecf540-valkey-1 Starting + Container lab4-check-1ad8ecf540-s3-storage-1 Starting + Container lab4-check-1ad8ecf540-s3-storage-1 Started + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-valkey-1 Started + Container lab4-check-1ad8ecf540-postgres-1 Started + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Starting + Container lab4-check-1ad8ecf540-migrate-1 Started + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Starting + Container lab4-check-1ad8ecf540-s3-1 Started + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Starting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Started + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-valkey-1 Waiting + Container lab4-check-1ad8ecf540-migrate-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Waiting + Container lab4-check-1ad8ecf540-migrate-1 Waiting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-valkey-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Exited + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Exited + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Exited + Container lab4-check-1ad8ecf540-cleanup-1 Starting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Exited + Container lab4-check-1ad8ecf540-api-1 Starting + Container lab4-check-1ad8ecf540-cleanup-1 Started + Container lab4-check-1ad8ecf540-api-1 Started + Container lab4-check-1ad8ecf540-api-2 Starting + Container lab4-check-1ad8ecf540-api-2 Started + Container lab4-check-1ad8ecf540-api-1 Waiting + Container lab4-check-1ad8ecf540-api-2 Waiting + Container lab4-check-1ad8ecf540-api-1 Healthy + Container lab4-check-1ad8ecf540-api-2 Healthy + Container lab4-check-1ad8ecf540-lb-1 Starting + Container lab4-check-1ad8ecf540-lb-1 Started +API ready through LB: 27e984eebdb7, 330027f55a61 +PASS: 2 real API containers, CPU/RAM limits, API non-root and no public ports; only LB published +Проверяем сервер: http://127.0.0.1:37173 +/mnt/c/Users/Арсен/Downloads/mtusi2026lab4/mtusi2026lab4/.venv/bin/python scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +/mnt/c/Users/Арсен/Downloads/mtusi2026lab4/mtusi2026lab4/.venv/bin/python tests/smoke.py --base-url "http://127.0.0.1:37173" +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. +test_chat_access (test_api.ApiTests.test_chat_access) ... ok +test_chat_pagination_and_cursor_owner (test_api.ApiTests.test_chat_pagination_and_cursor_owner) ... ok +test_cursor_cannot_be_used_for_another_chat_or_changed (test_api.ApiTests.test_cursor_cannot_be_used_for_another_chat_or_changed) ... ok +test_default_page_size (test_api.ApiTests.test_default_page_size) ... ok +test_duplicate_username (test_api.ApiTests.test_duplicate_username) ... ok +test_framework_errors_and_request_ids (test_api.ApiTests.test_framework_errors_and_request_ids) ... ok +test_identification_and_authentication_order (test_api.ApiTests.test_identification_and_authentication_order) ... ok +test_invalid_chat_members (test_api.ApiTests.test_invalid_chat_members) ... ok +test_invalid_chat_title (test_api.ApiTests.test_invalid_chat_title) ... ok +test_invalid_limits_and_cursors (test_api.ApiTests.test_invalid_limits_and_cursors) ... ok +test_invalid_message_fields (test_api.ApiTests.test_invalid_message_fields) ... ok +test_invalid_user_fields (test_api.ApiTests.test_invalid_user_fields) ... ok +test_malformed_json_and_encoding (test_api.ApiTests.test_malformed_json_and_encoding) ... ok +test_message_pagination_and_changing_limit (test_api.ApiTests.test_message_pagination_and_changing_limit) ... ok +test_unicode_and_text_preservation (test_api.ApiTests.test_unicode_and_text_preservation) ... ok +test_wrong_content_type (test_api.ApiTests.test_wrong_content_type) ... ok +test_access_and_authentication (test_attachments.AttachmentTests.test_access_and_authentication) ... ok +test_attachment_only_message_and_other_member (test_attachments.AttachmentTests.test_attachment_only_message_and_other_member) ... ok +test_chunked_limit_without_content_length (test_attachments.AttachmentTests.test_chunked_limit_without_content_length) ... ok +test_content_length_limit_before_body (test_attachments.AttachmentTests.test_content_length_limit_before_body) ... ok +test_corruption_and_mime_spoof (test_attachments.AttachmentTests.test_corruption_and_mime_spoof) ... ok +test_filename_rejected_before_storage (test_attachments.AttachmentTests.test_filename_rejected_before_storage) ... ok +test_foreign_and_unknown_attachment_ids (test_attachments.AttachmentTests.test_foreign_and_unknown_attachment_ids) ... ok +test_idempotency_includes_ordered_attachment_ids (test_attachments.AttachmentTests.test_idempotency_includes_ordered_attachment_ids) ... ok +test_invalid_attachment_lists (test_attachments.AttachmentTests.test_invalid_attachment_lists) ... ok +test_pixel_limit_before_decode (test_attachments.AttachmentTests.test_pixel_limit_before_decode) ... ok +test_png_and_jpeg_originals (test_attachments.AttachmentTests.test_png_and_jpeg_originals) ... ok +test_simultaneous_registration_of_one_username (test_concurrency.ConcurrencyTests.test_simultaneous_registration_of_one_username) ... ok +test_ten_clients_send_one_hundred_messages (test_concurrency.ConcurrencyTests.test_ten_clients_send_one_hundred_messages) ... ok +test_conflict_and_semantic_json_replay (test_idempotency.IdempotencyTests.test_conflict_and_semantic_json_replay) ... ok +test_key_format_and_missing_key (test_idempotency.IdempotencyTests.test_key_format_and_missing_key) ... ok +test_parallel_replay_across_replicas (test_idempotency.IdempotencyTests.test_parallel_replay_across_replicas) ... ok +test_replay_rechecks_session_and_access (test_idempotency.IdempotencyTests.test_replay_rechecks_session_and_access) ... ok +test_scope_is_user_and_chat (test_idempotency.IdempotencyTests.test_scope_is_user_and_chat) ... ok +test_logout_revokes_only_one_session (test_sessions.SessionTests.test_logout_revokes_only_one_session) ... ok +test_password_validation (test_sessions.SessionTests.test_password_validation) ... ok +test_sql_like_message_is_plain_text (test_sessions.SessionTests.test_sql_like_message_is_plain_text) ... ok +test_unicode_password_with_colon_and_private_response (test_sessions.SessionTests.test_unicode_password_with_colon_and_private_response) ... ok +test_wrong_password_and_basic_only_for_login (test_sessions.SessionTests.test_wrong_password_and_basic_only_for_login) ... ok + +---------------------------------------------------------------------- +Ran 39 tests in 14.272s + +OK +PASS: 10 clients sent 100 messages; history contains exactly 100 unique messages. + Container lab4-check-1ad8ecf540-postgres-1 Running + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-run-916abfabd827 Creating + Container lab4-check-1ad8ecf540-migrate-run-916abfabd827 Created + Container lab4-check-1ad8ecf540-postgres-1 Running + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-run-839efbaa362d Creating + Container lab4-check-1ad8ecf540-migrate-run-839efbaa362d Created +PASS: migrations only in one-shot service; repeated execution preserves data + Container lab4-check-1ad8ecf540-cleanup-1 Stopping + Container lab4-check-1ad8ecf540-cleanup-1 Stopped + Container lab4-check-1ad8ecf540-s3-storage-1 Running + Container lab4-check-1ad8ecf540-s3-1 Running + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-s3-bootstrap-run-c4dad425de35 Creating + Container lab4-check-1ad8ecf540-s3-bootstrap-run-c4dad425de35 Created + Container lab4-check-1ad8ecf540-s3-storage-1 Running + Container lab4-check-1ad8ecf540-s3-1 Running + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-s3-bootstrap-run-2610d032cce8 Creating + Container lab4-check-1ad8ecf540-s3-bootstrap-run-2610d032cce8 Created +PASS: private S3, limited credentials, isolated administration, repeated bootstrap +Stopped API: 27e984eebdb7 container=27e984eebdb76456c9f743366e95d6bc21d2b7df61da990d6d1f3dbe962a390d +API ready through LB: 330027f55a61 + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Starting + Container lab4-check-1ad8ecf540-migrate-1 Started + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Starting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Started + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-valkey-1 Waiting + Container lab4-check-1ad8ecf540-migrate-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-valkey-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Exited + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Exited + Container lab4-check-1ad8ecf540-api-1 Starting + Container lab4-check-1ad8ecf540-api-1 Started +API ready through LB: 27e984eebdb7, 330027f55a61 +PASS: original downloaded through another replica after stopping uploader +PASS: post-PUT DB failure recorded; cleanup protects fresh, active and ready uploads + Container lab4-check-1ad8ecf540-s3-1 Stopping + Container lab4-check-1ad8ecf540-s3-1 Stopped + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Starting + Container lab4-check-1ad8ecf540-s3-1 Started +API ready through LB: 27e984eebdb7, 330027f55a61 +PASS: S3 outage gives API 503; recovery preserves original and session + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Starting + Container lab4-check-1ad8ecf540-migrate-1 Started + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Starting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Started + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Waiting + Container lab4-check-1ad8ecf540-migrate-1 Waiting + Container lab4-check-1ad8ecf540-migrate-1 Exited + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Exited + Container lab4-check-1ad8ecf540-cleanup-1 Starting + Container lab4-check-1ad8ecf540-cleanup-1 Started +PASS: 10 concurrent real PNG uploads; all checksums match; memory peaks: [105451520, 234598400] + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Starting + Container lab4-check-1ad8ecf540-migrate-1 Started + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Starting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Started + Container lab4-check-1ad8ecf540-migrate-1 Waiting + Container lab4-check-1ad8ecf540-valkey-1 Waiting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Waiting + Container lab4-check-1ad8ecf540-migrate-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-valkey-1 Healthy + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Exited + Container lab4-check-1ad8ecf540-migrate-1 Exited + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Exited + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Exited +/mnt/c/Users/Арсен/Downloads/mtusi2026lab4/mtusi2026lab4/.venv/bin/python tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:37173" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +PASS: both API, LB, PostgreSQL, Valkey, S3 and cleaner actually restarted; data and session preserved +PASS: SIGTERM with unfinished request: {"instance": "27e984eebdb7", "unfinished_request": true, "shutdown_seconds": 6.036, "new_connections_refused_seconds": 0.26, "exit_code": 0, "oom_killed": false} + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Starting + Container lab4-check-1ad8ecf540-migrate-1 Started + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Starting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Started + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-valkey-1 Waiting + Container lab4-check-1ad8ecf540-migrate-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-valkey-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Exited + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Exited + Container lab4-check-1ad8ecf540-api-1 Starting + Container lab4-check-1ad8ecf540-api-1 Started +API ready through LB: 27e984eebdb7, 330027f55a61 + Container lab4-check-1ad8ecf540-valkey-1 Stopping + Container lab4-check-1ad8ecf540-valkey-1 Stopped +PASS: valkey outage: API live=200, ready=503, LB ready=503 + Container lab4-check-1ad8ecf540-valkey-1 Starting + Container lab4-check-1ad8ecf540-valkey-1 Started +API ready through LB: 27e984eebdb7, 330027f55a61 + Container lab4-check-1ad8ecf540-postgres-1 Stopping + Container lab4-check-1ad8ecf540-postgres-1 Stopped +PASS: postgres outage: API live=200, ready=503, LB ready=503 + Container lab4-check-1ad8ecf540-postgres-1 Starting + Container lab4-check-1ad8ecf540-postgres-1 Started +API ready through LB: 27e984eebdb7, 330027f55a61 + Container lab4-check-1ad8ecf540-s3-1 Stopping + Container lab4-check-1ad8ecf540-s3-1 Stopped +PASS: s3 outage: API live=200, ready=503, LB ready=503 + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Starting + Container lab4-check-1ad8ecf540-s3-1 Started +API ready through LB: 27e984eebdb7, 330027f55a61 + Container lab4-check-1ad8ecf540-postgres-1 Paused + Container lab4-check-1ad8ecf540-postgres-1 Unpaused +PASS: paused PostgreSQL: SQL and direct readiness bounded; live works; unpause restores API without restart +/mnt/c/Users/Арсен/Downloads/mtusi2026lab4/mtusi2026lab4/.venv/bin/python tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:37173" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 113, "failed_attempts": 1, "first_recovery_seconds": 2.584} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Starting + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-migrate-1 Started + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Starting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Started + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-valkey-1 Waiting + Container lab4-check-1ad8ecf540-migrate-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-valkey-1 Healthy + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Exited + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Exited + Container lab4-check-1ad8ecf540-api-2 Starting + Container lab4-check-1ad8ecf540-api-2 Started +API ready through LB: 27e984eebdb7, 330027f55a61 +Stopped API: 27e984eebdb7 container=27e984eebdb76456c9f743366e95d6bc21d2b7df61da990d6d1f3dbe962a390d +{"label": "stop 27e984eebdb7", "duration_seconds": 16.032, "successful_requests": 1104, "successful_writes": 551, "errors": 4, "successful_rps": 68.86, "first_success_after_action_seconds": {"POST": 0.027, "GET": 0.026}, "maximum_success_gap_seconds": {"POST": 1.99, "GET": 1.937}, "action_start_seconds": 1.002, "action_end_seconds": 2.378, "p50_ms": 18.076, "p95_ms": 80.838, "confirmed_data_preserved": true, "duplicate_messages": 0, "instances": ["27e984eebdb7", "330027f55a61"]} + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Starting + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-migrate-1 Started + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Starting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Started + Container lab4-check-1ad8ecf540-valkey-1 Waiting + Container lab4-check-1ad8ecf540-migrate-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-valkey-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Exited + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Exited + Container lab4-check-1ad8ecf540-api-1 Starting + Container lab4-check-1ad8ecf540-api-1 Started +API ready through LB: 27e984eebdb7, 330027f55a61 +Stopped API: 330027f55a61 container=330027f55a61e2a1205fe2ad0eead1233bfbf16822bfb79650c17c416991e85a +{"label": "stop 330027f55a61", "duration_seconds": 16.105, "successful_requests": 1142, "successful_writes": 572, "errors": 4, "successful_rps": 70.91, "first_success_after_action_seconds": {"POST": 0.044, "GET": 0.003}, "maximum_success_gap_seconds": {"POST": 1.997, "GET": 2.0}, "action_start_seconds": 1.002, "action_end_seconds": 2.183, "p50_ms": 17.395, "p95_ms": 64.873, "confirmed_data_preserved": true, "duplicate_messages": 0, "instances": ["27e984eebdb7", "330027f55a61"]} + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-s3-storage-1 Waiting + Container lab4-check-1ad8ecf540-s3-storage-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Starting + Container lab4-check-1ad8ecf540-migrate-1 Started + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Starting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Started + Container lab4-check-1ad8ecf540-migrate-1 Waiting + Container lab4-check-1ad8ecf540-s3-1 Waiting + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-valkey-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-valkey-1 Healthy + Container lab4-check-1ad8ecf540-s3-1 Healthy + Container lab4-check-1ad8ecf540-migrate-1 Exited + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Exited + Container lab4-check-1ad8ecf540-api-2 Starting + Container lab4-check-1ad8ecf540-api-2 Started +API ready through LB: 27e984eebdb7, 330027f55a61 +Local .env and secrets are ready; values are not printed + Image mtusi-messenger:lab4 Building +#1 [internal] load local bake definitions +#1 reading from stdin 585B done +#1 DONE 0.0s + +#2 [internal] load build definition from Dockerfile +#2 transferring dockerfile: 733B 0.1s done +#2 DONE 0.1s + +#3 [internal] load metadata for docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3 +#3 DONE 0.0s + +#4 [internal] load .dockerignore +#4 transferring context: 167B 0.1s done +#4 DONE 0.1s + +#5 [1/8] FROM docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3 +#5 resolve docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3 0.0s done +#5 DONE 0.0s + +#6 [internal] load build context +#6 transferring context: 1.01kB 0.2s done +#6 DONE 0.2s + +#7 [2/8] WORKDIR /app +#7 CACHED + +#8 [3/8] COPY requirements.txt . +#8 CACHED + +#9 [5/8] RUN groupadd --gid 10001 app && useradd --uid 10001 --gid app --no-create-home app +#9 CACHED + +#10 [6/8] COPY src/ ./src/ +#10 CACHED + +#11 [4/8] RUN python -m pip install --no-cache-dir -r requirements.txt && python -m pip check +#11 CACHED + +#12 [7/8] COPY migrations/ ./migrations/ +#12 CACHED + +#13 [8/8] COPY research/ ./research/ +#13 CACHED + +#14 exporting to image +#14 exporting layers done +#14 exporting manifest sha256:6f1ead7285b0b8ce31023565fd9947f9056fe386b4bb9d560cc374a859d57257 done +#14 exporting config sha256:c839d8ac2a7ee1b756f2be85e5d96c5503965c2119c85ebe1041b73b4db64133 done +#14 exporting attestation manifest sha256:5f69eeb2680e0b86cd71ba190ceb53013d7a75aacb52c1ef47a8faf648169b03 0.0s done +#14 exporting manifest list sha256:c8960ea2adbe77df50a4e81d5a39cdde43c004ac67ba07023d54e3ae7ec6a02e +#14 exporting manifest list sha256:c8960ea2adbe77df50a4e81d5a39cdde43c004ac67ba07023d54e3ae7ec6a02e 0.0s done +#14 naming to docker.io/library/mtusi-messenger:lab4 done +#14 unpacking to docker.io/library/mtusi-messenger:lab4 0.0s done +#14 DONE 0.2s + +#15 resolving provenance for metadata file +#15 DONE 0.0s + Image mtusi-messenger:lab4 Built + Container lab4-check-1ad8ecf540-postgres-1 Running + Container lab4-check-1ad8ecf540-postgres-1 Waiting + Container lab4-check-1ad8ecf540-postgres-1 Healthy + Container lab4-check-1ad8ecf540-migrate-run-f258d2d53aaa Creating + Container lab4-check-1ad8ecf540-migrate-run-f258d2d53aaa Created +Migrations: already applied +API ready through LB: 27e984eebdb7, 330027f55a61 +Replacing API: 27e984eebdb7 + Container lab4-check-1ad8ecf540-api-2 Running + Container lab4-check-1ad8ecf540-api-3 Creating + Container lab4-check-1ad8ecf540-api-3 Created + Container lab4-check-1ad8ecf540-api-3 Starting + Container lab4-check-1ad8ecf540-api-3 Started +API ready through LB: 330027f55a61, e68fad5a7a8d +Replacing API: 330027f55a61 + Container lab4-check-1ad8ecf540-api-3 Running + Container lab4-check-1ad8ecf540-api-4 Creating + Container lab4-check-1ad8ecf540-api-4 Created + Container lab4-check-1ad8ecf540-api-4 Starting + Container lab4-check-1ad8ecf540-api-4 Started +API ready through LB: 7311a0e8c865, e68fad5a7a8d +PASS: all API containers replaced sequentially; stores and LB kept running +{"label": "sequential API replacement", "duration_seconds": 30.186, "successful_requests": 2148, "successful_writes": 1075, "errors": 8, "successful_rps": 71.16, "first_success_after_action_seconds": {"POST": 0.016, "GET": 0.012}, "maximum_success_gap_seconds": {"POST": 1.995, "GET": 2.146}, "action_start_seconds": 1.002, "action_end_seconds": 27.178, "p50_ms": 15.574, "p95_ms": 46.361, "confirmed_data_preserved": true, "duplicate_messages": 0, "instances": ["27e984eebdb7", "330027f55a61", "7311a0e8c865", "e68fad5a7a8d"]} +PASS: all lab4 grade-4 checks completed + Container lab4-check-1ad8ecf540-cleanup-1 Stopping + Container lab4-check-1ad8ecf540-lb-1 Stopping + Container lab4-check-1ad8ecf540-lb-1 Stopped + Container lab4-check-1ad8ecf540-lb-1 Removing + Container lab4-check-1ad8ecf540-lb-1 Removed + Container lab4-check-1ad8ecf540-api-3 Stopping + Container lab4-check-1ad8ecf540-api-4 Stopping + Container lab4-check-1ad8ecf540-api-4 Stopped + Container lab4-check-1ad8ecf540-api-4 Removing + Container lab4-check-1ad8ecf540-api-4 Removed + Container lab4-check-1ad8ecf540-api-3 Stopped + Container lab4-check-1ad8ecf540-api-3 Removing + Container lab4-check-1ad8ecf540-api-3 Removed + Container lab4-check-1ad8ecf540-valkey-1 Stopping + Container lab4-check-1ad8ecf540-valkey-1 Stopped + Container lab4-check-1ad8ecf540-valkey-1 Removing + Container lab4-check-1ad8ecf540-valkey-1 Removed + Container lab4-check-1ad8ecf540-cleanup-1 Stopped + Container lab4-check-1ad8ecf540-cleanup-1 Removing + Container lab4-check-1ad8ecf540-cleanup-1 Removed + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Stopping + Container lab4-check-1ad8ecf540-migrate-1 Stopping + Container lab4-check-1ad8ecf540-migrate-1 Stopped + Container lab4-check-1ad8ecf540-migrate-1 Removing + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Stopped + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Removing + Container lab4-check-1ad8ecf540-migrate-1 Removed + Container lab4-check-1ad8ecf540-postgres-1 Stopping + Container lab4-check-1ad8ecf540-s3-bootstrap-1 Removed + Container lab4-check-1ad8ecf540-s3-1 Stopping + Container lab4-check-1ad8ecf540-postgres-1 Stopped + Container lab4-check-1ad8ecf540-postgres-1 Removing + Container lab4-check-1ad8ecf540-postgres-1 Removed + Container lab4-check-1ad8ecf540-s3-1 Stopped + Container lab4-check-1ad8ecf540-s3-1 Removing + Container lab4-check-1ad8ecf540-s3-1 Removed + Container lab4-check-1ad8ecf540-s3-storage-1 Stopping + Container lab4-check-1ad8ecf540-s3-storage-1 Stopped + Container lab4-check-1ad8ecf540-s3-storage-1 Removing + Container lab4-check-1ad8ecf540-s3-storage-1 Removed + Network lab4-check-1ad8ecf540_default Removing + Volume lab4-check-1ad8ecf540_postgres_data Removing + Volume lab4-check-1ad8ecf540_s3_data Removing + Volume lab4-check-1ad8ecf540_valkey_data Removing + Network lab4-check-1ad8ecf540_s3-internal Removing + Volume lab4-check-1ad8ecf540_postgres_data Removed + Volume lab4-check-1ad8ecf540_s3_data Removed + Volume lab4-check-1ad8ecf540_valkey_data Removed + Network lab4-check-1ad8ecf540_default Removed + Network lab4-check-1ad8ecf540_s3-internal Removed +Removed only temporary test containers and volumes: lab4-check-1ad8ecf540 diff --git a/evidence/postgres-pause.json b/evidence/postgres-pause.json new file mode 100644 index 0000000..857b248 --- /dev/null +++ b/evidence/postgres-pause.json @@ -0,0 +1,76 @@ +{ + "utc": "2026-11-06T10:46:32.484122+00:00", + "project": "lab4-pg-pause-6c3e872952", + "command": ".venv/bin/python student-tests/postgres_pause.py", + "passed": true, + "sql_without_server_timeout": { + "elapsed_seconds": 2.0, + "connection_closed": true + }, + "direct_ready": { + "status": 503, + "elapsed_seconds": 2.012 + }, + "direct_live": { + "status": 200, + "elapsed_seconds": 0.008 + }, + "repeated_ready": [ + { + "status": 503, + "elapsed_seconds": 2.197 + }, + { + "status": 503, + "elapsed_seconds": 2.105 + }, + { + "status": 503, + "elapsed_seconds": 2.086 + }, + { + "status": 503, + "elapsed_seconds": 2.107 + }, + { + "status": 503, + "elapsed_seconds": 2.095 + }, + { + "status": 503, + "elapsed_seconds": 2.014 + }, + { + "status": 503, + "elapsed_seconds": 2.097 + }, + { + "status": 503, + "elapsed_seconds": 2.094 + }, + { + "status": 503, + "elapsed_seconds": 2.098 + }, + { + "status": 503, + "elapsed_seconds": 2.014 + } + ], + "ready_after_12_seconds": { + "status": 503, + "elapsed_seconds": 2.009 + }, + "live_after_repeated_requests": { + "status": 200, + "elapsed_seconds": 0.009 + }, + "paused_seconds": 14.918, + "recovered_ready": { + "status": 200, + "elapsed_seconds": 0.012 + }, + "recovery_seconds": 1.355, + "api_not_restarted": true, + "existing_session_and_message_preserved": true +} diff --git a/examples/requests.http b/examples/requests.http new file mode 100644 index 0000000..052497b --- /dev/null +++ b/examples/requests.http @@ -0,0 +1,53 @@ +# 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}} + +### Binary upload; HTTP file-client syntax for reading local fixture +POST {{baseUrl}}/api/v1/chats/{{chatId}}/attachments?filename=sample.png +Authorization: Bearer {{sessionToken}} +Content-Type: image/png + +< ../tests/fixtures/sample.png diff --git a/infra/README.md b/infra/README.md new file mode 100644 index 0000000..5a39e86 --- /dev/null +++ b/infra/README.md @@ -0,0 +1,7 @@ +# Инфраструктура студента + +Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли. + +В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд. + +Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику. diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg new file mode 100644 index 0000000..c39b8d5 --- /dev/null +++ b/infra/haproxy.cfg @@ -0,0 +1,40 @@ +global + log stdout format raw local0 + maxconn 256 + +defaults + mode http + log global + option dontlognull + option http-server-close + timeout connect 1s + timeout client 40s + timeout server 60s + timeout http-request 5s + timeout check 1s + retries 1 + +resolvers docker + nameserver dns 127.0.0.11:53 + accepted_payload_size 8192 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 1s + hold obsolete 1s + hold nx 1s + hold timeout 1s + hold refused 1s + hold other 1s + +frontend public + bind :8080 + default_backend api + +backend api + balance roundrobin + option httpchk + http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host localhost + http-check expect status 200 + default-server inter 1s fastinter 1s downinter 1s fall 2 rise 2 + server-template replica 10 api:8080 check resolvers docker resolve-prefer ipv4 init-addr none diff --git a/lab.json b/lab.json new file mode 100644 index 0000000..e9ffc9f --- /dev/null +++ b/lab.json @@ -0,0 +1,8 @@ +{ + "number": 4, + "title": "S3-хранилище и вложения", + "contract_version": "1.4.0", + "default_base_url": "http://localhost:8080", + "grading": "3; 4 includes 3; 5 includes 4 plus one completed research track", + "scaffold_has_application": false +} diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 0000000..9dfbb86 --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,30 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name varchar(100) NOT NULL CHECK (char_length(display_name) >= 1), + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title varchar(100) NOT NULL CHECK (char_length(title) >= 1), + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id uuid NOT NULL, + text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000 AND text !~ '^\s*$'), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id) +); +CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id); diff --git a/migrations/002_message_idempotency.sql b/migrations/002_message_idempotency.sql new file mode 100644 index 0000000..375b58c --- /dev/null +++ b/migrations/002_message_idempotency.sql @@ -0,0 +1,10 @@ +-- Добавочная миграция: существующие данные и таблицы lab2 сохраняются. +CREATE TABLE message_idempotency ( + user_id uuid NOT NULL REFERENCES users(id), + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + key varchar(128) NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'), + request_text text NOT NULL, + message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + expires_at timestamptz NOT NULL, + PRIMARY KEY (user_id, chat_id, key) +); diff --git a/migrations/003_attachments.sql b/migrations/003_attachments.sql new file mode 100644 index 0000000..5a9db48 --- /dev/null +++ b/migrations/003_attachments.sql @@ -0,0 +1,34 @@ +-- Только добавления к lab3; старые сообщения и ключи сохраняются. +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + owner_id uuid NOT NULL, + object_key text NOT NULL UNIQUE, + filename varchar(255) NOT NULL, + content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')), + size_bytes integer NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760), + sha256 char(64) NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY (chat_id, owner_id) REFERENCES chat_members(chat_id, user_id) +); +CREATE INDEX attachments_chat_idx ON attachments(chat_id); + +ALTER TABLE messages DROP CONSTRAINT messages_text_check; +ALTER TABLE messages ADD CONSTRAINT messages_text_check CHECK (char_length(text) <= 4000); +CREATE TABLE message_attachments ( + message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + attachment_id uuid NOT NULL REFERENCES attachments(id), + position integer NOT NULL CHECK (position BETWEEN 0 AND 9), + PRIMARY KEY (message_id, attachment_id), + UNIQUE (message_id, position) +); +ALTER TABLE message_idempotency + ADD COLUMN request_attachment_ids uuid[] NOT NULL DEFAULT '{}'; + +-- Фиксируется ДО S3 PUT. После COMMIT ready-метаданных удаляется атомарно с ними. +CREATE TABLE attachment_uploads ( + id uuid PRIMARY KEY, + object_key text NOT NULL UNIQUE, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX attachment_uploads_created_idx ON attachment_uploads(created_at); diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..6b103dd --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,2 @@ +# Only for full OpenAPI/JSON Schema validation; HTTP tests use stdlib. +openapi-spec-validator==0.7.2 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..2bb42d3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,36 @@ +# Основные библиотеки +fastapi==0.142.4 +uvicorn==0.54.0 +pydantic==2.13.5 + +# Их зависимости +annotated-doc==0.0.5 +annotated-types==0.8.0 +anyio==4.15.1 +click==8.5.0 +h11==0.16.0 +idna==3.20 +opentelemetry-api==1.45.1 +pydantic-core==2.46.5 +starlette==1.7.0 +typing-extensions==4.16.0 +typing-inspection==0.4.4 + +# PostgreSQL, сессии и Argon2id +psycopg[binary,pool]==3.3.6 +redis==8.1.0 +argon2-cffi==25.1.0 + +# Транзитивные зависимости новых библиотек +psycopg-binary==3.3.6 +psycopg-pool==3.3.3 +argon2-cffi-bindings==26.1.0 +cffi==2.1.1 +pycparser==3.11 + +# S3 и проверка настоящих PNG/JPEG (без изменения оригинала) +minio==7.2.20 +Pillow==13.0.0 +certifi==2026.10.23 +pycryptodome==4.3.0 +urllib3==2.8.0 diff --git a/research/README.md b/research/README.md new file mode 100644 index 0000000..956721c --- /dev/null +++ b/research/README.md @@ -0,0 +1,12 @@ +# Трек 2 на оценку 5 + +Запуск из корня: `./scripts/research.sh`. Нужны Docker Compose, Python 3 и интернет для первой сборки. Скрипт собирает API-образ и использует отдельный Compose project с новыми volumes. Текущий стенд не участвует. + +- run.py управляет контейнерами, pg_dump, pg_restore, файлами evidence и cleanup. +- benchmark.py выполняет SQL и сверку внутри API-образа. Перед заполнением требует пустую БД. Исследовательский флаг устанавливает только драйвер. + +Датасет: 100000 сообщений в 4 чатах (70000/20000/9000/1000). Сравниваются индекс chat_id и индекс (chat_id,created_at,id), по 3 повтора с одинаковыми ограничениями и записями. На каждый чат — страницы около 10/50/90%, один прогрев и пять измерений, 51 строка. Измеряется INSERT SELECT с COMMIT, WAL и размер индекса. EXPLAIN и основные цифры сохраняются в evidence. + +После dump создаётся ещё одно сообщение. Backup восстанавливается в другой контейнер и свежий volume. Сравниваются все счётчики, 12 полных записей и SHA-256 всех сообщений. Последующая запись ожидаемо отсутствует в восстановленном снимке. + +Файлы research.json, query-plans.json и research.txt обновляются автоматически. Dump остаётся в игнорируемом backups/. Временные исследовательские volumes удаляются после проверки. Методика, фактические результаты и ограничения лабораторной 2 описаны в [REPORT.lab2.md](../REPORT.lab2.md). diff --git a/research/__init__.py b/research/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/research/benchmark.py b/research/benchmark.py new file mode 100644 index 0000000..93b51fe --- /dev/null +++ b/research/benchmark.py @@ -0,0 +1,168 @@ +"""SQL-эксперимент запускается только в отдельном research Compose project.""" +from datetime import datetime, timedelta, timezone +import hashlib +import json +import os +import secrets +import statistics +import sys +import time +from uuid import UUID + +import psycopg +from psycopg.conninfo import make_conninfo +from psycopg.rows import dict_row + +from src import db, migrate, passwords +from src.config import secret + + +SIZES = [70000, 20000, 9000, 1000] +START = datetime(2026, 1, 1, tzinfo=timezone.utc) +QUERY = """SELECT * FROM messages WHERE chat_id=%s AND (created_at, id)>(%s, %s) + ORDER BY created_at, id LIMIT %s""" + + +def identifier(value): + return UUID(hashlib.md5(value.encode(), usedforsecurity=False).hexdigest()) + + +def connect(restored=False): + url = secret("DATABASE_URL") + if restored: + url = make_conninfo(url, host="postgres-restore") + return psycopg.connect(url, autocommit=True, row_factory=dict_row, + options="-c timezone=UTC -c statement_timeout=120000") + + +def snapshot(conn): + counts = {} + for table in ("users", "chats", "chat_members", "messages", "schema_migrations"): + # Имена таблиц — фиксированный список выше, не входные данные клиента. + counts[table] = conn.execute("SELECT count(*) AS n FROM " + table).fetchone()["n"] + digest = hashlib.sha256() + for row in conn.execute("SELECT * FROM messages ORDER BY id"): + digest.update((json.dumps(row, default=str, sort_keys=True, ensure_ascii=False) + "\n").encode()) + samples = [] + offset = 0 + for size in SIZES: + for number in (offset + 1, offset + size // 2, offset + size): + row = conn.execute("SELECT * FROM messages WHERE id=%s", (identifier(f"message:{number}"),)).fetchone() + samples.append(json.loads(json.dumps(row, default=str, sort_keys=True, ensure_ascii=False))) + offset += size + return {"counts": counts, "messages_sha256": digest.hexdigest(), "samples": samples} + + +def benchmark(): + db.pool.open(wait=True, timeout=15) + try: + migrate.apply() + finally: + db.pool.close() + results, plans = [], [] + with connect() as conn: + assert conn.execute("SELECT count(*) AS n FROM users").fetchone()["n"] == 0, "Research requires an empty database" + encoded = passwords.hash_password(secrets.token_urlsafe(24)) + for n in range(1, 11): + conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES(%s,%s,%s,%s)", + (identifier(f"user:{n}"), f"research_{n}", "Synthetic research user", encoded)) + for n in range(4): + chat = identifier(f"chat:{n}") + conn.execute("INSERT INTO chats(id,title) VALUES(%s,%s)", (chat, f"Research chat {n}")) + for user in (1, 2): + conn.execute("INSERT INTO chat_members(chat_id,user_id) VALUES(%s,%s)", (chat, identifier(f"user:{user}"))) + variants = [("chat_only", "chat_id"), ("history", "chat_id, created_at, id")] + for repeat in range(3): + order = variants if repeat % 2 == 0 else variants[::-1] + for variant, columns in order: + conn.execute("TRUNCATE messages") + conn.execute("DROP INDEX IF EXISTS messages_history_idx") + conn.execute("DROP INDEX IF EXISTS messages_chat_idx") + index = "messages_history_idx" if variant == "history" else "messages_chat_idx" + conn.execute("CREATE INDEX " + index + " ON messages (" + columns + ")") + lsn = conn.execute("SELECT pg_current_wal_insert_lsn() AS lsn").fetchone()["lsn"] + started = time.perf_counter() + conn.execute("""INSERT INTO messages(id,chat_id,sender_id,text,created_at) + SELECT md5('message:'||n)::uuid, + md5('chat:'||(CASE WHEN n<=70000 THEN 0 WHEN n<=90000 THEN 1 WHEN n<=99000 THEN 2 ELSE 3 END))::uuid, + md5('user:'||(1+n%2))::uuid, + 'Synthetic message '||n||' '||repeat('x',80), + timestamptz '2026-01-01 00:00:00+00' + n*interval '1 microsecond' + FROM generate_series(1,100000) AS n""") + insert_ms = (time.perf_counter() - started) * 1000 + wal = conn.execute("SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(), %s) AS bytes", (lsn,)).fetchone()["bytes"] + conn.execute("VACUUM (ANALYZE) messages") + index_bytes = conn.execute("SELECT pg_relation_size(%s::regclass) AS bytes", (index,)).fetchone()["bytes"] + result = {"variant": variant, "repeat": repeat + 1, "insert_100000_ms": insert_ms, + "wal_bytes": int(wal), "index_bytes": index_bytes, "queries": []} + offset = 0 + for chat, size in enumerate(SIZES): + for fraction in (0.1, 0.5, 0.9): + number = offset + int(size * fraction) + params = (identifier(f"chat:{chat}"), START + timedelta(microseconds=number), identifier(f"message:{number}"), 51) + conn.execute(QUERY, params).fetchall() # один прогрев именно этой страницы + times = [] + for _ in range(5): + started = time.perf_counter() + rows = conn.execute(QUERY, params).fetchall() + times.append((time.perf_counter() - started) * 1000) + assert len(rows) == 51 + plan = conn.execute("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + QUERY, params).fetchone()["QUERY PLAN"][0] + result["queries"].append({"chat_size": size, "position": fraction, "latency_ms": times, + "explain_execution_ms": plan["Execution Time"]}) + if repeat == 0: + plans.append({"variant": variant, "chat_size": size, "position": fraction, "plan": plan}) + offset += size + results.append(result) + # Последняя итерация заканчивается production-индексом history. + assert conn.execute("SELECT to_regclass('messages_history_idx') AS name").fetchone()["name"] + baseline = snapshot(conn) + assert baseline["counts"]["messages"] == 100000 + summary = {} + for variant, _ in variants: + trials = [row for row in results if row["variant"] == variant] + latencies = sorted(t for row in trials for q in row["queries"] for t in q["latency_ms"]) + summary[variant] = { + "insert_100000_median_ms": statistics.median(row["insert_100000_ms"] for row in trials), + "index_bytes": trials[-1]["index_bytes"], + "wal_bytes_median": statistics.median(row["wal_bytes"] for row in trials), + "queries": len(latencies), "errors": 0, "concurrency": 1, + "p50_ms": statistics.median(latencies), + "p95_ms": latencies[int(0.95 * (len(latencies) - 1))], + "p99_ms": latencies[int(0.99 * (len(latencies) - 1))], + "successful_sql_rps": len(latencies) / (sum(latencies) / 1000), + } + return {"postgres": conn.execute("SELECT version() AS version").fetchone()["version"], + "messages": 100000, "chat_sizes": SIZES, "repeats": 3, "warmup_per_case": 1, + "measurements_per_case": 5, "page_size": 51, "query": QUERY, + "summary": summary, "trials": results, "plans": plans, "snapshot": baseline} + + +def after_backup(): + with connect() as conn: + message_id = identifier("after-backup") + conn.execute("INSERT INTO messages(id,chat_id,sender_id,text) VALUES(%s,%s,%s,%s)", + (message_id, identifier("chat:0"), identifier("user:1"), "Committed AFTER backup")) + return {"id": str(message_id), "source_messages": conn.execute("SELECT count(*) AS n FROM messages").fetchone()["n"]} + + +def verify(): + expected = json.load(sys.stdin) + with connect(restored=True) as restored, connect() as source: + actual = snapshot(restored) + assert actual == expected, "Restored data differs from the snapshot" + marker = (identifier("after-backup"),) + assert restored.execute("SELECT 1 FROM messages WHERE id=%s", marker).fetchone() is None + assert source.execute("SELECT 1 FROM messages WHERE id=%s", marker).fetchone() is not None + return {"counts": actual["counts"], "messages_sha256": actual["messages_sha256"], + "samples_verified": len(actual["samples"]), "all_messages_match": True, + "after_backup_message_missing_in_restore": True, + "source_messages": source.execute("SELECT count(*) AS n FROM messages").fetchone()["n"]} + + +if __name__ == "__main__": + if os.environ.get("LAB2_RESEARCH") != "1": + raise SystemExit("Use ./scripts/research.sh: an isolated research database is required") + operation = sys.argv[1] if len(sys.argv) > 1 else "benchmark" + result = {"benchmark": benchmark, "after-backup": after_backup, "verify": verify}[operation]() + print(json.dumps(result, ensure_ascii=False, default=str)) diff --git a/research/run.py b/research/run.py new file mode 100644 index 0000000..33e0f0e --- /dev/null +++ b/research/run.py @@ -0,0 +1,99 @@ +"""Создаёт изолированный стенд, измеряет SQL, делает dump и restore; пишет реальные результаты.""" +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import platform +import subprocess +import sys +import time +from uuid import uuid4 + + +ROOT = Path(__file__).resolve().parents[1] +project = "lab2-research-" + uuid4().hex[:10] +env = dict(os.environ, COMPOSE_PROJECT_NAME=project) +command = ["docker", "compose", "--profile", "research"] + + +def compose(*args, stdin=None, stdout=subprocess.PIPE): + return subprocess.run([*command, *args], cwd=ROOT, env=env, input=stdin, + stdout=stdout, stderr=subprocess.PIPE, check=True, timeout=600) + + +def run_module(operation, stdin=None): + result = compose("run", "--rm", "--no-deps", "-T", "-e", "LAB2_RESEARCH=1", "api", "python", "-m", "research.benchmark", operation, stdin=stdin) + return json.loads(result.stdout) + + +def wait_database(service): + for _ in range(60): + cid = compose("ps", "-q", service).stdout.decode().strip() + state = subprocess.run(["docker", "inspect", "--format", "{{.State.Health.Status}}", cid], capture_output=True, text=True, check=True) + if state.stdout.strip() == "healthy": + return + time.sleep(1) + raise RuntimeError(service + " did not become healthy") + + +def main(): + evidence = ROOT / "evidence" + evidence.mkdir(exist_ok=True) + backups = ROOT / "backups" + backups.mkdir(exist_ok=True) + dump = backups / (project + ".dump") + metadata = {"utc": datetime.now(timezone.utc).isoformat(), "project": project, + "command": "./scripts/research.sh", "host": platform.system() + " " + platform.machine(), + "commit": subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True, text=True).stdout.strip() + " + working tree", + "postgres_limits": {"cpus": 1, "memory_mib": 512}, "api_runner_limits": {"cpus": 1, "memory_mib": 256}} + started = time.perf_counter() + try: + print("Research project:", project, flush=True) + compose("up", "-d", "postgres", "postgres-restore") + wait_database("postgres") + wait_database("postgres-restore") + print("Measuring two indexes on the same 100000 messages, three repeats...", flush=True) + result = run_module("benchmark") + plans = result.pop("plans") + (evidence / "query-plans.json").write_text(json.dumps(plans, ensure_ascii=False, indent=2)) + source_id = compose("ps", "-q", "postgres").stdout.decode().strip() + restore_id = compose("ps", "-q", "postgres-restore").stdout.decode().strip() + assert source_id != restore_id + for label, cid in (("source", source_id), ("restored", restore_id)): + inspected = json.loads(subprocess.run(["docker", "inspect", cid], capture_output=True, check=True).stdout)[0] + metadata[label] = {"container": cid, "image": inspected["Image"], + "volumes": [m["Name"] for m in inspected["Mounts"] if m["Type"] == "volume"]} + assert metadata["source"]["volumes"] != metadata["restored"]["volumes"] + metadata["docker"] = subprocess.run(["docker", "info", "--format", "{{.ServerVersion}} {{.Architecture}} CPUs={{.NCPU}} RAM={{.MemTotal}}"], capture_output=True, text=True, check=True).stdout.strip() + metadata["stats_after_queries"] = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{json .}}", source_id], capture_output=True, text=True, check=True).stdout.strip() + backup_started = time.perf_counter() + with dump.open("wb") as output: + compose("exec", "-T", "postgres", "pg_dump", "-U", "messenger", "-d", "messenger", "--format=custom", stdout=output) + backup_seconds = time.perf_counter() - backup_started + marker = run_module("after-backup") + restore_started = time.perf_counter() + # Dump подаётся через stdin, без вывода данных или credentials в журнал. + with dump.open("rb") as input_file: + subprocess.run([*command, "exec", "-T", "postgres-restore", "pg_restore", "-U", "messenger", "-d", "messenger", + "--exit-on-error", "--single-transaction", "--no-owner"], cwd=ROOT, env=env, stdin=input_file, + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, check=True, timeout=300) + restore_seconds = time.perf_counter() - restore_started + verification_started = time.perf_counter() + verification = run_module("verify", stdin=json.dumps(result["snapshot"]).encode()) + result.update(metadata) + result["backup"] = {"file": "backups/" + dump.name, "bytes": dump.stat().st_size, "seconds": backup_seconds} + result["restore"] = {"seconds": restore_seconds, "verification_seconds": time.perf_counter() - verification_started, + "verification": verification, "post_backup_insert": marker} + result["total_seconds"] = time.perf_counter() - started + (evidence / "research.json").write_text(json.dumps(result, ensure_ascii=False, indent=2)) + print(json.dumps(result["summary"], ensure_ascii=False, indent=2), flush=True) + print(f"PASS: backup {backup_seconds:.2f}s; restore {restore_seconds:.2f}s; 100000 messages, all hashes and 12 samples match", flush=True) + print("PASS: restored into a different container and fresh volume; one post-backup commit is absent as expected", flush=True) + print("Results: evidence/research.json, evidence/query-plans.json; dump stays outside Git in backups/", flush=True) + finally: + compose("down", "--volumes", "--timeout", "10") + print("Removed only temporary research project:", project, flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100644 index 0000000..0a0b999 --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$project_dir" +python3 scripts/init_local.py +docker compose build "$@" api diff --git a/scripts/check-docker.sh b/scripts/check-docker.sh new file mode 100644 index 0000000..435b9f8 --- /dev/null +++ b/scripts/check-docker.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$project_dir" +if [[ ! -x .venv/bin/python ]]; then + echo "Создай .venv и установи requirements.txt по REPORT.md" >&2 + exit 1 +fi +./scripts/build.sh +mkdir -p evidence +.venv/bin/python -u student-tests/docker_lifecycle.py 2>&1 | sed -E 's/[[:blank:]]+$//' | tee evidence/lab4-checks.txt diff --git a/scripts/check.sh b/scripts/check.sh new file mode 100644 index 0000000..90a608d --- /dev/null +++ b/scripts/check.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail + +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$project_dir" + +if [[ ! -x .venv/bin/python ]]; then + echo "Не хватает .venv" >&2 + echo "python3 -m venv .venv" >&2 + echo ".venv/bin/python -m pip install -r requirements.txt" >&2 + exit 1 +fi + +export BASE_URL="${BASE_URL:-http://localhost:8080}" +echo "Проверяем сервер: $BASE_URL" +make check test PYTHON="$project_dir/.venv/bin/python" BASE_URL="$BASE_URL" +.venv/bin/python -m unittest discover -s student-tests -v diff --git a/scripts/check_contract.py b/scripts/check_contract.py new file mode 100644 index 0000000..dcb34df --- /dev/null +++ b/scripts/check_contract.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Offline structural checks; full schema validation is a separate target.""" +import ast +import json +from pathlib import Path +import re + +ROOT = Path(__file__).resolve().parents[1] + +def main(): + lab = json.loads((ROOT/'lab.json').read_text())['number'] + spec = json.loads((ROOT/'contracts/openapi.json').read_text()) + assert spec['openapi']=='3.1.0' + assert spec['info']['version']=='1.%d.0'%lab + operation_ids = set() + def walk(value): + if isinstance(value,dict): + if '$ref' in value: + pointer = value['$ref'] + assert pointer.startswith('#/'), 'unexpected external reference' + target = spec + for part in pointer[2:].split('/'): + target = target[part.replace('~1','/').replace('~0','~')] + for v in value.values(): + walk(v) + elif isinstance(value,list): + for v in value: + walk(v) + walk(spec) + for route,methods in spec['paths'].items(): + placeholders = set(re.findall(r'\{([^}]+)\}',route)) + for method,op in methods.items(): + assert op['operationId'] not in operation_ids, 'duplicate operationId' + operation_ids.add(op['operationId']) + params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')} + assert placeholders==params, 'path parameter mismatch: '+route + for response in op['responses'].values(): + assert 'X-Request-Id' in response['headers'] + if lab>=3: + assert 'X-Instance-Id' in response['headers'] + assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2) + assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4) + for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')): + ast.parse(file.read_text(),filename=str(file)) + for file in ROOT.rglob('*.json'): + if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts): + continue + json.loads(file.read_text()) + for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'): + assert (ROOT/required).is_file(), 'missing '+required + print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.') + +if __name__=='__main__': + main() diff --git a/scripts/demo.sh b/scripts/demo.sh new file mode 100644 index 0000000..5d51128 --- /dev/null +++ b/scripts/demo.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +set -euo pipefail +base_url="${BASE_URL:-http://localhost:8080}" +suffix="$(date +%s)_$RANDOM" +# Только синтетические пароли; токены остаются в памяти shell и не выводятся. +password="Demo-password-$suffix" +register() { + local username="$1" display_name="$2" + jq -nc --arg u "$username" --arg d "$display_name" --arg p "$password" \ + '{username:$u, display_name:$d, password:$p}' | + curl -fsS -H 'Content-Type: application/json' --data-binary @- "$base_url/api/v1/users" | jq -er '.id' +} +login() { + curl -fsS -X POST -u "$1:$password" "$base_url/api/v1/auth/sessions" | jq -er '.token' +} +alice_id="$(register "alice_$suffix" Алиса)" +bob_id="$(register "bob_$suffix" Боб)" +alice_token="$(login "alice_$suffix")" +bob_token="$(login "bob_$suffix")" +chat_id="$(jq -nc --arg a "$alice_id" --arg b "$bob_id" '{title:"Учебный чат",member_ids:[$a,$b]}' | + curl -fsS -H "Authorization: Bearer $alice_token" -H 'Content-Type: application/json' \ + --data-binary @- "$base_url/api/v1/chats" | jq -er '.id')" +for token in "$alice_token" "$bob_token"; do + curl -fsS -H "Authorization: Bearer $token" -H 'Content-Type: application/json' \ + -H "Idempotency-Key: demo-$RANDOM-$RANDOM" \ + -d '{"text":"Привет из lab3! 👋"}' "$base_url/api/v1/chats/$chat_id/messages" | jq . +done +curl -fsS -H "Authorization: Bearer $bob_token" "$base_url/api/v1/chats/$chat_id/messages" | jq . diff --git a/scripts/init_local.py b/scripts/init_local.py new file mode 100644 index 0000000..f970193 --- /dev/null +++ b/scripts/init_local.py @@ -0,0 +1,57 @@ +"""Создаёт локальное окружение и secrets; существующие значения сохраняет.""" +from pathlib import Path +import json +import os +import re +import secrets +import shutil +from urllib.parse import quote + + +root = Path(__file__).resolve().parents[1] +if not (root / ".env").exists(): + shutil.copyfile(root / ".env.example", root / ".env") +directory = root / "secrets" +directory.mkdir(exist_ok=True, mode=0o700) +directory.chmod(0o700) +password_file = directory / "postgres_password" +if not password_file.exists(): + password_file.write_text(secrets.token_hex(24)) +password = password_file.read_text().strip() +values = { + "database_url": f"postgresql://messenger:{quote(password, safe='')}@postgres:5432/messenger", + "cache_url": "redis://valkey:6379/0", + "s3_root_user": "root-" + secrets.token_hex(8), + "s3_root_password": secrets.token_urlsafe(32), + "s3_access_key_id": "api-" + secrets.token_hex(8), + "s3_secret_access_key": secrets.token_urlsafe(32), +} +for name, value in values.items(): + path = directory / name + if not path.exists(): + path.write_text(value) +dotenv = dict(line.split("=", 1) for line in (root / ".env").read_text().splitlines() + if line.strip() and not line.lstrip().startswith("#") and "=" in line) +bucket = os.environ.get("S3_BUCKET", dotenv.get("S3_BUCKET", "messenger-attachments")) +if re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket) is None: + raise ValueError("Недопустимое имя S3 bucket") +def local_secret(name): + return (directory / name).read_text().strip() +config = {"accounts": [{"id": "messenger-api", "displayName": "messenger-api"}], "identities": [ + {"name": "bootstrap", "credentials": [{"accessKey": local_secret("s3_root_user"), + "secretKey": local_secret("s3_root_password")}], "actions": ["Admin"]}, + {"name": "messenger-api", "account": {"id": "messenger-api", "displayName": "messenger-api"}, + "credentials": [{"accessKey": local_secret("s3_access_key_id"), "secretKey": local_secret("s3_secret_access_key")}], + "actions": ["Read:" + bucket, "List:" + bucket, "Write:" + bucket + "/attachments/*"]}, +]} +config_file = directory / "s3_config" +encoded_config = json.dumps(config) +if not config_file.exists() or config_file.read_text() != encoded_config: + temporary = directory / "s3_config.tmp" + temporary.write_text(encoded_config) + temporary.chmod(0o444) + temporary.replace(config_file) +# Каталог 0700 защищает файлы на хосте; 0444 позволяет USER 10001 читать bind-mounted secret. +for name in ("postgres_password", "s3_config", *values): + (directory / name).chmod(0o444) +print("Local .env and secrets are ready; values are not printed") diff --git a/scripts/migrate.sh b/scripts/migrate.sh new file mode 100644 index 0000000..9f0bb21 --- /dev/null +++ b/scripts/migrate.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$project_dir" +./scripts/build.sh +docker compose run --rm migrate diff --git a/scripts/replicas.py b/scripts/replicas.py new file mode 100644 index 0000000..e9cfe3e --- /dev/null +++ b/scripts/replicas.py @@ -0,0 +1,90 @@ +"""Управление репликами только текущего Compose project через Docker CLI.""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import time +from urllib.request import urlopen + +ROOT = Path(__file__).resolve().parents[1] + + +def command(*args): + return subprocess.check_output(args, cwd=ROOT, text=True, timeout=120).strip() + + +def replicas(): + ids = command("docker", "compose", "ps", "-q", "api").split() + return json.loads(command("docker", "inspect", *ids)) if ids else [] + + +def base_url(): + config = json.loads(command("docker", "compose", "config", "--format", "json")) + port = config["services"]["lb"]["ports"][0]["published"] + return os.environ.get("BASE_URL", "http://127.0.0.1:" + str(port)).rstrip("/") + + +def wait_ready(): + url = base_url() + "/health/ready" + deadline = time.monotonic() + 90 + seen = set() + while time.monotonic() < deadline: + current = replicas() + expected = {info["Config"]["Hostname"] for info in current} + if expected and all(info["State"].get("Health", {}).get("Status") == "healthy" for info in current): + try: + with urlopen(url, timeout=2) as response: + if response.status == 200: + seen.add(response.headers.get("X-Instance-Id")) + if expected <= seen: + print("API ready through LB:", ", ".join(sorted(expected)), flush=True) + return + except OSError: + pass + time.sleep(0.2) + raise RuntimeError("Не все работающие API-реплики готовы через LB за 90 секунд") + + +def stop_one(): + target = os.environ.get("TARGET_INSTANCE_ID") + if not target: + raise RuntimeError("Задайте TARGET_INSTANCE_ID из X-Instance-Id") + current = replicas() + matches = [info for info in current if info["Config"]["Hostname"] == target] + if len(current) < 2 or len(matches) != 1: + raise RuntimeError("Нужны минимум две работающие реплики и ровно одна выбранная") + selected = matches[0] + command("docker", "stop", "--time", "8", selected["Id"]) + print("Stopped API:", target, "container=" + selected["Id"], flush=True) + + +def rolling(): + wait_ready() + originals = replicas() + count = len(originals) + if count < 2: + raise RuntimeError("Для поочерёдной замены нужны минимум две API-реплики") + for old in originals: + active = replicas() + healthy = [info for info in active if info["Id"] != old["Id"] + and info["State"].get("Health", {}).get("Status") == "healthy"] + if not healthy: + raise RuntimeError("Нет готовой реплики, которая продолжит обслуживать запросы") + print("Replacing API:", old["Config"]["Hostname"], flush=True) + command("docker", "stop", "--time", "8", old["Id"]) + command("docker", "rm", old["Id"]) + # --no-recreate сохраняет остальные процессы; Compose создаёт только недостающий. + command("docker", "compose", "up", "-d", "--no-deps", "--no-recreate", "--scale", f"api={count}", "api") + wait_ready() + assert len(replicas()) == count + final = replicas() + assert not ({info["Id"] for info in originals} & {info["Id"] for info in final}) + print("PASS: all API containers replaced sequentially; stores and LB kept running", flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["wait", "stop", "rolling"]) + action = parser.parse_args().action + {"wait": wait_ready, "stop": stop_one, "rolling": rolling}[action]() diff --git a/scripts/research.sh b/scripts/research.sh new file mode 100644 index 0000000..b4f8e34 --- /dev/null +++ b/scripts/research.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$project_dir" +./scripts/build.sh +mkdir -p evidence +python3 -u research/run.py 2>&1 | tee evidence/research.txt diff --git a/scripts/restart.example.sh b/scripts/restart.example.sh new file mode 100644 index 0000000..967e951 --- /dev/null +++ b/scripts/restart.example.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +# TODO: copy to restart.sh and implement using YOUR compose/stack services. +# Restart API and ALL used state stores (DB, sessions, S3, broker as applicable). +# Preserve persistent volumes and schema/data; never down -v / flush / re-seed. +# Allow operator unseal if required in lab7; do not print credentials. +# Exit 0 only after the intended action; test waits for API readiness separately. +printf '%s +' 'TODO: implement restart.sh for your infrastructure' >&2 +exit 2 diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 0000000..5b9c85b --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$project_dir" +docker compose restart --timeout 8 postgres valkey s3-storage s3 api lb cleanup +./scripts/wait-ready.sh diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh new file mode 100644 index 0000000..b5b225f --- /dev/null +++ b/scripts/rolling-update.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$project_dir" +# Сначала собираем образ и применяем только обратно совместимые миграции. +./scripts/migrate.sh +exec python3 scripts/replicas.py rolling diff --git a/scripts/run-local.sh b/scripts/run-local.sh new file mode 100644 index 0000000..1c0b0e7 --- /dev/null +++ b/scripts/run-local.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +# Локальный стенд: HAProxy, две API-реплики, PostgreSQL и Valkey. +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +exec "$project_dir/scripts/start.sh" diff --git a/scripts/start.sh b/scripts/start.sh new file mode 100644 index 0000000..653502b --- /dev/null +++ b/scripts/start.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$project_dir" +python3 scripts/init_local.py +docker compose up -d --build lb cleanup +./scripts/wait-ready.sh diff --git a/scripts/stop-one.example.sh b/scripts/stop-one.example.sh new file mode 100644 index 0000000..ae149e8 --- /dev/null +++ b/scripts/stop-one.example.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +# TODO: copy to stop-one.sh, map TARGET_INSTANCE_ID to ONE API container/task. +# Stop that instance and leave it stopped; no stop of DB/LB/volumes. +# Return quickly (within 10 s); the test sends requests during this script. +# Restore the replica explicitly after the test. Never print credentials. +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +printf '%s +' 'TODO: implement stop-one.sh for your infrastructure' >&2 +exit 2 diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 0000000..b77ec3f --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$project_dir" +exec python3 scripts/replicas.py stop diff --git a/scripts/stop.sh b/scripts/stop.sh new file mode 100644 index 0000000..7dfffac --- /dev/null +++ b/scripts/stop.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$project_dir" +docker compose down --timeout 10 +echo "Контейнеры удалены; именованные volumes сохранены" diff --git a/scripts/validate_openapi.py b/scripts/validate_openapi.py new file mode 100644 index 0000000..1dfe4a9 --- /dev/null +++ b/scripts/validate_openapi.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""Full OpenAPI and JSON Schema checks; install requirements-dev.txt first.""" +import json +from pathlib import Path +from openapi_spec_validator import validate +from jsonschema import Draft202012Validator + +root = Path(__file__).resolve().parents[1] +spec = json.loads((root/'contracts/openapi.json').read_text()) +validate(spec) +from referencing import Registry, Resource +# The base URI resolves local #/components references inside examples. +resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'}) +registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource)) +for name, example in json.loads((root/'contracts/examples.json').read_text()).items(): + schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name} + Draft202012Validator(schema, registry=registry).validate(example) +for path in (root/'contracts').glob('*.schema.json'): + schema = json.loads(path.read_text()) + Draft202012Validator.check_schema(schema) + for example in schema.get('examples',[]): + Draft202012Validator(schema).validate(example) +print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.') diff --git a/scripts/wait-ready.sh b/scripts/wait-ready.sh new file mode 100644 index 0000000..da08577 --- /dev/null +++ b/scripts/wait-ready.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$project_dir" +exec python3 scripts/replicas.py wait diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/__main__.py b/src/__main__.py new file mode 100644 index 0000000..420cbd4 --- /dev/null +++ b/src/__main__.py @@ -0,0 +1,16 @@ +"""Общий запуск""" + +import os + +import uvicorn + + +if __name__ == "__main__": + uvicorn.run( + "src.app:app", + host=os.environ.get("APP_HOST", "0.0.0.0"), + port=int(os.environ.get("APP_PORT", "8080")), + workers=1, + access_log=False, + timeout_graceful_shutdown=5, + ) diff --git a/src/app.py b/src/app.py new file mode 100644 index 0000000..5c82517 --- /dev/null +++ b/src/app.py @@ -0,0 +1,180 @@ +"""HTTP-адреса, определение пользователя и обработка запросов""" + +from contextlib import asynccontextmanager +import json +import logging +import re +from time import perf_counter +from uuid import UUID, uuid4 +from urllib.parse import quote + +from fastapi import FastAPI, Request, Response +from fastapi.responses import StreamingResponse +from starlette.concurrency import run_in_threadpool +from fastapi.exceptions import RequestValidationError +from starlette.exceptions import HTTPException + +from src import attachments, auth, db, migrate, object_store, passwords, storage +from src.errors import ApiError, error_response +from src.models import CreateChat, CreateMessage, CreateUser +from src.config import INSTANCE_ID + + +@asynccontextmanager +async def lifespan(app): + await run_in_threadpool(db.pool.open, wait=True, timeout=15) + try: + await run_in_threadpool(migrate.check) + yield + finally: + await run_in_threadpool(db.pool.close) + + +app = FastAPI(title="Учебный мессенджер", redirect_slashes=False, lifespan=lifespan) +logger = logging.getLogger("uvicorn.error") + + +@app.middleware("http") +async def handle_request(request: Request, call_next): + request.state.request_id = str(uuid4()) + started = perf_counter() + path = request.url.path + try: + is_registration = request.method == "POST" and path == "/api/v1/users" + is_login = request.method == "POST" and path == "/api/v1/auth/sessions" + is_upload = request.method == "POST" and re.fullmatch(r"/api/v1/chats/[^/]+/attachments", path) + if is_login: + request.state.user = await run_in_threadpool(auth.basic_user, request.headers.get("Authorization")) + if await request.body(): + raise ApiError(400, "invalid_request", "Вход через Basic не принимает тело запроса") + elif path.startswith("/api/v1/") and not is_registration: + request.state.user = await run_in_threadpool(auth.current_user, request.headers.get("Authorization")) + if request.method == "POST" and path.startswith("/api/v1/") and not is_login and not is_upload: + content_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type != "application/json": + raise ApiError(415, "unsupported_media_type", "Ожидается application/json") + try: + json.loads((await request.body()).decode("utf-8")) + except (ValueError, RecursionError): + raise ApiError(400, "invalid_request", "Ожидается корректный JSON в UTF-8") + response = await call_next(request) + except ApiError as error: + response = error_response(request, error) + except Exception as error: + # Не печатаем тело запроса или текст исключения: там могут быть сообщения. + logger.error("%s request_id=%s", type(error).__name__, request.state.request_id) + response = error_response(request, ApiError(500, "internal_error", "Внутренняя ошибка сервера")) + response.headers["X-Request-Id"] = request.state.request_id + response.headers["X-Instance-Id"] = INSTANCE_ID + logger.info( + "%s %s status=%s duration_ms=%.2f request_id=%s", + request.method, path, response.status_code, + (perf_counter() - started) * 1000, request.state.request_id, + ) + return response + + +@app.exception_handler(ApiError) +def handle_api_error(request: Request, error: ApiError): + return error_response(request, error) + + +@app.exception_handler(RequestValidationError) +def handle_validation_error(request: Request, error: RequestValidationError): + # Контракт требует 400 и наш формат ошибки, а не стандартный ответ FastAPI. + return error_response(request, ApiError(400, "invalid_request", "Неверные поля или параметры запроса")) + + +@app.exception_handler(HTTPException) +def handle_http_error(request: Request, error: HTTPException): + code = "not_found" if error.status_code == 404 else "invalid_request" + message = "Адрес не найден" if error.status_code == 404 else "Недопустимый HTTP-запрос" + response = error_response(request, ApiError(error.status_code, code, message)) + if error.headers: + response.headers.update(error.headers) + return response + + +@app.get("/health/live") +def health_live(): + return {"status": "ok"} + + +@app.get("/health/ready") +def health_ready(): + db.ready() + auth.ready() + object_store.ready() + return {"status": "ok"} + + +@app.post("/api/v1/users", status_code=201) +def create_user(data: CreateUser): + return storage.create_user(data.username, data.display_name, passwords.hash_password(data.password)) + + +@app.get("/api/v1/users/me") +def current_user(request: Request): + return request.state.user + + +@app.post("/api/v1/chats", status_code=201) +def create_chat(request: Request, data: CreateChat): + return storage.create_chat(request.state.user["id"], data.title, data.member_ids) + + +@app.get("/api/v1/chats") +def list_chats(request: Request, limit: str = "50", cursor: str | None = None): + user_id = request.state.user["id"] + return storage.list_chats(user_id, limit, cursor) + + +@app.get("/api/v1/chats/{chat_id}") +def get_chat(request: Request, chat_id: UUID): + return storage.get_chat(request.state.user["id"], str(chat_id)) + + +@app.post("/api/v1/chats/{chat_id}/messages", status_code=201) +def create_message(request: Request, chat_id: UUID, data: CreateMessage): + keys = request.headers.getlist("Idempotency-Key") + if len(keys) != 1 or re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", keys[0]) is None: + raise ApiError(400, "invalid_request", "Нужен Idempotency-Key: 1–128 символов ASCII [A-Za-z0-9._:-]") + return storage.create_message(request.state.user["id"], str(chat_id), data.text, keys[0], data.attachment_ids) + + +@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201) +async def upload_attachment(request: Request, chat_id: UUID, filename: str): + return await attachments.upload(request, str(chat_id), filename) + + +@app.get("/api/v1/attachments/{attachment_id}") +def get_attachment(request: Request, attachment_id: UUID): + return attachments.public_attachment(attachments.find(request.state.user["id"], str(attachment_id))) + + +@app.get("/api/v1/attachments/{attachment_id}/content") +def download_attachment(request: Request, attachment_id: UUID, variant: str = "original"): + row = attachments.find(request.state.user["id"], str(attachment_id)) + if variant != "original": + raise ApiError(404, "not_found", "Вариант вложения не найден") + response = object_store.get(row["object_key"]) + return StreamingResponse(attachments.chunks(response), media_type=row["content_type"], headers={ + "Content-Length": str(row["size_bytes"]), "X-Content-Type-Options": "nosniff", + "Content-Disposition": "attachment; filename*=UTF-8''" + quote(row["filename"], safe=""), + }) + + +@app.get("/api/v1/chats/{chat_id}/messages") +def list_messages(request: Request, chat_id: UUID, limit: str = "50", cursor: str | None = None): + return storage.list_messages(request.state.user["id"], str(chat_id), limit, cursor) + + +@app.post("/api/v1/auth/sessions", status_code=201) +def create_session(request: Request): + return auth.create_session(request.state.user) + + +@app.delete("/api/v1/auth/sessions/current", status_code=204) +def delete_session(request: Request): + auth.logout(request.headers.get("Authorization")) + return Response(status_code=204) diff --git a/src/attachments.py b/src/attachments.py new file mode 100644 index 0000000..d025efa --- /dev/null +++ b/src/attachments.py @@ -0,0 +1,147 @@ +"""Синхронная загрузка: ограниченный поток -> проверка -> журнал -> S3 -> COMMIT.""" +import asyncio +import hashlib +import os +from tempfile import TemporaryFile +import unicodedata +from uuid import UUID, uuid4 +import warnings + +from PIL import Image, UnidentifiedImageError +from starlette.concurrency import run_in_threadpool +from starlette.requests import ClientDisconnect + +from src import db, object_store, storage +from src.errors import ApiError + + +MAX_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760")) +MAX_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000")) +if not 1 <= MAX_BYTES <= 10485760 or not 1 <= MAX_PIXELS <= 40000000: + raise ValueError("Лимиты загрузки должны быть положительными и не превышать контракт") +Image.MAX_IMAGE_PIXELS = MAX_PIXELS +warnings.filterwarnings("error", category=Image.DecompressionBombWarning) +# Максимум одно полное декодирование на реплику, независимо от числа клиентов. +upload_slot = asyncio.Semaphore(1) + + +def public_attachment(row): + return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]), + "filename": row["filename"], "content_type": row["content_type"], + "size_bytes": row["size_bytes"], "sha256": row["sha256"], "status": "ready", + "variants": [], "error_code": None, "created_at": storage.utc(row["created_at"]), + "updated_at": storage.utc(row["created_at"])} + + +def validate_filename(filename): + if not 1 <= len(filename) <= 255 or not filename.strip() or any( + char in "/\\" or unicodedata.category(char) == "Cc" for char in filename + ): + raise ApiError(400, "invalid_request", "Недопустимое имя файла") + try: + filename.encode("utf-8") + except UnicodeError: + raise ApiError(400, "invalid_request", "Недопустимое имя файла") from None + + +def validate_image(file, declared_type): + try: + file.seek(0) + with Image.open(file, formats=["PNG", "JPEG"]) as image: + true_type = {"PNG": "image/png", "JPEG": "image/jpeg"}[image.format] + if image.width * image.height > MAX_PIXELS: + raise ApiError(413, "payload_too_large", "Слишком много пикселей") + if true_type != declared_type: + raise ApiError(415, "unsupported_media_type", "MIME не совпадает с содержимым") + image.verify() + # verify проверяет структуру/CRC, load дополнительно обнаруживает обрыв pixel data. + file.seek(0) + with Image.open(file, formats=["PNG", "JPEG"]) as image: + image.load() + return true_type + except (Image.DecompressionBombError, Image.DecompressionBombWarning): + raise ApiError(413, "payload_too_large", "Слишком много пикселей") from None + except (UnidentifiedImageError, OSError, ValueError, SyntaxError): + raise ApiError(415, "unsupported_media_type", "Повреждённый PNG/JPEG или другой формат") from None + + +def lock_upload(conn, key, blocking=True): + function = "pg_advisory_xact_lock" if blocking else "pg_try_advisory_xact_lock" + return conn.execute(f"SELECT {function}(hashtextextended(%s, 4)) AS locked", (key,)).fetchone()["locked"] + + +def save(user_id, chat_id, filename, content_type, file, size, sha256): + attachment_id = uuid4() + key = "attachments/" + attachment_id.hex + # Даже при kill -9 после PUT остаётся долговечное намерение для cleaner. + with db.connection() as conn: + storage.require_member(conn, user_id, chat_id) + conn.execute("INSERT INTO attachment_uploads(id, object_key) VALUES (%s, %s)", (attachment_id, key)) + with db.connection() as conn: + conn.execute("SET LOCAL idle_in_transaction_session_timeout='30s'") + lock_upload(conn, key) + if not conn.execute("SELECT 1 FROM attachment_uploads WHERE id=%s", (attachment_id,)).fetchone(): + raise ApiError(503, "unavailable", "Загрузка больше не активна") + object_store.put(key, file, size, content_type) + row = conn.execute("""INSERT INTO attachments(id, chat_id, owner_id, object_key, filename, + content_type, size_bytes, sha256) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) RETURNING *""", + (attachment_id, UUID(chat_id), UUID(user_id), key, filename, content_type, size, sha256)).fetchone() + conn.execute("DELETE FROM attachment_uploads WHERE id=%s", (attachment_id,)) + result = public_attachment(row) + # Ответ только после успешного COMMIT; при неопределённом исходе ничего не удаляем. + return result + + +async def upload(request, chat_id, filename): + user_id = request.state.user["id"] + await run_in_threadpool(storage.get_chat, user_id, chat_id) + validate_filename(filename) + content_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if content_type not in {"image/png", "image/jpeg"}: + raise ApiError(415, "unsupported_media_type", "Ожидаются сырые bytes PNG/JPEG") + length = request.headers.get("Content-Length") + if length is not None: + if not length.isascii() or not length.isdecimal(): + raise ApiError(400, "invalid_request", "Неверный Content-Length") + if len(length) > 10 or int(length) > MAX_BYTES: + raise ApiError(413, "payload_too_large", "Файл больше допустимого размера") + try: + await asyncio.wait_for(upload_slot.acquire(), timeout=20) + except TimeoutError: + raise ApiError(503, "unavailable", "Загрузки заняты; повторите позднее") from None + try: + with TemporaryFile() as file: + size = 0 + digest = hashlib.sha256() + try: + async with asyncio.timeout(30): + async for chunk in request.stream(): + size += len(chunk) + if size > MAX_BYTES: + raise ApiError(413, "payload_too_large", "Файл больше допустимого размера") + digest.update(chunk) + await run_in_threadpool(file.write, chunk) + except (TimeoutError, ClientDisconnect): + raise ApiError(400, "invalid_request", "Загрузка прервана или истёк таймаут") from None + true_type = await run_in_threadpool(validate_image, file, content_type) + return await run_in_threadpool(save, user_id, chat_id, filename, true_type, file, size, digest.hexdigest()) + finally: + upload_slot.release() + + +def find(user_id, attachment_id): + with db.connection() as conn: + row = conn.execute("""SELECT a.* FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id + WHERE a.id=%s AND m.user_id=%s""", (UUID(attachment_id), UUID(user_id))).fetchone() + if row is None: + raise ApiError(404, "not_found", "Вложение не найдено") + return row + + +def chunks(response): + try: + while chunk := response.read(65536): + yield chunk + finally: + response.close() + response.release_conn() diff --git a/src/auth.py b/src/auth.py new file mode 100644 index 0000000..a8db643 --- /dev/null +++ b/src/auth.py @@ -0,0 +1,95 @@ +"""Basic только для входа; Bearer-сессии с TTL и AOF находятся в Valkey.""" +import base64 +import binascii +from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +import hashlib +import json +import secrets + +import redis + +from src import passwords, storage +from src.config import SESSION_TTL, secret +from src.errors import ApiError + + +sessions = redis.Redis.from_url( + secret("CACHE_URL"), decode_responses=True, + socket_connect_timeout=0.5, socket_timeout=0.5, max_connections=10, + retry=redis.retry.Retry(redis.backoff.NoBackoff(), 0), +) + + +@contextmanager +def available(): + try: + yield + except redis.RedisError: + raise ApiError(503, "unavailable", "Valkey временно недоступен") from None + + +def unauthorized(basic=False): + challenge = 'Basic realm="messenger", charset="UTF-8"' if basic else 'Bearer realm="messenger"' + return ApiError(401, "unauthorized", "Неверная или отсутствующая идентификация", {"WWW-Authenticate": challenge}) + + +def credential(header, scheme): + parts = (header or "").split() + if len(parts) != 2 or parts[0].lower() != scheme.lower(): + raise unauthorized(scheme == "Basic") + return parts[1] + + +def basic_user(header): + value = credential(header, "Basic") + try: + decoded = base64.b64decode(value, validate=True).decode("utf-8") + username, password = decoded.split(":", 1) + except (ValueError, UnicodeError, binascii.Error): + raise unauthorized(True) from None + user = storage.find_login(username) + if user is None or not passwords.matches(user["password_hash"], password): + raise unauthorized(True) + return storage.public_user(user) + + +def session_key(token): + return "session:" + hashlib.sha256(token.encode()).hexdigest() + + +def create_session(user): + token = secrets.token_urlsafe(32) + expires = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL) + value = {"user_id": user["id"], "expires_at": storage.utc(expires)} + with available(): + sessions.set(session_key(token), json.dumps(value), ex=SESSION_TTL) + return {"token": token, "token_type": "Bearer", "expires_at": value["expires_at"], "user": user} + + +def current_user(header): + token = credential(header, "Bearer") + with available(): + value = sessions.get(session_key(token)) + if value is None: + raise unauthorized() + data = json.loads(value) + if datetime.fromisoformat(data["expires_at"].replace("Z", "+00:00")) <= datetime.now(timezone.utc): + raise unauthorized() + user = storage.find_user(data["user_id"]) + if user is None: + raise unauthorized() + return user + + +def logout(header): + token = credential(header, "Bearer") + with available(): + removed = sessions.delete(session_key(token)) + if not removed: + raise unauthorized() + + +def ready(): + with available(): + sessions.ping() diff --git a/src/bootstrap_s3.py b/src/bootstrap_s3.py new file mode 100644 index 0000000..254c6fe --- /dev/null +++ b/src/bootstrap_s3.py @@ -0,0 +1,38 @@ +"""Идемпотентное создание приватного bucket отдельной административной учёткой.""" +import os +import time +from urllib.parse import urlsplit + +from minio import Minio +from minio.error import MinioException, S3Error +import urllib3 + +from src.config import secret + + +def bootstrap(): + endpoint = urlsplit(os.environ.get("S3_ENDPOINT", "http://s3:9000")) + client = Minio(endpoint.netloc, access_key=secret("S3_ROOT_USER"), secret_key=secret("S3_ROOT_PASSWORD"), + secure=endpoint.scheme == "https", region=os.environ.get("S3_REGION", "us-east-1"), + http_client=urllib3.PoolManager(timeout=urllib3.Timeout(connect=1, read=3), retries=False)) + bucket = os.environ.get("S3_BUCKET", "messenger-attachments") + deadline = time.monotonic() + 60 + while True: + try: + if not client.bucket_exists(bucket): + client.make_bucket(bucket) + print("Private bucket is ready; static IAM permits only authenticated accounts", flush=True) + return + except S3Error as error: + if error.code in {"BucketAlreadyOwnedByYou", "BucketAlreadyExists"}: + return + if time.monotonic() >= deadline: + raise RuntimeError("S3 bootstrap failed") from None + except (MinioException, urllib3.exceptions.HTTPError, OSError): + if time.monotonic() >= deadline: + raise RuntimeError("S3 bootstrap timed out") from None + time.sleep(1) + + +if __name__ == "__main__": + bootstrap() diff --git a/src/cleanup.py b/src/cleanup.py new file mode 100644 index 0000000..482e30f --- /dev/null +++ b/src/cleanup.py @@ -0,0 +1,60 @@ +"""Уровень 4: очистка только журнала незавершённых PUT, без полного обхода S3.""" +import argparse +import json +import logging +import os +import time + +from src import db, object_store +from src.attachments import lock_upload + + +GRACE_SECONDS = int(os.environ.get("UPLOAD_CLEANUP_GRACE_SECONDS", "3600")) +if GRACE_SECONDS < 60: + raise ValueError("Безопасный grace period должен быть не меньше 60 секунд") + + +def cleanup_once(): + result = {"removed": 0, "kept_ready": 0, "skipped_active": 0} + with db.connection() as conn: + candidates = conn.execute("""SELECT id, object_key FROM attachment_uploads + WHERE created_at < clock_timestamp() - %s * interval '1 second' + ORDER BY created_at LIMIT 100""", (GRACE_SECONDS,)).fetchall() + for row in candidates: + with db.connection() as conn: + if not lock_upload(conn, row["object_key"], blocking=False): + result["skipped_active"] += 1 + continue + pending = conn.execute("""SELECT 1 FROM attachment_uploads WHERE id=%s + AND created_at < clock_timestamp() - %s * interval '1 second' FOR UPDATE""", + (row["id"], GRACE_SECONDS)).fetchone() + if not pending: + continue + ready = conn.execute("SELECT 1 FROM attachments WHERE object_key=%s", (row["object_key"],)).fetchone() + if ready: + result["kept_ready"] += 1 + else: + object_store.remove(row["object_key"]) + result["removed"] += 1 + conn.execute("DELETE FROM attachment_uploads WHERE id=%s", (row["id"],)) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + db.pool.open(wait=True, timeout=15) + try: + while True: + try: + print(json.dumps(cleanup_once()), flush=True) + except Exception as error: + if args.once: + raise + logging.error("Cleanup postponed: %s", type(error).__name__) + if args.once: + break + time.sleep(30) + finally: + db.pool.close() diff --git a/src/config.py b/src/config.py new file mode 100644 index 0000000..c86331c --- /dev/null +++ b/src/config.py @@ -0,0 +1,20 @@ +"""Настройки и чтение локальных Docker secrets.""" +import os +import socket +from pathlib import Path + + +def secret(name): + return Path(os.environ[name + "_FILE"]).read_text().strip() + + +SESSION_TTL = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) +if SESSION_TTL < 1: + raise ValueError("SESSION_TTL_SECONDS должен быть положительным") +if os.environ.get("SESSION_STORE", "valkey") != "valkey": + raise ValueError("В этой реализации SESSION_STORE=valkey") + +INSTANCE_ID = socket.gethostname() +IDEMPOTENCY_TTL = int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400")) +if IDEMPOTENCY_TTL < 86400: + raise ValueError("IDEMPOTENCY_TTL_SECONDS должен быть не меньше 86400") diff --git a/src/db.py b/src/db.py new file mode 100644 index 0000000..973bbc2 --- /dev/null +++ b/src/db.py @@ -0,0 +1,52 @@ +"""Ограниченный пул; каждый with connection() — отдельная транзакция.""" +from contextlib import contextmanager + +import psycopg +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool, PoolTimeout, TooManyRequests + +from src.config import secret +from src.errors import ApiError + + +IO_TIMEOUT = 2.0 + + +class TimedConnection(psycopg.Connection): + def wait(self, gen, interval=0.1, timeout=None): + # statement_timeout работает на сервере и не помогает при docker pause. + # Ограничиваем само ожидание I/O: проверку пула, SQL, COMMIT и ROLLBACK. + timeout = IO_TIMEOUT if timeout is None else min(timeout, IO_TIMEOUT) + try: + return super().wait(gen, interval=interval, timeout=timeout) + except psycopg.OperationalError: + # Не ждём отмены/ROLLBACK от зависшего сервера. Пул заменит соединение. + self.close() + raise + + +pool = ConnectionPool( + conninfo=secret("DATABASE_URL"), open=False, + connection_class=TimedConnection, + min_size=1, max_size=5, max_waiting=20, timeout=2, + check=ConnectionPool.check_connection, + kwargs={ + "row_factory": dict_row, + "connect_timeout": 2, + "options": "-c timezone=UTC -c statement_timeout=3000 -c lock_timeout=2000 -c idle_in_transaction_session_timeout=5000", + }, +) + + +@contextmanager +def connection(): + try: + with pool.connection() as conn: + yield conn + except (psycopg.OperationalError, PoolTimeout, TooManyRequests): + raise ApiError(503, "unavailable", "PostgreSQL временно недоступен") from None + + +def ready(): + with connection() as conn: + conn.execute("SELECT 1") diff --git a/src/errors.py b/src/errors.py new file mode 100644 index 0000000..09e0cdf --- /dev/null +++ b/src/errors.py @@ -0,0 +1,27 @@ +"""общий формат ошибок""" + +from fastapi import Request +from fastapi.responses import JSONResponse + + +class ApiError(Exception): + def __init__(self, status: int, code: str, message: str, headers=None): + super().__init__(message) + self.status = status + self.code = code + self.message = message + self.headers = headers or {} + + +def error_response(request: Request, error: ApiError): + return JSONResponse( + status_code=error.status, + content={ + "error": { + "code": error.code, + "message": error.message, + "request_id": request.state.request_id, + } + }, + headers={"X-Request-Id": request.state.request_id, **error.headers}, + ) diff --git a/src/healthcheck.py b/src/healthcheck.py new file mode 100644 index 0000000..dae4d1d --- /dev/null +++ b/src/healthcheck.py @@ -0,0 +1,15 @@ +"""healthcheck докера""" + +import json +import os +from urllib.request import urlopen + + +if __name__ == "__main__": + port = os.environ.get("APP_PORT", "8080") + try: + with urlopen(f"http://127.0.0.1:{port}/health/ready", timeout=2) as response: + ready = response.status == 200 and json.load(response) == {"status": "ok"} + raise SystemExit(0 if ready else 1) + except (OSError, ValueError): + raise SystemExit(1) diff --git a/src/migrate.py b/src/migrate.py new file mode 100644 index 0000000..c4bf5ee --- /dev/null +++ b/src/migrate.py @@ -0,0 +1,48 @@ +"""Версионируемые миграции с проверкой checksum и блокировкой.""" +import hashlib +from pathlib import Path + +from src import db + + +DIRECTORY = Path(__file__).resolve().parents[1] / "migrations" + + +def check(): + """API только проверяет схему; DDL выполняет отдельный migrate-service.""" + with db.connection() as conn: + for path in sorted(DIRECTORY.glob("*.sql")): + row = conn.execute("SELECT checksum FROM schema_migrations WHERE version=%s", (path.name,)).fetchone() + if row is None or row["checksum"] != hashlib.sha256(path.read_bytes()).hexdigest(): + raise RuntimeError("Сначала выполните миграции: " + path.name) + + +def apply(): + applied = [] + with db.connection() as conn: + conn.execute("SELECT pg_advisory_xact_lock(202602)") + conn.execute(""" + CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, checksum text NOT NULL, + applied_at timestamptz NOT NULL DEFAULT clock_timestamp() + ) + """) + for path in sorted(DIRECTORY.glob("*.sql")): + checksum = hashlib.sha256(path.read_bytes()).hexdigest() + existing = conn.execute("SELECT checksum FROM schema_migrations WHERE version=%s", (path.name,)).fetchone() + if existing: + if existing["checksum"] != checksum: + raise RuntimeError("Изменена применённая миграция: " + path.name) + continue + conn.execute(path.read_text(), prepare=False) + conn.execute("INSERT INTO schema_migrations(version, checksum) VALUES (%s, %s)", (path.name, checksum)) + applied.append(path.name) + return applied + + +if __name__ == "__main__": + db.pool.open(wait=True, timeout=15) + try: + print("Migrations:", ", ".join(apply()) or "already applied") + finally: + db.pool.close() diff --git a/src/models.py b/src/models.py new file mode 100644 index 0000000..ee5360b --- /dev/null +++ b/src/models.py @@ -0,0 +1,56 @@ +"""допустимые поля и проверка данных""" + +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator, model_validator + + +class RequestModel(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + + @field_validator("*") + @classmethod + def check_strings(cls, value, info: ValidationInfo): + if isinstance(value, str): + if info.field_name != "text" and not value.strip(): + raise ValueError("Строка не должна состоять из пробелов") + value.encode("utf-8") + return value + + +class CreateUser(RequestModel): + username: str = Field(pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(min_length=1, max_length=100) + password: str = Field(min_length=12, max_length=128) + + +class CreateChat(RequestModel): + title: str = Field(min_length=1, max_length=100) + member_ids: list[str] = Field(min_length=1, max_length=100) + + @field_validator("member_ids") + @classmethod + def check_members(cls, values): + member_ids = [str(UUID(value)) for value in values] + if len(set(member_ids)) != len(member_ids): + raise ValueError("Участники не должны повторяться") + return member_ids + + +class CreateMessage(RequestModel): + text: str = Field(max_length=4000) + attachment_ids: list[str] = Field(default_factory=list, max_length=10) + + @field_validator("attachment_ids") + @classmethod + def check_attachments(cls, values): + ids = [str(UUID(value)) for value in values] + if len(ids) != len(set(ids)): + raise ValueError("Вложения не должны повторяться") + return ids + + @model_validator(mode="after") + def check_content(self): + if not self.text.strip() and not self.attachment_ids: + raise ValueError("Нужен текст или хотя бы одно вложение") + return self diff --git a/src/object_store.py b/src/object_store.py new file mode 100644 index 0000000..3cb4b8c --- /dev/null +++ b/src/object_store.py @@ -0,0 +1,57 @@ +"""Один приватный bucket; короткие таймауты и отсутствие прозрачных повторов PUT.""" +from contextlib import contextmanager +import os +from urllib.parse import urlsplit + +from minio import Minio +from minio.error import MinioException +import urllib3 + +from src.config import secret +from src.errors import ApiError + + +BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments") +endpoint = urlsplit(os.environ.get("S3_ENDPOINT", "http://s3:9000")) +client = Minio( + endpoint.netloc, + access_key=secret("S3_ACCESS_KEY_ID"), + secret_key=secret("S3_SECRET_ACCESS_KEY"), + secure=endpoint.scheme == "https", + region=os.environ.get("S3_REGION", "us-east-1"), + http_client=urllib3.PoolManager( + timeout=urllib3.Timeout(connect=1, read=3), retries=False, maxsize=4, + ), +) + + +@contextmanager +def available(): + try: + yield + except (MinioException, urllib3.exceptions.HTTPError, OSError): + raise ApiError(503, "unavailable", "Хранилище вложений временно недоступно") from None + + +def ready(): + with available(): + if not client.bucket_exists(BUCKET): + raise ApiError(503, "unavailable", "Хранилище вложений не готово") + + +def put(key, file, size, content_type): + with available(): + file.seek(0) + # Весь обязательный диапазон <=10 MiB помещается в ОДИН PUT, без multipart. + client.put_object(BUCKET, key, file, size, content_type=content_type, + part_size=10 * 1024 * 1024, num_parallel_uploads=1) + + +def get(key): + with available(): + return client.get_object(BUCKET, key) + + +def remove(key): + with available(): + client.remove_object(BUCKET, key) diff --git a/src/pagination.py b/src/pagination.py new file mode 100644 index 0000000..dcac20c --- /dev/null +++ b/src/pagination.py @@ -0,0 +1,39 @@ +"""Курсор — scope, время и UUID; сами страницы выбирает PostgreSQL.""" +import base64 +import binascii +from datetime import datetime +import json +import re +from uuid import UUID + +from src.errors import ApiError + + +def parameters(limit, cursor, scope): + try: + if not re.fullmatch(r"[0-9]+", limit): + raise ValueError + size = int(limit) + if not 1 <= size <= 100: + raise ValueError + anchor = None + if cursor is not None: + raw = base64.b64decode(cursor, altchars=b"-_", validate=True) + data = json.loads(raw.decode("utf-8")) + if not isinstance(data, dict) or set(data) != {"scope", "created_at", "id"}: + raise ValueError + if data["scope"] != scope or not isinstance(data["created_at"], str) or not data["created_at"].endswith("Z"): + raise ValueError + anchor = (datetime.fromisoformat(data["created_at"].replace("Z", "+00:00")), UUID(data["id"])) + return size, anchor + except (ValueError, TypeError, AttributeError, binascii.Error, RecursionError): + raise ApiError(400, "invalid_request", "Неверный limit или cursor") from None + + +def page(items, size, scope): + cursor = None + if len(items) > size: + last = items[size - 1] + value = {"scope": scope, "created_at": last["created_at"], "id": last["id"]} + cursor = base64.urlsafe_b64encode(json.dumps(value).encode()).decode() + return {"items": items[:size], "next_cursor": cursor} diff --git a/src/passwords.py b/src/passwords.py new file mode 100644 index 0000000..bc98066 --- /dev/null +++ b/src/passwords.py @@ -0,0 +1,22 @@ +"""Argon2id. Одновременно считаются не более двух хешей.""" +from threading import Semaphore + +from argon2 import PasswordHasher +from argon2.exceptions import VerificationError + + +hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1) +slots = Semaphore(2) + + +def hash_password(password): + with slots: + return hasher.hash(password) + + +def matches(encoded, password): + with slots: + try: + return hasher.verify(encoded, password) + except VerificationError: + return False diff --git a/src/storage.py b/src/storage.py new file mode 100644 index 0000000..fc76309 --- /dev/null +++ b/src/storage.py @@ -0,0 +1,154 @@ +"""Параметризованный SQL. Одна функция записи — одна транзакция.""" +from uuid import UUID, uuid4 + +from psycopg.errors import ForeignKeyViolation, UniqueViolation + +from src import db, pagination +from src.errors import ApiError +from src.config import IDEMPOTENCY_TTL + + +def utc(value): + return value.isoformat(timespec="microseconds").replace("+00:00", "Z") + + +def public_user(row): + return {"id": str(row["id"]), "username": row["username"], + "display_name": row["display_name"], "created_at": utc(row["created_at"])} + + +def public_chat(row): + return {"id": str(row["id"]), "title": row["title"], + "member_ids": [str(value) for value in row["member_ids"]], "created_at": utc(row["created_at"])} + + +def public_message(row): + return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), + "text": row["text"], "created_at": utc(row["created_at"]), + "attachment_ids": [str(value) for value in row.get("attachment_ids", [])]} + + +MESSAGE_ATTACHMENTS = """ARRAY(SELECT attachment_id FROM message_attachments + WHERE message_id=m.id ORDER BY position) AS attachment_ids""" + + +def create_user(username, display_name, password_hash): + try: + with db.connection() as conn: + row = conn.execute("""INSERT INTO users(id, username, display_name, password_hash) + VALUES (%s, %s, %s, %s) RETURNING *""", (uuid4(), username, display_name, password_hash)).fetchone() + result = public_user(row) + return result + except UniqueViolation: + raise ApiError(409, "conflict", "Имя пользователя уже занято") from None + + +def find_login(username): + with db.connection() as conn: + return conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone() + + +def find_user(user_id): + with db.connection() as conn: + row = conn.execute("SELECT * FROM users WHERE id=%s", (UUID(user_id),)).fetchone() + return public_user(row) if row else None + + +def create_chat(user_id, title, member_ids): + if user_id not in member_ids: + raise ApiError(400, "invalid_request", "Создатель должен входить в member_ids") + try: + with db.connection() as conn: + row = conn.execute("INSERT INTO chats(id, title) VALUES (%s, %s) RETURNING *", (uuid4(), title)).fetchone() + with conn.cursor() as cur: + cur.executemany("INSERT INTO chat_members(chat_id, user_id) VALUES (%s, %s)", + [(row["id"], UUID(member)) for member in member_ids]) + row["member_ids"] = member_ids + result = public_chat(row) + return result + except ForeignKeyViolation: + raise ApiError(400, "invalid_request", "Все участники должны существовать") from None + + +def require_member(conn, user_id, chat_id): + row = conn.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s", (UUID(chat_id), UUID(user_id))).fetchone() + if row is None: + raise ApiError(404, "not_found", "Чат не найден") + + +def get_chat(user_id, chat_id): + with db.connection() as conn: + require_member(conn, user_id, chat_id) + row = conn.execute("""SELECT c.*, ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id) AS member_ids + FROM chats c WHERE c.id=%s""", (UUID(chat_id),)).fetchone() + return public_chat(row) + + +def list_chats(user_id, limit, cursor): + scope = "chats:" + user_id + size, anchor = pagination.parameters(limit, cursor, scope) + with db.connection() as conn: + if anchor: + found = conn.execute("""SELECT 1 FROM chats c JOIN chat_members m ON m.chat_id=c.id + WHERE m.user_id=%s AND (c.created_at, c.id)=(%s, %s)""", (UUID(user_id), *anchor)).fetchone() + if not found: + raise ApiError(400, "invalid_request", "Неверный cursor") + condition = "AND (c.created_at, c.id) > (%s, %s)" if anchor else "" + params = (UUID(user_id), *(anchor or ()), size + 1) + rows = conn.execute("""WITH selected AS ( + SELECT c.* FROM chats c JOIN chat_members own ON own.chat_id=c.id + WHERE own.user_id=%s """ + condition + """ ORDER BY c.created_at, c.id LIMIT %s + ) SELECT c.*, ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id) AS member_ids + FROM selected c ORDER BY c.created_at, c.id""", params).fetchall() + return pagination.page([public_chat(row) for row in rows], size, scope) + + +def create_message(user_id, chat_id, text, key, attachment_ids=()): + attachment_ids = [UUID(value) for value in attachment_ids] + with db.connection() as conn: + require_member(conn, user_id, chat_id) + # Одна блокировка на область ключа во всех API-процессах. + # Побочный эффект и результат повтора фиксируются одной транзакцией. + scope = user_id + ":POST:/api/v1/chats/" + chat_id + "/messages:" + key + conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (scope,)) + previous = conn.execute("SELECT m.*, i.request_text, i.request_attachment_ids, " + MESSAGE_ATTACHMENTS + """ FROM message_idempotency i + JOIN messages m ON m.id=i.message_id + WHERE i.user_id=%s AND i.chat_id=%s AND i.key=%s AND i.expires_at>clock_timestamp()""", + (UUID(user_id), UUID(chat_id), key)).fetchone() + if previous: + if previous["request_text"] != text or previous["request_attachment_ids"] != attachment_ids: + raise ApiError(409, "conflict", "Этот ключ уже использован с другим сообщением") + return public_message(previous) + if attachment_ids: + available = conn.execute("SELECT id FROM attachments WHERE chat_id=%s AND id=ANY(%s)", + (UUID(chat_id), attachment_ids)).fetchall() + if len(available) != len(attachment_ids): + raise ApiError(404, "not_found", "Вложение не найдено в этом чате") + conn.execute("DELETE FROM message_idempotency WHERE user_id=%s AND chat_id=%s AND key=%s", + (UUID(user_id), UUID(chat_id), key)) + row = conn.execute("""INSERT INTO messages(id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s) + RETURNING *""", (uuid4(), UUID(chat_id), UUID(user_id), text)).fetchone() + for position, attachment_id in enumerate(attachment_ids): + conn.execute("INSERT INTO message_attachments(message_id, attachment_id, position) VALUES (%s, %s, %s)", + (row["id"], attachment_id, position)) + conn.execute("""INSERT INTO message_idempotency(user_id, chat_id, key, request_text, request_attachment_ids, message_id, expires_at) + VALUES (%s, %s, %s, %s, %s, %s, clock_timestamp() + %s * interval '1 second')""", + (UUID(user_id), UUID(chat_id), key, text, attachment_ids, row["id"], IDEMPOTENCY_TTL)) + row["attachment_ids"] = attachment_ids + result = public_message(row) + return result + + +def list_messages(user_id, chat_id, limit, cursor): + scope = "messages:" + chat_id + size, anchor = pagination.parameters(limit, cursor, scope) + with db.connection() as conn: + require_member(conn, user_id, chat_id) + if anchor: + found = conn.execute("SELECT 1 FROM messages WHERE chat_id=%s AND (created_at, id)=(%s, %s)", (UUID(chat_id), *anchor)).fetchone() + if not found: + raise ApiError(400, "invalid_request", "Неверный cursor") + condition = "AND (m.created_at, m.id) > (%s, %s)" if anchor else "" + rows = conn.execute("SELECT m.*, " + MESSAGE_ATTACHMENTS + " FROM messages m WHERE m.chat_id=%s " + condition + + " ORDER BY m.created_at, m.id LIMIT %s", (UUID(chat_id), *(anchor or ()), size + 1)).fetchall() + return pagination.page([public_message(row) for row in rows], size, scope) diff --git a/student-tests/attachment_checks.py b/student-tests/attachment_checks.py new file mode 100644 index 0000000..63562be --- /dev/null +++ b/student-tests/attachment_checks.py @@ -0,0 +1,275 @@ +"""Реальные отказы/очистка/память уровня 4; только временный тестовый стенд.""" +from concurrent.futures import ThreadPoolExecutor +import hashlib +import io +import json +import os +import socket +import subprocess +import threading +import time +from urllib.parse import urlsplit +from uuid import uuid4 + +from PIL import Image + +from helpers import Client, ROOT +from client import Failure + + +def run_checks(base, env, compose, apis, script, sql): + result = {} + client = Client(base, timeout=30) + alice, bob, _, chat = client.bootstrap() + png = (ROOT / "tests/fixtures/sample.png").read_bytes() + upload_path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=sample.png" + + def upload(): + return client.call("POST", upload_path, 201, actor=alice, raw=png, + headers={"Content-Type": "image/png"}, schema="Attachment") + + def inside(code, data=None): + completed = subprocess.run(["docker", "exec", "-i", apis()[0]["Id"], "python", "-c", code], + input=json.dumps(data), capture_output=True, text=True, timeout=45, check=True) + return json.loads(completed.stdout) + + def cleanup(): + return inside("from src import db; from src.cleanup import cleanup_once; import json; " + "db.pool.open(wait=True); print(json.dumps(cleanup_once())); db.pool.close()") + + def stat(key): + return inside("import json,sys; from src import object_store; from minio.error import S3Error\n" + "key=json.load(sys.stdin)\n" + "try:\n r=object_store.client.stat_object(object_store.BUCKET,key); print(json.dumps({'size':r.size}))\n" + "except S3Error as e:\n print(json.dumps({'error':e.code}))", key) + + def age(key): + sql("UPDATE attachment_uploads SET created_at=clock_timestamp()-interval '2 hours' WHERE object_key='" + key + "'") + + compose("stop", "cleanup") + try: + for _ in range(2): + compose("run", "--rm", "s3-bootstrap") + ready = upload()["json"] + key = sql("SELECT object_key FROM attachments WHERE id='" + ready["id"] + "'") + backend_id = compose("ps", "-q", "s3-storage") + backend = json.loads(subprocess.check_output(["docker", "inspect", backend_id], text=True))[0] + assert not set(backend["NetworkSettings"]["Networks"]) & set(apis()[0]["NetworkSettings"]["Networks"]) + backend_ip = next(iter(backend["NetworkSettings"]["Networks"].values()))["IPAddress"] + # Вызов S3 напрямую из контейнера клиента, минуя HTTP API приложения. + result["private_bucket"] = inside(""" +import io,json,socket,sys +from urllib.error import HTTPError +from urllib.request import urlopen +from minio.error import S3Error +from src import object_store +data=json.load(sys.stdin); key=data['key'] +try: + urlopen('http://s3:9000/'+object_store.BUCKET+'/'+key,timeout=3) + raise AssertionError('public original') +except HTTPError as e: + assert e.code == 403 +for operation in (lambda: object_store.client.make_bucket('forbidden-bucket'), + lambda: object_store.client.put_object(object_store.BUCKET,'outside-prefix',io.BytesIO(b'x'),1)): + try: + operation() + raise AssertionError('excess application permissions') + except S3Error as e: + assert e.code == 'AccessDenied', e.code +for port in (9333,8888,8080): + with socket.socket() as connection: + connection.settimeout(1) + assert connection.connect_ex(('s3',port)) != 0, 'admin/backend port open' + with socket.socket() as connection: + connection.settimeout(.5) + assert connection.connect_ex((data['backend_ip'],port)) != 0, 'storage network reachable from API' +print(json.dumps({'anonymous_get':403,'create_bucket':'AccessDenied','write_outside_prefix':'AccessDenied', + 'admin_ports_unreachable':[9333,8888,8080],'storage_network_isolated':True,'bootstrap_runs':2})) +""", {"key":key, "backend_ip":backend_ip}) + print("PASS: private S3, limited credentials, isolated administration, repeated bootstrap", flush=True) + + # Останавливаем именно реплику, которая ответила на upload, а затем читаем другой. + uploaded = upload() + target = uploaded["headers"]["X-Instance-Id"] + stopped_at = time.monotonic() + subprocess.run([str(ROOT / "scripts/stop-one.sh")], cwd=ROOT, + env=dict(env, TARGET_INSTANCE_ID=target), check=True, timeout=15) + script("wait-ready.sh") + while True: + try: + response = client.call("GET", "/api/v1/attachments/" + uploaded["json"]["id"] + "/content", actor=bob) + break + except Failure: + assert time.monotonic() - stopped_at < 10, "download failover exceeded 10 seconds" + time.sleep(.1) + assert response["bytes"] == png and response["headers"]["X-Instance-Id"] != target + stopped = next(info for info in apis() if info["Config"]["Hostname"] == target) + assert not stopped["State"]["Running"] + result["upload_replica_failover"] = {"uploaded_by": target, "stopped_container": stopped["Id"], + "downloaded_by": response["headers"]["X-Instance-Id"], "sha256": hashlib.sha256(png).hexdigest(), + "recovery_seconds":round(time.monotonic()-stopped_at,3)} + compose("start", "api") + script("wait-ready.sh") + print("PASS: original downloaded through another replica after stopping uploader", flush=True) + + # Незавершённое HTTP-тело не достигает S3 и не создаёт метаданных/журнала. + before = sql("SELECT (SELECT count(*) FROM attachments)||':'||(SELECT count(*) FROM attachment_uploads)") + address = urlsplit(base) + with socket.create_connection((address.hostname, address.port), timeout=3) as connection: + headers = ("POST " + upload_path + " HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer " + alice["token"] + + "\r\nContent-Type: image/png\r\nContent-Length: 1000000\r\n\r\n").encode() + connection.sendall(headers + png[:30]) + time.sleep(0.5) + assert sql("SELECT (SELECT count(*) FROM attachments)||':'||(SELECT count(*) FROM attachment_uploads)") == before + result["interrupted_body"] = {"metadata_or_journal_created": False} + + # Детерминированный реальный отказ PostgreSQL ПОСЛЕ успешного S3 PUT. + sql("""CREATE FUNCTION lab4_reject_attachment() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'injected storage failure' USING ERRCODE='08006'; END $$; + CREATE TRIGGER lab4_reject BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION lab4_reject_attachment();""") + try: + failure = client.call("POST", upload_path, 503, actor=alice, raw=png, headers={"Content-Type": "image/png"}) + assert failure["json"]["error"]["code"] == "unavailable" + finally: + sql("DROP TRIGGER lab4_reject ON attachments; DROP FUNCTION lab4_reject_attachment()") + pending_key = sql("SELECT object_key FROM attachment_uploads ORDER BY created_at DESC LIMIT 1") + assert stat(pending_key)["size"] == len(png) + assert sql("SELECT count(*) FROM attachments WHERE object_key='" + pending_key + "'") == "0" + assert cleanup()["removed"] == 0 + age(pending_key) + lock_code = ("from src import db; from src.attachments import lock_upload; import sys\n" + "db.pool.open(wait=True)\nwith db.connection() as c:\n" + " lock_upload(c,'" + pending_key + "'); print('locked',flush=True); sys.stdin.readline()\n" + "db.pool.close()") + holder = subprocess.Popen(["docker", "exec", "-i", apis()[0]["Id"], "python", "-u", "-c", lock_code], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + assert holder.stdout.readline().strip() == "locked" + assert cleanup()["skipped_active"] == 1 + assert stat(pending_key)["size"] == len(png) + finally: + holder.communicate("\n", timeout=10) + assert cleanup()["removed"] == 1 + assert stat(pending_key).get("error") == "NoSuchKey" + assert cleanup()["removed"] == 0 + # Даже устаревшая ошибочная запись журнала не позволяет удалить ready-файл. + sql("INSERT INTO attachment_uploads(id,object_key,created_at) VALUES ('" + str(uuid4()) + "','" + key + + "',clock_timestamp()-interval '2 hours')") + assert cleanup()["kept_ready"] == 1 + assert client.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", actor=bob)["bytes"] == png + result["compensation"] = {"failure_after_put":503, "orphan_recorded":True, "fresh_kept":True, + "active_locked_kept":True, "expired_removed":True, "ready_kept":True, "repeat_safe":True} + print("PASS: post-PUT DB failure recorded; cleanup protects fresh, active and ready uploads", flush=True) + + try: + compose("stop", "--timeout", "8", "s3") + result["s3_outage"] = inside(""" +import json,sys +from urllib.request import Request,urlopen +from urllib.error import HTTPError +data=json.load(sys.stdin) +statuses={} +for name,method,path,body in [('live','GET','/health/live',None),('ready','GET','/health/ready',None), + ('download','GET','/api/v1/attachments/'+data['id']+'/content',None), + ('upload','POST',data['upload'],bytes.fromhex(data['png']))]: + req=Request('http://127.0.0.1:8080'+path,data=body,method=method, + headers={'Authorization':'Bearer '+data['token'],'Content-Type':'image/png'}) + try: response=urlopen(req,timeout=8) + except HTTPError as error: response=error + with response: + statuses[name]=response.status + payload=json.load(response) + if name!='live': + assert response.status==503 and payload['error']['code']=='unavailable' + assert payload['error']['request_id']==response.headers['X-Request-Id'] +assert statuses['live']==200 +print(json.dumps(statuses)) +""", {"id":ready["id"], "token":alice["token"], "upload":upload_path, "png":png.hex()}) + finally: + compose("start", "s3") + script("wait-ready.sh") + assert client.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", actor=bob)["bytes"] == png + sql("UPDATE attachment_uploads SET created_at=clock_timestamp()-interval '2 hours'") + assert cleanup()["removed"] >= 1 + result["s3_outage"]["original_preserved_after_recovery"] = True + print("PASS: S3 outage gives API 503; recovery preserves original and session", flush=True) + + # Доказываем работу постоянного worker, а не только ручного вызова cleanup_once. + inside("import io,json; from src import object_store; " + "object_store.put('attachments/cleanup-worker-test',io.BytesIO(b'x'),1,'application/octet-stream'); print('{}')") + sql("INSERT INTO attachment_uploads(id,object_key,created_at) VALUES ('" + str(uuid4()) + + "','attachments/cleanup-worker-test',clock_timestamp()-interval '2 hours')") + compose("start", "cleanup") + deadline = time.monotonic() + 40 + while sql("SELECT count(*) FROM attachment_uploads WHERE object_key='attachments/cleanup-worker-test'") != "0": + assert time.monotonic() < deadline, "automatic cleanup not running" + time.sleep(0.2) + assert stat('attachments/cleanup-worker-test').get("error") == "NoSuchKey" + result["compensation"]["automatic_worker"] = True + + # 10 одновременно отправляемых реальных PNG ~5.5 MiB; монитор cgroup каждые 20 ms. + image = Image.frombytes("RGB", (1600, 1200), os.urandom(1600 * 1200 * 3)) + buffer = io.BytesIO() + image.save(buffer, format="PNG") + image.close() + data = buffer.getvalue() + expected_sha = hashlib.sha256(data).hexdigest() + monitor_code = """ +from pathlib import Path +import json,sys,threading,time +root=Path('/sys/fs/cgroup'); stop=threading.Event(); samples=[] +threading.Thread(target=lambda:(sys.stdin.readline(),stop.set()),daemon=True).start() +start=time.monotonic(); before=int((root/'memory.current').read_text()) +print('ready',flush=True) +while not stop.is_set(): + samples.append([round(time.monotonic()-start,3),int((root/'memory.current').read_text())]) + stop.wait(.02) +print(json.dumps({'baseline_bytes':before,'sample_peak_bytes':max(s[1] for s in samples), + 'lifetime_peak_bytes':int((root/'memory.peak').read_text()),'samples':samples}),flush=True) +""" + monitors = [] + responses = [] + try: + for info in apis(): + process = subprocess.Popen(["docker", "exec", "-i", info["Id"], "python", "-u", "-c", monitor_code], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + assert process.stdout.readline().strip() == "ready" + monitors.append((info, process)) + barrier = threading.Barrier(10) + def send(_): + concurrent_client = Client(base, timeout=60) + barrier.wait(timeout=15) + return concurrent_client.call("POST", upload_path, 201, actor=alice, raw=data, + headers={"Content-Type":"image/png"}, schema="Attachment") + started = time.monotonic() + with ThreadPoolExecutor(max_workers=10) as pool: + responses = list(pool.map(send, range(10))) + elapsed = time.monotonic() - started + finally: + memory = [] + for info, process in monitors: + output, error = process.communicate("\n", timeout=10) + assert process.returncode == 0, error + measurement = json.loads(output) + measurement.update({"instance": info["Config"]["Hostname"], "limit_bytes": info["HostConfig"]["Memory"]}) + assert measurement["sample_peak_bytes"] < measurement["limit_bytes"] + memory.append(measurement) + assert len(responses) == 10 + assert len({r["headers"]["X-Instance-Id"] for r in responses}) >= 2 + for response in responses: + assert response["json"]["sha256"] == expected_sha and response["json"]["size_bytes"] == len(data) + original = client.call("GET", "/api/v1/attachments/" + response["json"]["id"] + "/content", actor=bob) + assert hashlib.sha256(original["bytes"]).hexdigest() == expected_sha + assert all(not i["State"]["OOMKilled"] for i in apis()) + timings = sorted(r["elapsed"] * 1000 for r in responses) + result["parallel_uploads"] = {"concurrency":10, "successful":10, "errors":0, + "dimensions":[1600,1200], "size_bytes":len(data), "sha256":expected_sha, + "duration_seconds":round(elapsed,3), "successful_rps":round(10/elapsed,3), + "p50_ms":round(timings[4],3), "p95_ms":round(timings[-1],3), + "memory_sample_interval_seconds":0.02, "memory_includes_monitor_process":True, + "memory":memory, "all_original_checksums_verified":True, "oom_killed":False} + print("PASS: 10 concurrent real PNG uploads; all checksums match; memory peaks:", + [m["sample_peak_bytes"] for m in memory], flush=True) + return result + finally: + compose("start", "s3", "api", "cleanup") diff --git a/student-tests/docker_lifecycle.py b/student-tests/docker_lifecycle.py new file mode 100644 index 0000000..29f6aeb --- /dev/null +++ b/student-tests/docker_lifecycle.py @@ -0,0 +1,325 @@ +"""Проверки уровня 4 в отдельном Compose project с синтетическими данными.""" +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone +import json +import os +import platform +import socket +import subprocess +import sys +import threading +import time +from urllib.error import HTTPError +from urllib.request import urlopen +from uuid import uuid4 + +from helpers import Client, ROOT +from client import Failure +from resilience import history +from attachment_checks import run_checks +from postgres_pause import check_postgres_pause + + +def docker(*args): + return subprocess.check_output(["docker", *args], text=True, timeout=180).strip() + + +def main(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + project = "lab4-check-" + uuid4().hex[:10] + base = f"http://127.0.0.1:{port}" + env = dict(os.environ, COMPOSE_PROJECT_NAME=project, HOST_PORT=str(port), + API_REPLICAS="2", SESSION_TTL_SECONDS="3600", BASE_URL=base) + result = {"utc": datetime.now(timezone.utc).isoformat(), "project": project, + "base_url": base, "host": platform.system() + " " + platform.machine(), + "docker": docker("info", "--format", "{{.ServerVersion}} {{.Architecture}} CPUs={{.NCPU}} RAM={{.MemTotal}}"), + "commit": docker("compose", "version", "--short"), + "profile": {"workers": 4, "pause_seconds": 0.05, "operation": "POST message then GET history, same-key retry after uncertain POST"}} + result["compose_version"] = result.pop("commit") + try: + result["source_commit"] = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=ROOT, text=True, stderr=subprocess.DEVNULL).strip() + dirty = subprocess.run(["git", "status", "--porcelain"], cwd=ROOT, capture_output=True, text=True, check=True) + result["working_tree"] = bool(dirty.stdout.strip()) + except (subprocess.CalledProcessError, FileNotFoundError): + result["source_commit"] = None + result["working_tree"] = None + + def compose(*args): + return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, env=env, text=True, timeout=180).strip() + + def script(name): + subprocess.run([str(ROOT / "scripts" / name)], cwd=ROOT, env=env, check=True, timeout=240) + + def inspect_all(): + ids = compose("ps", "-a", "-q").split() + return json.loads(docker("inspect", *ids)) + + def apis(): + return [i for i in inspect_all() if i["Config"]["Labels"]["com.docker.compose.service"] == "api"] + + def metadata(info): + return {"id": info["Id"], "instance": info["Config"]["Hostname"], + "service": info["Config"]["Labels"]["com.docker.compose.service"], + "image": info["Image"], "started_at": info["State"]["StartedAt"], + "running": info["State"]["Running"], "exit_code": info["State"]["ExitCode"], + "memory_bytes": info["HostConfig"]["Memory"], "nano_cpus": info["HostConfig"]["NanoCpus"], + "published_ports": info["HostConfig"]["PortBindings"], + "mounts": [{"type": m["Type"], "destination": m["Destination"], "name": m.get("Name")} for m in info["Mounts"]]} + + def sql(query): + return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", query) + + def check_shutdown(): + info = apis()[0] + # Внутреннее подключение через docker exec не публикует порт API на хост. + pending_code = """import socket,time +s=socket.create_connection(('127.0.0.1',8080),timeout=2) +s.sendall(b'POST /api/v1/users HTTP/1.1\\r\\nHost: localhost\\r\\nContent-Type: application/json\\r\\nContent-Length: 1000\\r\\nExpect: 100-continue\\r\\n\\r\\n') +assert b'100 Continue' in s.recv(1024) +s.sendall(b'{"username":') +print('pending',flush=True) +time.sleep(30) +""" + pending = subprocess.Popen(["docker", "exec", info["Id"], "python", "-u", "-c", pending_code], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + assert pending.stdout.readline().strip() == "pending" + started = time.monotonic() + docker("kill", "--signal=TERM", info["Id"]) + first_refusal = None + while True: + state = json.loads(docker("inspect", info["Id"]))[0]["State"] + if not state["Running"]: + break + assert time.monotonic() - started < 8 + probe = subprocess.run(["docker", "exec", info["Id"], "python", "-c", + "import socket; s=socket.socket(); s.settimeout(.2); raise SystemExit(s.connect_ex(('127.0.0.1',8080)))"], + capture_output=True, timeout=3) + if probe.returncode and first_refusal is None: + first_refusal = time.monotonic() - started + time.sleep(0.1) + elapsed = time.monotonic() - started + assert first_refusal is not None and first_refusal < elapsed < 8 + assert state["ExitCode"] == 0 and not state["OOMKilled"] + logs = subprocess.run(["docker", "logs", info["Id"]], capture_output=True, text=True, check=True) + assert "Application shutdown complete" in logs.stdout + logs.stderr + result["sigterm"] = {"instance": info["Config"]["Hostname"], "unfinished_request": True, + "shutdown_seconds": round(elapsed, 3), "new_connections_refused_seconds": round(first_refusal, 3), + "exit_code": state["ExitCode"], "oom_killed": state["OOMKilled"]} + print("PASS: SIGTERM with unfinished request:", json.dumps(result["sigterm"]), flush=True) + finally: + pending.communicate(timeout=10) + compose("start", "api") + script("wait-ready.sh") + + def load_action(label, action, target=None): + client = Client(base, timeout=2) + alice, bob, _, chat = client.bootstrap() + original = client.message(alice, chat, "До воздействия")["json"] + stop = threading.Event() + lock = threading.Lock() + successes, errors, confirmed = [], [], {} + started = time.monotonic() + + def worker(index): + c = Client(base, timeout=2) + key = uuid4().hex + while not stop.is_set(): + for method in ("POST", "GET"): + try: + if method == "POST": + response = c.message(alice, chat, "load-" + key, key=key) + with lock: + confirmed[response["json"]["id"]] = response["json"] + key = uuid4().hex + else: + response = c.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", + actor=bob, schema="MessagePage") + with lock: + successes.append((time.monotonic() - started, method, + response["headers"]["X-Instance-Id"], response["elapsed"])) + except Failure as exc: + with lock: + errors.append((time.monotonic() - started, method, str(exc))) + stop.wait(0.05) + + with ThreadPoolExecutor(max_workers=4) as pool: + futures = [pool.submit(worker, i) for i in range(4)] + time.sleep(1) + action_start = time.monotonic() - started + try: + action_info = action() + action_end = time.monotonic() - started + # Охватывает обнаружение отказа и устойчивую работу после него. + time.sleep(max(3, 15 - (action_end - action_start))) + finally: + stop.set() + for future in futures: + future.result() + elapsed = time.monotonic() - started + items = history(client, bob, chat) + by_id = {m["id"]: m for m in items} + assert len(items) == len(by_id) == len({m["text"] for m in items}), "Повтор создал дубль" + assert by_id.get(original["id"]) == original + assert all(by_id.get(mid) == msg for mid, msg in confirmed.items()), "Потеря подтверждённого сообщения" + after = [s for s in successes if s[0] >= action_end] + assert {s[1] for s in after} == {"POST", "GET"}, "Нет чтений/записей после воздействия" + recovery = {method: round(min(s[0] for s in successes if s[0] >= action_start and s[1] == method) - action_start, 3) + for method in ("POST", "GET")} + assert max(recovery.values()) <= 10, recovery + max_gap = {} + for method in ("POST", "GET"): + moments = sorted(s[0] for s in successes if s[1] == method) + max_gap[method] = round(max(b - a for a, b in zip(moments, moments[1:])), 3) + assert max(max_gap.values()) <= 10, max_gap + if target: + assert target not in {s[2] for s in after[-20:]}, "Остановленная реплика ещё отвечает" + buckets = [] + for second in range(int(elapsed) + 1): + buckets.append({"second": second, "successes": sum(second <= s[0] < second + 1 for s in successes), + "errors": sum(second <= e[0] < second + 1 for e in errors)}) + latencies = sorted(s[3] * 1000 for s in successes) + summary = {"label": label, "duration_seconds": round(elapsed, 3), "successful_requests": len(successes), + "successful_writes": len(confirmed), "errors": len(errors), "successful_rps": round(len(successes) / elapsed, 2), + "first_success_after_action_seconds": recovery, "maximum_success_gap_seconds": max_gap, + "action_start_seconds": round(action_start, 3), "action_end_seconds": round(action_end, 3), + "p50_ms": round(latencies[len(latencies) // 2], 3), + "p95_ms": round(latencies[int(len(latencies) * .95)], 3), + "confirmed_data_preserved": True, "duplicate_messages": 0, + "instances": sorted({s[2] for s in successes}), "per_second": buckets, + "error_samples": errors[:5], "action": action_info} + print(json.dumps({k: v for k, v in summary.items() if k not in ("per_second", "error_samples", "action")}, ensure_ascii=False), flush=True) + return summary + + print("Command: ./scripts/check-docker.sh; project:", project, flush=True) + print("Docker:", result["docker"], flush=True) + try: + script("start.sh") + initial = inspect_all() + result["containers"] = [metadata(info) for info in initial] + assert len(apis()) == 2 + for info in initial: + assert info["HostConfig"]["Memory"] > 0 and info["HostConfig"]["NanoCpus"] > 0 + if info["Config"]["Labels"]["com.docker.compose.service"] != "lb": + assert not info["HostConfig"]["PortBindings"] + for info in apis(): + assert docker("exec", info["Id"], "id", "-u") == "10001" + assert all(m["Destination"].startswith("/run/secrets/") for m in info["Mounts"]) + print("PASS: 2 real API containers, CPU/RAM limits, API non-root and no public ports; only LB published", flush=True) + subprocess.run([str(ROOT / "scripts/check.sh")], cwd=ROOT, env=env, check=True, timeout=240) + result["api_tests"] = "public smoke + student unittest suite passed" + subprocess.run([str(ROOT / "scripts/demo.sh")], cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL, timeout=30) + assert sql("SELECT count(*) FROM schema_migrations") == "3" + count = sql("SELECT count(*) FROM messages") + for _ in range(2): + compose("run", "--rm", "migrate") + assert sql("SELECT count(*) FROM schema_migrations") == "3" + assert sql("SELECT count(*) FROM messages") == count + print("PASS: migrations only in one-shot service; repeated execution preserves data", flush=True) + result["attachments"] = run_checks(base, env, compose, apis, script, sql) + + replay_client = Client(base) + replay_actor, _, _, replay_chat = replay_client.bootstrap() + replay_key = uuid4().hex + saved_message = replay_client.message(replay_actor, replay_chat, "Повтор после рестарта", key=replay_key)["json"] + before = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]} + subprocess.run(["make", "test-persistence", "PYTHON=" + sys.executable, "ACTION_SCRIPT=scripts/restart.sh"], + cwd=ROOT, env=env, check=True, timeout=180) + after = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]} + assert before.keys() == after.keys() + assert all(before[cid]["started_at"] != after[cid]["started_at"] for cid in before) + assert replay_client.message(replay_actor, replay_chat, "Повтор после рестарта", key=replay_key)["json"] == saved_message + result["persistence"] = {"before": list(before.values()), "after": list(after.values()), "passed": True, + "idempotency_replay_after_restart": True} + print("PASS: both API, LB, PostgreSQL, Valkey, S3 and cleaner actually restarted; data and session preserved", flush=True) + + check_shutdown() + + dependency_client = Client(base) + actor = dependency_client.user("deps") + result["dependency_readiness"] = [] + for dependency in ("valkey", "postgres", "s3"): + try: + compose("stop", "--timeout", "8", dependency) + probe_id = apis()[0]["Id"] + readiness = subprocess.run(["docker", "exec", probe_id, "python", "-m", "src.healthcheck"], capture_output=True, timeout=10) + assert readiness.returncode == 1 + live = docker("exec", probe_id, "python", "-c", + "from urllib.request import urlopen; print(urlopen('http://127.0.0.1:8080/health/live').status)") + assert live == "200" + deadline = time.monotonic() + 8 + while True: + try: + urlopen(base + "/health/ready", timeout=2).close() + except HTTPError as error: + if error.code == 503: + break + raise + except OSError: + # Уже отправленный запрос может истечь до исключения backend. + pass + assert time.monotonic() < deadline + time.sleep(0.1) + result["dependency_readiness"].append({"dependency": dependency, "api_live": 200, "api_ready": 503, "lb_ready": 503}) + print("PASS:", dependency, "outage: API live=200, ready=503, LB ready=503", flush=True) + finally: + compose("start", dependency) + script("wait-ready.sh") + dependency_client.call("GET", "/api/v1/users/me", actor=actor, schema="User") + + result["postgres_pause"] = check_postgres_pause(compose, apis, base) + + subprocess.run(["make", "test-failover", "PYTHON=" + sys.executable, "ACTION_SCRIPT=scripts/stop-one.sh"], + cwd=ROOT, env=env, check=True, timeout=90) + assert sum(i["State"]["Running"] for i in apis()) == 1 + result["public_failover"] = {"passed": True, "containers_after": [metadata(i) for i in apis()]} + compose("start", "api") + script("wait-ready.sh") + + result["failovers"] = [] + for info in apis(): + target = info["Config"]["Hostname"] + + def stop_target(): + subprocess.run([str(ROOT / "scripts/stop-one.sh")], cwd=ROOT, + env=dict(env, TARGET_INSTANCE_ID=target), check=True, timeout=10) + stopped = json.loads(docker("inspect", info["Id"]))[0] + assert not stopped["State"]["Running"] + assert not stopped["State"]["OOMKilled"] and stopped["State"]["ExitCode"] == 0 + # Uvicorn пишет в stderr; получаем оба потока без вывода запросов. + logs_result = subprocess.run(["docker", "logs", info["Id"]], capture_output=True, text=True, check=True) + assert "Application shutdown complete" in logs_result.stdout + logs_result.stderr + return metadata(stopped) + + result["failovers"].append(load_action("stop " + target, stop_target, target)) + compose("start", "api") + script("wait-ready.sh") + + before = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]} + + def replace(): + script("rolling-update.sh") + after = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]} + old_api = {i["id"] for i in before.values() if i["service"] == "api"} + new_api = {i["id"] for i in after.values() if i["service"] == "api"} + assert len(new_api) == 2 and not old_api & new_api + for cid, info in before.items(): + if info["service"] != "api": + assert after[cid]["started_at"] == info["started_at"] + return {"before": list(before.values()), "after": list(after.values())} + + result["rolling_update"] = load_action("sequential API replacement", replace) + result["passed"] = True + print("PASS: all lab4 grade-4 checks completed", flush=True) + finally: + output = ROOT / "evidence" / "lab4-checks.json" + output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n") + compose("down", "--volumes", "--timeout", "8") + print("Removed only temporary test containers and volumes:", project, flush=True) + + +if __name__ == "__main__": + main() diff --git a/student-tests/helpers.py b/student-tests/helpers.py new file mode 100644 index 0000000..d44e6fd --- /dev/null +++ b/student-tests/helpers.py @@ -0,0 +1,42 @@ +from pathlib import Path +import sys +import unittest +from urllib.parse import urlencode +from uuid import uuid4 + + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client + + +class ApiTestCase(unittest.TestCase): + def setUp(self): + self.client = Client() + self.alice, self.bob, self.eve, self.chat = self.client.bootstrap() + self.path = "/api/v1/chats/" + self.chat["id"] + + def assert_error(self, method, path, status, code, **kwargs): + if method == "POST" and path.endswith("/messages"): + kwargs["headers"] = {"Idempotency-Key": uuid4().hex, **kwargs.get("headers", {})} + result = self.client.call(method, path, status, **kwargs) + self.assertEqual(result["json"]["error"]["code"], code) + return result["json"]["error"] + + def read_all(self, path, actor, schema, limit=3): + items = [] + cursor = None + seen_cursors = set() + while True: + query = {"limit": limit} + if cursor is not None: + query["cursor"] = cursor + page = self.client.call("GET", path + "?" + urlencode(query), actor=actor, schema=schema)["json"] + self.assertLessEqual(len(page["items"]), limit) + items.extend(page["items"]) + cursor = page["next_cursor"] + if cursor is None: + return items + self.assertTrue(page["items"], "Пустая страница не должна вести к следующей") + self.assertNotIn(cursor, seen_cursors, "Зацикливание пагинации") + seen_cursors.add(cursor) diff --git a/student-tests/postgres_pause.py b/student-tests/postgres_pause.py new file mode 100644 index 0000000..07bd2fb --- /dev/null +++ b/student-tests/postgres_pause.py @@ -0,0 +1,145 @@ +"""Пауза живой PostgreSQL: прямой readiness, ограниченное SQL I/O и восстановление.""" +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import socket +import subprocess +import sys +import time +from uuid import uuid4 + +from helpers import Client, ROOT +from client import Failure + + +def check_postgres_pause(compose, apis, base): + client = Client(base) + alice, bob, _, chat = client.bootstrap() + saved_message = client.message(alice, chat, "До паузы PostgreSQL")["json"] + before = {info["Id"]:info["State"]["StartedAt"] for info in apis() if info["State"]["Running"]} + probe_id = sorted(before)[0] + + def direct_probe(path, expected): + # HTTP напрямую в API, без HAProxy и его собственных таймаутов/503. + code = """ +import json,time +from urllib.error import HTTPError +from urllib.request import urlopen +started=time.monotonic() +try: response=urlopen('http://127.0.0.1:8080/PATH',timeout=5) +except HTTPError as error: response=error +with response: + body=json.load(response) + elapsed=time.monotonic()-started + assert response.status==EXPECTED, response.status + assert response.headers['X-Request-Id'] and response.headers['X-Instance-Id'] + if response.status==503: + assert body['error']['code']=='unavailable' + assert body['error']['request_id']==response.headers['X-Request-Id'] + assert elapsed<4.5, elapsed + print(json.dumps({'status':response.status,'elapsed_seconds':round(elapsed,3)})) +""".replace("PATH", path).replace("EXPECTED", str(expected)) + completed = subprocess.run(["docker", "exec", probe_id, "python", "-c", code], + capture_output=True, text=True, timeout=8, check=True) + return json.loads(completed.stdout) + + # Соединение получено ДО pause: проверяем именно выполняющийся SQL, а не + # только timeout получения нового соединения или check callback пула. + query_code = """ +import json,sys,time +import psycopg +from src import db +db.pool.open(wait=True,timeout=10) +conn=db.pool.getconn() +conn.execute('SET statement_timeout=0') +print('connected',flush=True) +sys.stdin.readline() +started=time.monotonic() +try: + try: conn.execute('SELECT 1') + except psycopg.OperationalError: + elapsed=time.monotonic()-started + assert elapsed<4.5, elapsed + assert conn.closed, 'timed out connection was not discarded' + print(json.dumps({'elapsed_seconds':round(elapsed,3),'connection_closed':conn.closed}),flush=True) + else: raise AssertionError('paused database answered a query') +finally: + db.pool.putconn(conn) + db.pool.close() +""" + query = subprocess.Popen(["docker", "exec", "-i", probe_id, "python", "-u", "-c", query_code], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + result = {} + try: + assert query.stdout.readline().strip() == "connected" + compose("pause", "postgres") + paused_at = time.monotonic() + output, error = query.communicate("\n", timeout=10) + assert query.returncode == 0, "SQL I/O deadline failed: " + error + result["sql_without_server_timeout"] = json.loads(output) + result["direct_ready"] = direct_probe("health/ready", 503) + result["direct_live"] = direct_probe("health/live", 200) + # Повторные запросы при длительной паузе не должны оставлять занятые потоки. + with ThreadPoolExecutor(max_workers=10) as executor: + result["repeated_ready"] = list(executor.map(lambda _: direct_probe("health/ready", 503), range(10))) + # Сервер остаётся на pause не менее 12 секунд; ограничиваем именно API. + remaining = 12 - (time.monotonic() - paused_at) + if remaining > 0: + time.sleep(remaining) + result["ready_after_12_seconds"] = direct_probe("health/ready", 503) + result["live_after_repeated_requests"] = direct_probe("health/live", 200) + result["paused_seconds"] = round(time.monotonic() - paused_at, 3) + finally: + compose("unpause", "postgres") + if query.poll() is None: + query.communicate(timeout=10) + + resumed_at = time.monotonic() + while True: + try: + result["recovered_ready"] = direct_probe("health/ready", 200) + client.call("GET", "/api/v1/users/me", actor=alice, schema="User") + messages = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage")["json"]["items"] + assert saved_message in messages + break + except (subprocess.CalledProcessError, Failure): + assert time.monotonic() - resumed_at < 30, "readiness did not recover after unpause" + time.sleep(.2) + assert before == {info["Id"]:info["State"]["StartedAt"] for info in apis() if info["State"]["Running"]} + result.update({"recovery_seconds":round(time.monotonic()-resumed_at,3), "api_not_restarted":True, + "existing_session_and_message_preserved":True, "passed":True}) + print("PASS: paused PostgreSQL: SQL and direct readiness bounded; live works; unpause restores API without restart", flush=True) + return result + + +def main(): + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + port = listener.getsockname()[1] + project = "lab4-pg-pause-" + uuid4().hex[:10] + base = f"http://127.0.0.1:{port}" + env = dict(os.environ, COMPOSE_PROJECT_NAME=project, HOST_PORT=str(port), API_REPLICAS="2", BASE_URL=base) + + def compose(*args): + return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, env=env, text=True, timeout=180).strip() + + def apis(): + ids = compose("ps", "-a", "-q", "api").split() + return json.loads(subprocess.check_output(["docker", "inspect", *ids], text=True)) + + result = {"utc":datetime.now(timezone.utc).isoformat(), "project":project, + "command":".venv/bin/python student-tests/postgres_pause.py", "passed":False} + try: + compose("up", "-d", "--no-build", "lb") + subprocess.run([str(ROOT / "scripts/wait-ready.sh")], cwd=ROOT, env=env, check=True, timeout=120) + result.update(check_postgres_pause(compose, apis, base)) + print(json.dumps(result, ensure_ascii=False), flush=True) + finally: + Path(ROOT / "evidence/postgres-pause.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n") + compose("down", "--volumes", "--timeout", "8") + + +if __name__ == "__main__": + main() diff --git a/student-tests/test_api.py b/student-tests/test_api.py new file mode 100644 index 0000000..08940ae --- /dev/null +++ b/student-tests/test_api.py @@ -0,0 +1,164 @@ +import base64 +import json +from urllib.parse import urlencode +from uuid import uuid4 + +from helpers import ApiTestCase + + +class ApiTests(ApiTestCase): + def test_duplicate_username(self): + self.assert_error("POST", "/api/v1/users", 409, "conflict", body=self.alice["registration"]) + + def test_invalid_user_fields(self): + invalid_bodies = [ + {}, [], None, + {"username": "ab", "display_name": "Имя"}, + {"username": "UPPER", "display_name": "Имя"}, + {"username": "name\n", "display_name": "Имя"}, + {"username": "язык", "display_name": "Имя"}, + {"username": "a" * 33, "display_name": "Имя"}, + {"username": 123, "display_name": "Имя"}, + {"username": "valid_name", "display_name": " \t\n"}, + {"username": "valid_name", "display_name": "👋" * 101}, + {"username": "valid_name", "display_name": False}, + {"username": "valid_name", "display_name": "Имя", "extra": 1}, + ] + for body in invalid_bodies: + if isinstance(body, dict): + body = {**body, "password": "Synthetic-password-123"} + with self.subTest(body=body): + self.assert_error("POST", "/api/v1/users", 400, "invalid_request", + raw=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) + + def test_malformed_json_and_encoding(self): + invalid_bodies = [ + b'{"username":', b'', b'not JSON', b'\xff', + '{"username":"valid_name","display_name":"Имя"}'.encode("utf-16"), + b'{"username":"valid_name","display_name":"\\ud800"}', + ] + for body in invalid_bodies: + with self.subTest(body=body): + self.assert_error("POST", "/api/v1/users", 400, "invalid_request", + raw=body, headers={"Content-Type": "application/json"}) + + def test_wrong_content_type(self): + self.assert_error("POST", "/api/v1/users", 415, "unsupported_media_type", + raw=b'{}', headers={"Content-Type": "text/plain"}) + + def test_identification_and_authentication_order(self): + self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized") + self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized", + headers={"X-User-Id": self.alice["id"]}) + self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized", + headers={"Authorization": "Bearer unknown-session"}) + self.assert_error("POST", self.path + "/messages", 401, "unauthorized", + raw=b'{', headers={"Content-Type": "application/json"}) + me = self.client.call("GET", "/api/v1/users/me", schema="User", actor=self.alice, + headers={"X-User-Id": self.bob["id"]})["json"] + self.assertEqual(me, self.alice["user"]) + + def test_invalid_chat_members(self): + invalid_members = [ + [], [self.bob["id"]], [self.alice["id"], str(uuid4())], + [self.alice["id"], self.alice["id"]], + [self.alice["id"], self.alice["id"].upper()], + [self.alice["id"], "not-a-uuid"], [True], self.alice["id"], + [self.alice["id"]] + [str(uuid4()) for _ in range(100)], + ] + for members in invalid_members: + with self.subTest(members=members): + self.assert_error("POST", "/api/v1/chats", 400, "invalid_request", actor=self.alice, + body={"title": "Чат", "member_ids": members}) + chats = self.read_all("/api/v1/chats", self.alice, "ChatPage") + self.assertEqual([chat["id"] for chat in chats], [self.chat["id"]]) + + def test_invalid_chat_title(self): + for title in ("", " \n", "a" * 101, 123, None): + with self.subTest(title=title): + self.assert_error("POST", "/api/v1/chats", 400, "invalid_request", actor=self.alice, + body={"title": title, "member_ids": [self.alice["id"]]}) + + def test_chat_access(self): + outsider = self.assert_error("GET", self.path, 404, "not_found", actor=self.eve) + missing = self.assert_error("GET", "/api/v1/chats/" + str(uuid4()), 404, "not_found", actor=self.eve) + self.assertEqual(outsider["message"], missing["message"]) + self.assert_error("GET", self.path + "/messages", 404, "not_found", actor=self.eve) + self.assert_error("POST", self.path + "/messages", 404, "not_found", actor=self.eve, body={"text": "Чужое"}) + self.assertEqual(self.read_all("/api/v1/chats", self.eve, "ChatPage"), []) + self.assert_error("GET", "/api/v1/chats/not-a-uuid", 400, "invalid_request", actor=self.alice) + + def test_invalid_message_fields(self): + for text in ("", " \t\n", "👋" * 4001, 123, True, None, []): + with self.subTest(text_type=type(text).__name__): + self.assert_error("POST", self.path + "/messages", 400, "invalid_request", + actor=self.alice, body={"text": text}) + self.assert_error("POST", self.path + "/messages", 400, "invalid_request", actor=self.alice, + body={"text": "Подмена автора", "sender_id": self.bob["id"]}) + self.assertEqual(self.read_all(self.path + "/messages", self.alice, "MessagePage"), []) + + def test_unicode_and_text_preservation(self): + for text in (" Привет, мир 👋\n", "👋" * 4000): + message = self.client.message(self.bob, self.chat, text)["json"] + self.assertEqual(message["text"], text) + self.assertEqual(message["sender_id"], self.bob["id"]) + items = self.read_all(self.path + "/messages", self.alice, "MessagePage") + self.assertEqual([item["text"] for item in items], [" Привет, мир 👋\n", "👋" * 4000]) + + def test_message_pagination_and_changing_limit(self): + sent = [self.client.message(self.alice, self.chat, f"Сообщение {i}")["json"] for i in range(8)] + items = self.read_all(self.path + "/messages", self.bob, "MessagePage", limit=3) + self.assertEqual(items, sorted(sent, key=lambda item: (item["created_at"], item["id"]))) + first = self.client.call("GET", self.path + "/messages?limit=1", actor=self.alice, schema="MessagePage")["json"] + query = urlencode({"limit": 100, "cursor": first["next_cursor"]}) + rest = self.client.call("GET", self.path + "/messages?" + query, actor=self.alice, schema="MessagePage")["json"] + self.assertEqual(first["items"] + rest["items"], items) + self.assertIsNone(rest["next_cursor"]) + + def test_default_page_size(self): + for i in range(51): + self.client.message(self.alice, self.chat, f"Сообщение {i}") + page = self.client.call("GET", self.path + "/messages", actor=self.alice, schema="MessagePage")["json"] + self.assertEqual(len(page["items"]), 50) + self.assertIsNotNone(page["next_cursor"]) + + def test_chat_pagination_and_cursor_owner(self): + for i in range(4): + self.client.call("POST", "/api/v1/chats", 201, actor=self.alice, + body={"title": f"Чат {i}", "member_ids": [self.alice["id"], self.bob["id"]]}) + chats = self.read_all("/api/v1/chats", self.alice, "ChatPage", limit=2) + self.assertEqual(len(chats), 5) + self.assertEqual(len({chat["id"] for chat in chats}), 5) + self.assertEqual(chats, sorted(chats, key=lambda item: (item["created_at"], item["id"]))) + first = self.client.call("GET", "/api/v1/chats?limit=1", actor=self.alice, schema="ChatPage")["json"] + query = urlencode({"cursor": first["next_cursor"]}) + self.assert_error("GET", "/api/v1/chats?" + query, 400, "invalid_request", actor=self.bob) + + def test_invalid_limits_and_cursors(self): + bad_queries = [{"limit": value} for value in ("0", "101", "-1", "1.5", "1.0", "abc", "")] + bad_queries += [{"cursor": value} for value in ("", "not-base64!", "e30=", "W10=")] + for path in ("/api/v1/chats", self.path + "/messages"): + for query in bad_queries: + with self.subTest(path=path, query=query): + self.assert_error("GET", path + "?" + urlencode(query), 400, "invalid_request", actor=self.alice) + + def test_cursor_cannot_be_used_for_another_chat_or_changed(self): + for i in range(2): + self.client.message(self.alice, self.chat, f"Сообщение {i}") + first = self.client.call("GET", self.path + "/messages?limit=1", actor=self.alice, schema="MessagePage")["json"] + cursor = first["next_cursor"] + other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat", + body={"title": "Другой чат", "member_ids": [self.alice["id"]]})["json"] + path = "/api/v1/chats/" + other["id"] + "/messages?" + urlencode({"cursor": cursor}) + self.assert_error("GET", path, 400, "invalid_request", actor=self.alice) + data = json.loads(base64.urlsafe_b64decode(cursor)) + data["id"] = str(uuid4()) + changed = base64.urlsafe_b64encode(json.dumps(data).encode()).decode() + self.assert_error("GET", self.path + "/messages?" + urlencode({"cursor": changed}), + 400, "invalid_request", actor=self.alice) + + def test_framework_errors_and_request_ids(self): + first = self.assert_error("GET", "/unknown", 404, "not_found") + second = self.assert_error("GET", "/unknown", 404, "not_found") + self.assertNotEqual(first["request_id"], second["request_id"]) + self.assert_error("POST", "/health/live", 405, "invalid_request") diff --git a/student-tests/test_attachments.py b/student-tests/test_attachments.py new file mode 100644 index 0000000..338e7ad --- /dev/null +++ b/student-tests/test_attachments.py @@ -0,0 +1,133 @@ +import hashlib +import http.client +import io +import json +import struct +from urllib.parse import urlencode, urlsplit +from uuid import uuid4 +import zlib + +from PIL import Image + +from helpers import ApiTestCase, ROOT + + +class AttachmentTests(ApiTestCase): + def upload(self, data=None, filename="photo.png", content_type="image/png", expected=201, actor=None): + if data is None: + data = (ROOT / "tests/fixtures/sample.png").read_bytes() + return self.client.call("POST", self.path + "/attachments?" + urlencode({"filename": filename}), + expected, actor=actor or self.alice, raw=data, + headers={"Content-Type": content_type}, schema="Attachment" if expected == 201 else None) + + def test_png_and_jpeg_originals(self): + jpeg = io.BytesIO() + Image.new("RGB", (100, 60), "orange").save(jpeg, format="JPEG") + for data, mime, filename in (((ROOT / "tests/fixtures/sample.png").read_bytes(), "image/png", "Фото 👋.png"), + (jpeg.getvalue(), "image/jpeg", "photo.jpeg")): + with self.subTest(mime=mime): + attachment = self.upload(data, filename, mime)["json"] + self.assertEqual(attachment["filename"], filename) + self.assertEqual(attachment["status"], "ready") + self.assertEqual(attachment["variants"], []) + self.assertIsNone(attachment["error_code"]) + self.assertEqual(attachment["sha256"], hashlib.sha256(data).hexdigest()) + self.assertEqual(attachment["size_bytes"], len(data)) + self.assertEqual(self.client.call("GET", "/api/v1/attachments/" + attachment["id"], + actor=self.bob, schema="Attachment")["json"], attachment) + result = self.client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=self.bob) + self.assertEqual(result["bytes"], data) + self.assertEqual(result["headers"].get_content_type(), mime) + self.assertEqual(result["headers"]["X-Content-Type-Options"], "nosniff") + + def test_corruption_and_mime_spoof(self): + png = (ROOT / "tests/fixtures/sample.png").read_bytes() + for data, mime in ((png, "image/jpeg"), (png[:50], "image/png"), + (b"not an image", "image/png"), (b"", "image/png"), + (b"GIF89a", "image/png"), (png, "application/octet-stream")): + with self.subTest(size=len(data), mime=mime): + result = self.upload(data, content_type=mime, expected=415) + self.assertEqual(result["json"]["error"]["code"], "unsupported_media_type") + + def test_filename_rejected_before_storage(self): + for filename in ("", " ", "../a.png", "a/b.png", "a\\b.png", "a\x00.png", "a\r\n.png", "a\x7f.png", "a" * 256): + with self.subTest(filename=repr(filename)): + result = self.upload(filename=filename, expected=400) + self.assertEqual(result["json"]["error"]["code"], "invalid_request") + self.client.call("POST", self.path + "/attachments", 400, actor=self.alice, raw=b"x", + headers={"Content-Type": "image/png"}) + + def test_content_length_limit_before_body(self): + self.client.call("POST", self.path + "/attachments?filename=a.png", 413, actor=self.alice, + raw=b"x", headers={"Content-Type": "image/png", "Content-Length": str(10485761)}) + + def test_chunked_limit_without_content_length(self): + target = urlsplit(self.client.base) + connection = http.client.HTTPConnection(target.hostname, target.port, timeout=15) + try: + connection.request("POST", self.path + "/attachments?filename=large.png", + body=iter([b"x" * 65536] * 160 + [b"x"]), + headers={"Authorization": "Bearer " + self.alice["token"], "Content-Type": "image/png"}, + encode_chunked=True) + response = connection.getresponse() + self.assertEqual(response.status, 413) + self.assertEqual(json.loads(response.read())["error"]["code"], "payload_too_large") + finally: + connection.close() + + def test_pixel_limit_before_decode(self): + def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + # Размеры в корректном IHDR превышают лимит; pixel data вообще не выделяется. + data = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 10000, 4001, 8, 2, 0, 0, 0)) + data += chunk(b"IDAT", b"") + chunk(b"IEND", b"") + self.upload(data, expected=413) + + def test_access_and_authentication(self): + attachment = self.upload()["json"] + for suffix in ("", "/content"): + path = "/api/v1/attachments/" + attachment["id"] + suffix + self.assert_error("GET", path, 401, "unauthorized") + self.assert_error("GET", path, 404, "not_found", actor=self.eve) + self.assert_error("GET", "/api/v1/attachments/" + str(uuid4()) + suffix, + 404, "not_found", actor=self.eve) + self.upload(expected=404, actor=self.eve) + self.client.call("POST", self.path + "/attachments?filename=../bad", 401, + raw=b"x", headers={"Content-Type": "image/png"}) + self.assert_error("GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail", + 404, "not_found", actor=self.alice) + + def test_attachment_only_message_and_other_member(self): + attachment = self.upload()["json"] + message = self.client.message(self.bob, self.chat, "", attachments=[attachment["id"]])["json"] + self.assertEqual(message["attachment_ids"], [attachment["id"]]) + self.assertEqual(message["sender_id"], self.bob["id"]) + self.assertEqual(self.read_all(self.path + "/messages", self.alice, "MessagePage"), [message]) + + def test_foreign_and_unknown_attachment_ids(self): + attachment = self.upload()["json"] + other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat", + body={"title": "Другой чат", "member_ids": [self.alice["id"]]})["json"] + for chat_id, ids in ((self.chat["id"], [str(uuid4())]), (other["id"], [attachment["id"]])): + self.assert_error("POST", "/api/v1/chats/" + chat_id + "/messages", 404, "not_found", actor=self.alice, + body={"text": "", "attachment_ids": ids}) + + def test_invalid_attachment_lists(self): + attachment = self.upload()["json"] + for ids in ([attachment["id"], attachment["id"].upper()], [str(uuid4()) for _ in range(11)], + ["not-a-uuid"], [True], None, "uuid"): + self.assert_error("POST", self.path + "/messages", 400, "invalid_request", actor=self.alice, + body={"text": "Текст", "attachment_ids": ids}) + + def test_idempotency_includes_ordered_attachment_ids(self): + first, second = self.upload()["json"], self.upload()["json"] + key = uuid4().hex + ids = [first["id"], second["id"]] + saved = self.client.message(self.alice, self.chat, "", key=key, attachments=ids)["json"] + self.assertEqual(self.client.message(self.alice, self.chat, "", key=key, attachments=ids)["json"], saved) + for changed in ([second["id"], first["id"]], [first["id"]]): + self.assert_error("POST", self.path + "/messages", 409, "conflict", actor=self.alice, + body={"text": "", "attachment_ids": changed}, headers={"Idempotency-Key": key}) + key = uuid4().hex + saved = self.client.message(self.alice, self.chat, "Без файла", key=key)["json"] + self.assertEqual(self.client.message(self.alice, self.chat, "Без файла", key=key, attachments=[])["json"], saved) diff --git a/student-tests/test_concurrency.py b/student-tests/test_concurrency.py new file mode 100644 index 0000000..abebb61 --- /dev/null +++ b/student-tests/test_concurrency.py @@ -0,0 +1,47 @@ +from concurrent.futures import ThreadPoolExecutor +import threading +from uuid import uuid4 + +from helpers import ApiTestCase, Client + + +class ConcurrencyTests(ApiTestCase): + def test_ten_clients_send_one_hundred_messages(self): + barrier = threading.Barrier(10) + + def send_messages(worker): + client = Client() + actor = self.alice if worker % 2 == 0 else self.bob + barrier.wait(timeout=10) + sent = [] + for index in range(10): + message = client.message(actor, self.chat, f"parallel-{worker}-{index}")["json"] + self.assertEqual(message["sender_id"], actor["id"]) + sent.append(message) + return sent + + with ThreadPoolExecutor(max_workers=10) as pool: + batches = list(pool.map(send_messages, range(10))) + sent = [message for batch in batches for message in batch] + history = self.read_all(self.path + "/messages", self.alice, "MessagePage", limit=17) + self.assertEqual(len(history), 100) + self.assertEqual(len({message["id"] for message in history}), 100) + self.assertEqual(history, sorted(sent, key=lambda item: (item["created_at"], item["id"]))) + self.assertEqual({message["text"] for message in history}, + {f"parallel-{worker}-{index}" for worker in range(10) for index in range(10)}) + print("PASS: 10 clients sent 100 messages; history contains exactly 100 unique messages.") + + def test_simultaneous_registration_of_one_username(self): + username = "race_" + uuid4().hex[:20] + barrier = threading.Barrier(10) + + def register(worker): + client = Client() + barrier.wait(timeout=10) + return client.call("POST", "/api/v1/users", [201, 409], + body={"username": username, "display_name": f"Клиент {worker}", "password": "Synthetic-password-123"})["status"] + + with ThreadPoolExecutor(max_workers=10) as pool: + statuses = list(pool.map(register, range(10))) + self.assertEqual(statuses.count(201), 1) + self.assertEqual(statuses.count(409), 9) diff --git a/student-tests/test_idempotency.py b/student-tests/test_idempotency.py new file mode 100644 index 0000000..a53fd30 --- /dev/null +++ b/student-tests/test_idempotency.py @@ -0,0 +1,62 @@ +from concurrent.futures import ThreadPoolExecutor +import json +import threading +from uuid import uuid4 + +from helpers import ApiTestCase, Client + + +class IdempotencyTests(ApiTestCase): + def test_parallel_replay_across_replicas(self): + key = uuid4().hex + barrier = threading.Barrier(20) + + def send(_): + client = Client() + barrier.wait(timeout=10) + return client.message(self.alice, self.chat, "Одно сообщение 👋", key=key) + + with ThreadPoolExecutor(max_workers=20) as pool: + responses = list(pool.map(send, range(20))) + self.assertGreaterEqual(len({r["headers"]["X-Instance-Id"] for r in responses}), 2) + self.assertTrue(all(r["json"] == responses[0]["json"] for r in responses)) + self.assertEqual(self.read_all(self.path + "/messages", self.bob, "MessagePage"), [responses[0]["json"]]) + + def test_key_format_and_missing_key(self): + for key in (None, "", " ", "a b", "a/b", "a" * 129): + with self.subTest(key=key): + headers = {} if key is None else {"Idempotency-Key": key} + self.client.call("POST", self.path + "/messages", 400, actor=self.alice, + body={"text": "Текст"}, headers=headers) + for key in ("A", "a" * 128, "ABCdef012._:-"): + self.client.message(self.alice, self.chat, key, key=key) + + def test_conflict_and_semantic_json_replay(self): + key = uuid4().hex + first = self.client.message(self.alice, self.chat, "Текст 👋", key=key)["json"] + replay = self.client.call("POST", self.path + "/messages", 201, actor=self.alice, + raw=json.dumps({"text": "Текст 👋"}, ensure_ascii=True, indent=2).encode(), + headers={"Content-Type": "application/json", "Idempotency-Key": key}, + schema="Message")["json"] + self.assertEqual(first, replay) + self.assert_error("POST", self.path + "/messages", 409, "conflict", actor=self.alice, + body={"text": "Другой"}, headers={"Idempotency-Key": key}) + self.assertEqual(self.read_all(self.path + "/messages", self.bob, "MessagePage"), [first]) + + def test_scope_is_user_and_chat(self): + key = uuid4().hex + first = self.client.message(self.alice, self.chat, "Алиса", key=key)["json"] + second = self.client.message(self.bob, self.chat, "Боб", key=key)["json"] + other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat", + body={"title": "Другой чат", "member_ids": [self.alice["id"]]})["json"] + third = self.client.message(self.alice, other, "Другой чат", key=key)["json"] + self.assertEqual(len({first["id"], second["id"], third["id"]}), 3) + + def test_replay_rechecks_session_and_access(self): + key = uuid4().hex + self.client.message(self.alice, self.chat, "Текст", key=key) + self.client.call("POST", self.path + "/messages", 404, actor=self.eve, + body={"text": "Текст"}, headers={"Idempotency-Key": key}) + self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice) + self.client.call("POST", self.path + "/messages", 401, actor=self.alice, + body={"text": "Текст"}, headers={"Idempotency-Key": key}) diff --git a/student-tests/test_sessions.py b/student-tests/test_sessions.py new file mode 100644 index 0000000..d95c4d4 --- /dev/null +++ b/student-tests/test_sessions.py @@ -0,0 +1,51 @@ +import base64 +from uuid import uuid4 + +from helpers import ApiTestCase + + +class SessionTests(ApiTestCase): + def basic(self, username, password): + value = base64.b64encode((username + ":" + password).encode()).decode() + return {"Authorization": "Basic " + value} + + def test_wrong_password_and_basic_only_for_login(self): + registration = self.alice["registration"] + self.assert_error("POST", "/api/v1/auth/sessions", 401, "unauthorized", + headers=self.basic(registration["username"], "wrong-password")) + self.assert_error("POST", "/api/v1/auth/sessions", 401, "unauthorized") + self.assert_error("POST", "/api/v1/auth/sessions", 401, "unauthorized", + headers={"Authorization": "Basic not-base64!"}) + self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized", + headers=self.basic(registration["username"], registration["password"])) + + def test_logout_revokes_only_one_session(self): + registration = self.alice["registration"] + second = self.client.call("POST", "/api/v1/auth/sessions", 201, schema="Session", + headers=self.basic(registration["username"], registration["password"]))["json"] + self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice) + self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized", actor=self.alice) + self.assert_error("DELETE", "/api/v1/auth/sessions/current", 401, "unauthorized", actor=self.alice) + self.client.call("GET", "/api/v1/users/me", schema="User", headers={"Authorization": "Bearer " + second["token"]}) + + def test_password_validation(self): + for password in ("short", "x" * 129, 123, None, " " * 12): + body = {"username": "pw_" + uuid4().hex[:20], "display_name": "Пароль", "password": password} + self.assert_error("POST", "/api/v1/users", 400, "invalid_request", body=body) + + def test_unicode_password_with_colon_and_private_response(self): + username = "pw_" + uuid4().hex[:20] + password = "Пароль:с:двоеточием-123" + user = self.client.call("POST", "/api/v1/users", 201, schema="User", + body={"username": username, "display_name": "Пароль", "password": password})["json"] + session = self.client.call("POST", "/api/v1/auth/sessions", 201, schema="Session", + headers=self.basic(username, password))["json"] + self.assertEqual(session["user"], user) + self.assertEqual(set(user), {"id", "username", "display_name", "created_at"}) + self.assertGreaterEqual(len(session["token"]), 32) + + def test_sql_like_message_is_plain_text(self): + text = "'; DROP TABLE messages; -- Привет" + message = self.client.message(self.alice, self.chat, text)["json"] + self.assertEqual(message["text"], text) + self.assertEqual(self.read_all(self.path + "/messages", self.bob, "MessagePage"), [message]) diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..0dfa3f8 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,57 @@ +# Публичные проверки + +Python **3.9+**, стандартная библиотека. Сервер уже должен быть запущен; проверки не создают готовое приложение и сами не управляют Docker. `make check` можно выполнить на исходном skeleton, `make test` — только после реализации API. Полная OpenAPI-валидация отдельно: `make validate` после установки `requirements-dev.txt` в venv. + +```sh +make check +make test BASE_URL=http://localhost:8080 +# без make: +python3 tests/smoke.py --base-url http://localhost:8080 +``` + +`smoke.py` выполняет **один сквозной сценарий**, автоматически выбирая профиль из `lab.json`: health → три пользователя → вход с lab2 → чат → сообщения → пагинация → ошибки доступа → идемпотентность с lab3 → файл с lab4 → thumbnail с lab5 → logout. Он проверяет JSON по используемому подмножеству схемы, коды/headers, Unicode, SHA-256 оригинала и фактические JPEG-размеры thumbnail. Это публичный минимум, не полный fuzz/security/load suite. + +Каждый запуск создаёт уникальных синтетических пользователей, чат и сообщения. Данные автоматически не удаляются: в API курса нет delete. Для чистого повтора используйте отдельный тестовый стенд/volume и осознанный сброс своего окружения. Session tokens хранятся только в памяти процесса и не печатаются/не сохраняются. + +## Проверка сохранности, lab2+ + +Скопируйте `scripts/restart.example.sh` в `scripts/restart.sh`, реализуйте перезапуск **API и всех используемых хранилищ** с сохранением volumes и задайте executable bit. Скрипт может опираться на ваш compose.yaml или stack.yaml. Он не должен удалять volumes, повторно seed-ить БД или менять тестовые данные. + +```sh +chmod +x scripts/restart.sh +make test-persistence ACTION_SCRIPT=scripts/restart.sh +``` + +Тест создаёт данные и сессию, запускает указанный файл без shell interpolation, ожидает готовности и проверяет те же данные **с прежним токеном**. В lab4+ также проверяется исходный файл. Hook может работать до 90 секунд, готовность затем ожидается до 90 секунд. TTL сессии для этого теста — минимум 300 секунд. Успех не доказывает, что hook действительно перезапустил БД: приложите команды/состояния контейнеров до и после. + +## Проверка отказа, lab3+ + +Реализуйте `scripts/stop-one.sh` на основе примера. `TARGET_INSTANCE_ID` в окружении содержит alias обслужившей тест API-реплики: сопоставьте его своему контейнеру/Swarm task и остановите именно его. Скрипт должен быстро вернуть 0 и **оставить эту реплику остановленной**; восстановление выполняйте отдельно. Swarm может создать новую task с другим ID — это допустимо. + +```sh +chmod +x scripts/stop-one.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +``` + +Перед отказом тест наблюдает ≥2 API-реплики; 15 секунд отправляет сообщения параллельно выполнению hook, повторяет неопределённый POST с тем же ключом, проверяет восстановление записи за ≤10 секунд, отсутствие остановленной реплики в последних ответах, сохранность подтверждённых сообщений и отсутствие дублей. Ошибки переходного периода учитываются. Затем восстановите реплику и повторите для другой. Скрипт — проверка одного отказа API, не гарантия HA БД/LB/host. Вывод hook скрыт, чтобы не утекли секреты; отлаживайте его отдельно с безопасным выводом. + +## Нагрузка + +```sh +python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json +``` + +Это простой **closed-loop** генератор POST сообщений; он ограничен производительностью клиента и страдает coordinated omission. Он выдаёт successful RPS, ошибки и p50/p95/p99 **только успешных запросов**. Во время нагрузки нет прозрачных retry; timeout мог скрыть совершённую запись, поэтому это throughput HTTP-подтверждений, не точный счётчик COMMIT. Изменение размера истории входит в профиль. Для серьёзного исследования используйте k6/Locust/wrk либо свой обоснованный генератор, а не выводите максимальную пропускную способность из одного запуска этого скрипта. Для нагрузки pipeline изображений нужен отдельный сценарий студента. + +## HTTPS, lab7 + +```sh +make test BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt +make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt +``` + +Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. TLS-тест сначала проверяет рабочее доверенное соединение, затем намеренно пустой trust store и именно ошибку проверки сертификата; network timeout не засчитывается как правильный отказ. **Внутреннее mTLS, identity/authorization, OpenBao policy и hardening проверяют отдельные тесты студента** по trust matrix. Клиентский сертификат внешнему учебному REST-клиенту не требуется: mTLS находится на внутренних связях. + +## Что ещё остаётся доказать + +Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production. diff --git a/tests/client.py b/tests/client.py new file mode 100644 index 0000000..f0499a2 --- /dev/null +++ b/tests/client.py @@ -0,0 +1,217 @@ +"""HTTP helpers for public black-box tests; Python 3.9+, standard library only.""" +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import ssl +import time +import urllib.error +import urllib.request +import uuid + +ROOT = Path(__file__).resolve().parents[1] +LAB = json.loads((ROOT / 'lab.json').read_text())['number'] +SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text()) + +class Failure(AssertionError): + pass + +def check(condition, message): + if not condition: + raise Failure(message) + +def timestamp(value): + check(isinstance(value, str) and value.endswith('Z'), 'timestamp must be UTC ending in Z') + try: + return dt.datetime.fromisoformat(value[:-1] + '+00:00') + except ValueError as exc: + raise Failure('invalid RFC3339 timestamp') from exc + +def validate(value, schema, where='response'): + """Validate the JSON Schema subset used by the supplied contract, not arbitrary OpenAPI.""" + if '$ref' in schema: + target = SPEC + for part in schema['$ref'].split('/')[1:]: + target = target[part] + return validate(value, target, where) + kinds = schema.get('type', []) + if isinstance(kinds, str): + kinds = [kinds] + matches = {'null':value is None, 'boolean':isinstance(value,bool), 'integer':isinstance(value,int) and not isinstance(value,bool), 'number':isinstance(value,(int,float)) and not isinstance(value,bool), 'string':isinstance(value,str), 'array':isinstance(value,list), 'object':isinstance(value,dict)} + if kinds: + check(any(matches.get(k,False) for k in kinds), where + ': incorrect type') + if 'enum' in schema: + check(value in schema['enum'], where + ': invalid enum') + if 'const' in schema: + check(value == schema['const'], where + ': invalid const') + if isinstance(value,dict): + props = schema.get('properties',{}) + check(all(k in value for k in schema.get('required',[])), where + ': missing required fields') + if schema.get('additionalProperties') is False: + check(not set(value).difference(props), where + ': unexpected fields') + for key, sub in props.items(): + if key in value: + validate(value[key], sub, where + '.' + key) + if isinstance(value,list): + check(len(value) >= schema.get('minItems',0), where + ': too few items') + check(len(value) <= schema.get('maxItems',float('inf')), where + ': too many items') + if schema.get('uniqueItems'): + encoded = [json.dumps(x,sort_keys=True) for x in value] + check(len(encoded)==len(set(encoded)), where + ': duplicate items') + if 'items' in schema: + for item in value: + validate(item, schema['items'], where + '[]') + if isinstance(value,str): + check(len(value) >= schema.get('minLength',0), where + ': too short') + check(len(value) <= schema.get('maxLength',float('inf')), where + ': too long') + if 'pattern' in schema: + check(re.search(schema['pattern'], value) is not None, where + ': pattern mismatch') + if schema.get('format') == 'uuid': + try: + uuid.UUID(value) + except ValueError as exc: + raise Failure(where + ': invalid UUID') from exc + if schema.get('format') == 'date-time': + timestamp(value) + if isinstance(value,(int,float)) and not isinstance(value,bool): + check(value >= schema.get('minimum',-float('inf')), where + ': below minimum') + check(value <= schema.get('maximum',float('inf')), where + ': above maximum') + if 'anyOf' in schema: + for alternative in schema['anyOf']: + try: + validate(value, alternative, where) + break + except Failure: + pass + else: + raise Failure(where + ': no anyOf branch matches') + +def shape(value, name): + validate(value, SPEC['components']['schemas'][name]) + return value + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + +class Client: + def __init__(self, base_url=None, ca_file=None, timeout=10): + self.base = (base_url or os.environ.get('BASE_URL') or ('https://localhost:8443' if LAB==7 else 'http://localhost:8080')).rstrip('/') + check(self.base.startswith(('http://','https://')), 'BASE_URL must be HTTP(S)') + check(LAB != 7 or self.base.startswith('https://'), 'lab7 requires HTTPS') + self.timeout = timeout + context = ssl.create_default_context(cafile=ca_file or os.environ.get('CA_FILE') or None) + self.opener = urllib.request.build_opener(NoRedirect(), urllib.request.HTTPSHandler(context=context)) + + def call(self, method, path, expected=200, body=None, actor=None, headers=None, raw=None, schema=None): + h = {'Accept':'application/json'} + if actor: + h['X-User-Id' if LAB==1 else 'Authorization'] = actor['id'] if LAB==1 else 'Bearer ' + actor['token'] + if body is not None: + raw = json.dumps(body,ensure_ascii=False).encode('utf-8') + h['Content-Type'] = 'application/json' + h.update(headers or {}) + req = urllib.request.Request(self.base + path, data=raw, headers=h, method=method) + start = time.monotonic() + try: + response = self.opener.open(req, timeout=self.timeout) + except urllib.error.HTTPError as error: + response = error + except (urllib.error.URLError,TimeoutError,OSError) as exc: + # Do not print URL query, headers, request body, or credentials. + raise Failure(method + ' ' + path.split('?')[0] + ': connection/TLS failure (' + type(exc).__name__ + ')') from None + with response: + status = response.code + rh = response.headers + data = response.read(16*1024*1024 + 1) + check(len(data) <= 16*1024*1024, 'response exceeds test safety limit') + allowed = [expected] if isinstance(expected,int) else expected + check(status in allowed, method + ' ' + path.split('?')[0] + ': expected ' + str(allowed) + ', received ' + str(status)) + check(bool(rh.get('X-Request-Id')), 'missing X-Request-Id') + if LAB>=3: + check(bool(rh.get('X-Instance-Id')), 'missing X-Instance-Id') + payload = None + if schema or status>=400: + check(rh.get_content_type()=='application/json', 'expected application/json') + try: + payload = json.loads(data) + except (ValueError,UnicodeError): + raise Failure('invalid response JSON') from None + shape(payload, 'Error' if status>=400 else schema) + if status>=400: + check(payload['error']['request_id']==rh.get('X-Request-Id'),'error request_id differs from header') + if status==401 and LAB>=2: + scheme = 'Basic' if path=='/api/v1/auth/sessions' else 'Bearer' + check(rh.get('WWW-Authenticate','').lower().startswith(scheme.lower()), 'incorrect WWW-Authenticate challenge') + if status==204: + check(not data, '204 must not contain body') + return {'status':status,'headers':rh,'json':payload,'bytes':data,'elapsed':time.monotonic()-start} + + def user(self, label): + username = 'u_' + label + '_' + uuid.uuid4().hex[:12] + password = 'T3st-' + uuid.uuid4().hex + body = {'username':username,'display_name':'Студент ' + label} + if LAB>=2: + body['password'] = password + user = self.call('POST','/api/v1/users',201,body=body,schema='User')['json'] + check(user['username']==username,'username changed') + actor = {'id':user['id'],'user':user,'registration':body} + if LAB>=2: + credential = base64.b64encode((username+':'+password).encode()).decode() + session = self.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')['json'] + check(session['user']==user,'session user mismatch') + check(timestamp(session['expires_at']) > dt.datetime.now(dt.timezone.utc),'session already expired') + actor['token'] = session['token'] + return actor + + def bootstrap(self): + self.call('GET','/health/live',schema='Health') + self.call('GET','/health/ready',schema='Health') + alice, bob, eve = (self.user(label) for label in ('alice','bob','eve')) + chat = self.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Контрактный тест','member_ids':[alice['id'],bob['id']]},schema='Chat')['json'] + check(set(chat['member_ids'])=={alice['id'],bob['id']},'chat member mismatch') + return alice,bob,eve,chat + + def message(self, actor, chat, text, key=None, attachments=None): + body = {'text':text} + if attachments is not None: + body['attachment_ids'] = attachments + headers = {'Idempotency-Key':key or uuid.uuid4().hex} if LAB>=3 else {} + return self.call('POST','/api/v1/chats/'+chat['id']+'/messages',201,actor=actor,body=body,headers=headers,schema='Message') + + def attachment(self, actor, chat): + content = (ROOT / 'tests/fixtures/sample.png').read_bytes() + att = self.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png',201 if LAB==4 else 202,actor=actor,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')['json'] + check(att['status']==('ready' if LAB==4 else 'queued'),'incorrect upload status') + check(att['chat_id']==chat['id'] and att['owner_id']==actor['id'],'attachment ownership mismatch') + check(att['sha256']==hashlib.sha256(content).hexdigest() and att['size_bytes']==len(content),'original checksum/size mismatch') + return att,content + + def wait_ready(self, actor, att, wait_seconds=60): + deadline = time.monotonic()+wait_seconds + while time.monotonic()=2 and i+length<=len(data),'invalid JPEG segment length') + if marker in sof: + check(length>=8,'invalid JPEG SOF') + return (int.from_bytes(data[i+5:i+7],'big'),int.from_bytes(data[i+3:i+5],'big')) + i += length + raise Failure('JPEG dimensions not found') diff --git a/tests/load.py b/tests/load.py new file mode 100644 index 0000000..ad81d59 --- /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') + print(json.dumps({'observed_instances_before':len(observed),'successful_writes':len(successes),'failed_attempts':failures,'first_recovery_seconds':round(first_recovery,3)},ensure_ascii=False)) + # Existing token, no re-login. Read all confirmations and reject duplicates. + messages = history(c,bob,chat) + ids = [m['id'] for m in messages] + check(len(ids)==len(set(ids)),'duplicated message IDs in history') + check(any(m==original for m in messages),'confirmed pre-failure message lost or altered') + for msg in successes: + check(any(m==msg for m in messages),'confirmed in-flight message lost or altered') + # Bodies are unique in this scenario: an uncertain request may exist once, never twice. + texts = [m['text'] for m in messages] + check(len(texts)==len(set(texts)),'uncertain retry created duplicate message') + if attachment: + c.call('GET','/api/v1/attachments/'+attachment['id'],actor=bob,schema='Attachment') + downloaded = c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=bob) + check(downloaded['bytes']==content,'attachment lost or changed across failure') + print('PASS: '+args.mode+' preserved confirmed data and existing session. Hook scope needs operator evidence.') + finally: + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + +if __name__=='__main__': + run(main) diff --git a/tests/smoke.py b/tests/smoke.py new file mode 100644 index 0000000..4cbfa55 --- /dev/null +++ b/tests/smoke.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""One complete public acceptance scenario, cumulative by lab number.""" +import base64 +import hashlib +import uuid +from client import Client, LAB, arguments, check, run, timestamp + + +def main(): + args = arguments('Messenger public smoke; creates synthetic users and messages') + c = Client(args.base_url,args.ca_file) + alice,bob,eve,chat = c.bootstrap() + path = '/api/v1/chats/'+chat['id'] + c.call('POST','/api/v1/users',409,body=alice['registration']) + c.call('GET','/api/v1/users/me',401) + c.call('GET',path,404,actor=eve) + me = c.call('GET','/api/v1/users/me',actor=alice,schema='User')['json'] + check(me==alice['user'],'current user mismatch') + listed = c.call('GET','/api/v1/chats?limit=100',actor=bob,schema='ChatPage')['json'] + check(any(x['id']==chat['id'] for x in listed['items']),'member cannot list chat') + hidden = c.call('GET','/api/v1/chats?limit=100',actor=eve,schema='ChatPage')['json'] + check(all(x['id']!=chat['id'] for x in hidden['items']),'chat leaks to outsider') + key = uuid.uuid4().hex + first = c.message(alice,chat,'Привет, мир 👋',key=key)['json'] + second = c.message(bob,chat,'Сообщение Боба')['json'] + check(first['sender_id']==alice['id'] and second['sender_id']==bob['id'],'sender was not derived from actor') + check(first['chat_id']==second['chat_id']==chat['id'],'wrong chat in message') + check(first['text']=='Привет, мир 👋' and second['text']=='Сообщение Боба','message text changed') + page1 = c.call('GET',path+'/messages?limit=1',actor=bob,schema='MessagePage')['json'] + check(len(page1['items'])==1 and page1['next_cursor'],'first page must have one item and cursor') + from urllib.parse import quote + page2 = c.call('GET',path+'/messages?limit=1&cursor='+quote(page1['next_cursor'],safe=''),actor=alice,schema='MessagePage')['json'] + check(len(page2['items'])==1 and page2['next_cursor'] is None,'second page must finish history') + ordered = sorted([first,second],key=lambda x:(timestamp(x['created_at']),uuid.UUID(x['id']).int)) + check(page1['items']+page2['items']==ordered,'pagination lost, duplicated or reordered a message') + h = {'Idempotency-Key':uuid.uuid4().hex} if LAB>=3 else {} + c.call('POST',path+'/messages',400,actor=alice,body={'text':''},headers=h) + c.call('POST',path+'/messages',404,actor=eve,body={'text':'чужое'},headers=h) + c.call('GET',path+'/messages?limit=0',400,actor=alice) + if LAB>=2: + bad = base64.b64encode((alice['registration']['username']+':wrong-password').encode()).decode() + c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':'Basic '+bad}) + good = base64.b64encode((alice['registration']['username']+':'+alice['registration']['password']).encode()).decode() + c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Basic '+good}) + c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':alice['id']}) + me = c.call('GET','/api/v1/users/me',actor=alice,headers={'X-User-Id':eve['id']},schema='User')['json'] + check(me['id']==alice['id'],'X-User-Id overrode bearer identity') + if LAB>=3: + replay = c.message(alice,chat,first['text'],key=key)['json'] + check(replay==first,'idempotency replay differs') + c.call('POST',path+'/messages',409,actor=alice,body={'text':'другой body'},headers={'Idempotency-Key':key}) + c.call('POST',path+'/messages',400,actor=alice,body={'text':'без ключа'}) + if LAB>=4: + att,content = c.attachment(alice,chat) + # A queued attachment must already be linkable to its own chat. + attached = c.message(alice,chat,'',attachments=[att['id']])['json'] + check(attached['attachment_ids']==[att['id']],'message lost attachment') + ready = c.wait_ready(bob,att) if LAB>=5 else att + check(ready['error_code'] is None,'ready attachment has an error') + download = c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob) + check(download['bytes']==content,'download differs from original') + check(download['headers'].get_content_type()=='image/png','original content type mismatch') + for suffix in ('','/content'): + c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=eve) + if LAB>=5: + variants = [x for x in ready['variants'] if x['name']=='thumbnail'] + check(len(variants)==1,'expected exactly one thumbnail') + v = variants[0] + check((v['width'],v['height'])==(256,160),'thumbnail metadata has wrong dimensions') + thumb = c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',actor=bob) + check(thumb['headers'].get_content_type()=='image/jpeg','thumbnail content type mismatch') + check(len(thumb['bytes'])==v['size_bytes'] and hashlib.sha256(thumb['bytes']).hexdigest()==v['sha256'],'thumbnail checksum mismatch') + from image_probe import jpeg_size + check(jpeg_size(thumb['bytes'])==(256,160),'actual JPEG dimensions mismatch') + if LAB>=2: + c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice) + c.call('GET','/api/v1/users/me',401,actor=alice) + c.call('DELETE','/api/v1/auth/sessions/current',401,actor=alice) + print('PASS: lab%d public API scenario; infrastructure and grading evidence remain separate.' % LAB) + +if __name__=='__main__': + run(main)