ЛР 3 — БПИ2303 — Гавриленко — на 3 #146
+5
-10
@@ -1,13 +1,8 @@
|
||||
# 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
|
||||
# Generated local credentials live in secrets/, not in this file.
|
||||
# scripts/setup.sh creates .env without overwriting existing files.
|
||||
HOST_PORT=8083
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
# Container settings in compose.yaml: APP_HOST=0.0.0.0, APP_PORT=8080,
|
||||
# DATABASE_URL_FILE=/run/secrets/database_url, session store=PostgreSQL.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
name: Application
|
||||
on: [push, pull_request]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
application:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- run: scripts/setup.sh
|
||||
- run: docker compose up -d --build --wait
|
||||
- run: make check test BASE_URL=http://localhost:8083
|
||||
- run: python3 student-tests/check.py --base-url http://localhost:8083
|
||||
- run: python3 student-tests/idempotency.py --base-url http://localhost:8083
|
||||
- run: docker compose exec -T api python - < student-tests/db_check.py
|
||||
- name: Stop stack
|
||||
if: always()
|
||||
run: docker compose down
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
FROM python:3.13.7-slim-bookworm
|
||||
WORKDIR /app
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY src/ src/
|
||||
COPY migrations/ migrations/
|
||||
USER 10001:10001
|
||||
EXPOSE 8080
|
||||
CMD ["python", "src/server.py"]
|
||||
@@ -1,37 +1,74 @@
|
||||
# Отчёт — лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор: Владислав Гавриленко, БПИ2303.
|
||||
- Целевая оценка: 3; исследовательские треки 5 не заявлены.
|
||||
- MR: [ЛР 3 — БПИ2303 — Гавриленко — на 3, #146](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab3/pulls/146).
|
||||
- Ветка: `solution/bpi2303-gavrilenko`, форк: https://gitea.privcloud.tech/sxdees/mtusi2026lab3.
|
||||
- Основа: собственная реализация из соседнего `mtusi2026lab2`: `src/`, миграция `001_initial.sql`, Dockerfile, зависимости, генерация secrets и собственные тесты. Первая лаба лежит в GitFlic; исходный код её HTTP API уже включён в lab2. Публичные `tests/`, `contracts/`, README задания и COURSE сохранены из skeleton lab3.
|
||||
- Источники: контракт этого репозитория, Python standard library и psycopg 3.2.10; [DNS HAProxy](https://www.haproxy.com/documentation/haproxy-configuration-tutorials/proxying-essentials/dns-resolution/), [остановка socketserver](https://docs.python.org/3.13/library/socketserver.html#socketserver.BaseServer.shutdown). Реализация и оформление подготовлены с помощью Codex.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Docker Engine с Compose v2+ и Python 3.9+ для проверок. Проверено: Docker 29.8.2, Compose 5.5.0, macOS arm64 / OrbStack, Mac15,6; Docker VM: 11 CPU, 9 434 726 400 bytes RAM. Образы: Python 3.13.7 slim-bookworm, PostgreSQL 17.6 bookworm, HAProxy 3.2.6 alpine. У API лимит 0.5 CPU / 256 MiB на реплику, БД 1 CPU / 512 MiB, LB 0.5 CPU / 128 MiB. Сторонняя зависимость API — psycopg[binary] 3.2.10.
|
||||
|
||||
```sh
|
||||
git clone -b solution/bpi2303-gavrilenko https://gitea.privcloud.tech/sxdees/mtusi2026lab3.git
|
||||
cd mtusi2026lab3
|
||||
scripts/setup.sh
|
||||
docker compose config --quiet
|
||||
docker compose up -d --build --wait
|
||||
curl --fail http://localhost:8083/health/ready
|
||||
make check test BASE_URL=http://localhost:8083
|
||||
python3 student-tests/check.py --base-url http://localhost:8083
|
||||
python3 student-tests/idempotency.py --base-url http://localhost:8083
|
||||
docker compose exec -T api python - < student-tests/db_check.py
|
||||
make test-persistence BASE_URL=http://localhost:8083 ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover BASE_URL=http://localhost:8083 ACTION_SCRIPT=scripts/stop-one.sh
|
||||
docker compose ps --all
|
||||
docker compose up -d --wait
|
||||
```
|
||||
|
||||
`setup.sh` создаёт случайный пароль, DSN в `secrets/` и `.env`, существующие файлы не перезаписывает. Secrets не коммитятся; хостовый каталог доступен только владельцу. DSN доступен UID приложения внутри контейнера через read-only mount. `HOST_PORT=8083` выбран, чтобы не мешать соседним лабораторным; тестам явно передаётся BASE_URL. На хосте опубликован только LB на loopback. `API_REPLICAS` по умолчанию 2 (для лабы минимум 2, конфигурация LB содержит до 10 мест), `SESSION_TTL_SECONDS=3600`, `IDEMPOTENCY_TTL_SECONDS=86400` (меньше 24 часов запрещено). APP_HOST/APP_PORT и путь DATABASE_URL_FILE заданы в Compose; SESSION_STORE — PostgreSQL. APP_ENV, CACHE_URL_FILE не используются.
|
||||
|
||||
Миграции запускает отдельный завершающийся service `migrate`, API ждут успешного завершения. Версии записываются в `schema_migrations`, advisory lock защищает от параллельного запуска операторами. Схема описана в [infra/schema.md](infra/schema.md), перенесённом из lab2 и дополненном таблицей ключей. Миграция 002 добавляет отдельную таблицу и совместима со старой схемой; старый API lab2 не поддерживает новую гарантию идемпотентности, смешанный запуск lab2/lab3 за одним LB не допускается. Для переноса используются исходники и миграции, существующие volumes lab2 не изменяются.
|
||||
|
||||
Остановка без потери данных: `docker compose down`. Повторный запуск: `docker compose up -d --wait`. Намеренное удаление **всех учебных данных именно этого проекта**: `docker compose down -v`. Secrets сохраняются отдельно; не менять пароль файла без изменения пароля в существующей БД.
|
||||
|
||||
Полная проверка схемы:
|
||||
|
||||
```sh
|
||||
python3 -m venv .venv
|
||||
.venv/bin/python -m pip install -r requirements-dev.txt
|
||||
make validate PYTHON=.venv/bin/python
|
||||
```
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Клиент → HAProxy round-robin → два контейнера одного Compose-service API → общая PostgreSQL. Сессии, пользователи, чаты, сообщения и ключи идемпотентности находятся в БД. Sticky session нет. Заголовок X-Instance-Id содержит hostname контейнера, стабилен в течение процесса и сопоставляется реальному контейнеру через docker inspect; все ответы API также содержат X-Request-Id. Один пользователь работает через обе реплики с одним Bearer token. Пароли хешируются scrypt с индивидуальной солью; в sessions хранится только SHA-256 случайного 256-битного токена, срок не продлевается после restart.
|
||||
|
||||
Соединение с БД и транзакция создаются на запрос; ответ отправляется после COMMIT. POST сообщения проверяет сессию, членство, тело и ключ, берёт транзакционный advisory lock по `(user_id, chat_id, key)`, проверяет прежний результат и атомарно сохраняет сообщение вместе с ключом. HTTP-метод и маршрут фиксированы обработчиком POST messages. Конкурентная реплика ждёт завершения транзакции, после чего возвращает тот же Message и 201; другой текст получает 409. Отсутствующий attachment_ids и [] эквивалентны; непустые вложения не входят в lab3. После 24 часов ключ можно использовать заново, старое сообщение сохраняется. Ошибка до COMMIT откатывает и сообщение, и ключ. После неопределённого ответа клиент повторяет тот же ключ и тело. HAProxy не повторяет POST автоматически (`retries 0`).
|
||||
|
||||
HAProxy проверяет `/health/ready` каждую секунду, исключает backend после 2 неуспехов, возвращает после 1 успеха. `timeout check=1s`, `timeout connect=1s`: консервативное ожидаемое обнаружение до 4 секунд при молчащем backend, фактический переход измеряется публичным failover. Docker DNS обновляется через resolver 127.0.0.11, hold valid/obsolete — 1s, поэтому пересозданные контейнеры обнаруживаются без рестарта LB. `/health/live` не обращается к БД; ready требует доступной БД, единственной критичной зависимости. Таймаут SQL 5s, подключения к БД 3s, LB server/client 10s; сокет API 5s. SIGTERM прекращает accept через shutdown в другом потоке; активные недемонические request threads завершаются до выхода, Compose даёт 15s.
|
||||
|
||||
История сортируется `(created_at, id)`, cursor привязан к истории чата либо списку чатов пользователя. Это не snapshot: конкурентные вставки могут попасть в следующие страницы; при обратном скачке часов запись может оказаться до уже пройденного cursor. Новое чтение через любую реплику видит подтверждённую запись из общей БД.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| Критерий уровня 3 | Команда / сценарий | Результат | Доказательство |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Воспроизводимый стенд, ≥2 API, единый LB, общие данные и сессии | `docker compose up -d --build --wait`, `docker compose ps --all` | Две реальные API-реплики; только LB публикует порт | `evidence/failover.txt` |
|
||||
| Контракт и публичный smoke | `make check`, `make validate`, `make test BASE_URL=http://localhost:8083` | PASS | `evidence/checks.txt` |
|
||||
| Одна сессия через разные реплики, конкурентный повтор без дублей | `python3 student-tests/idempotency.py --base-url http://localhost:8083` | 32 конкурентных запроса через ≥2 X-Instance-Id вернули один Message | `evidence/checks.txt` |
|
||||
| Проверки валидации и изоляции предыдущей лабы | `python3 student-tests/check.py --base-url http://localhost:8083` | PASS: Unicode, границы паролей, чужой cursor, членство | `evidence/checks.txt` |
|
||||
| Истечение сессии из lab2 | Одноразовый API с `SESSION_TTL_SECONDS=2`, `python3 student-tests/expiry.py --base-url http://localhost:18083` | Сразу 200, спустя 3s чтение и logout → 401; основной стенд остаётся на TTL=3600 | `evidence/expiry.txt` |
|
||||
| Пароли/токены, повтор миграций, rollback | `docker compose exec -T api python - < student-tests/db_check.py` | PASS: KDF/digest, FK, неизменные counts после повторных миграций | `evidence/checks.txt` |
|
||||
| Перезапуск API и всех используемых хранилищ | `make test-persistence BASE_URL=http://localhost:8083 ACTION_SCRIPT=scripts/restart.sh` | Данные и прежняя сессия сохранены; StartedAt API/БД изменились | `evidence/persistence.txt` |
|
||||
| Остановка выбранной реальной API-реплики и чтение/запись при отказе | `make test-failover BASE_URL=http://localhost:8083 ACTION_SCRIPT=scripts/stop-one.sh` | ≥2 реплик до отказа; запись восстановилась ≤10s; подтверждённые сообщения без потери и дублей | `evidence/failover.txt` |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
## Эксперименты и ограничения
|
||||
|
||||
## Эксперименты и отказы
|
||||
Проверки функциональные на локальном синтетическом стенде, без претензии на оценку 4/5 или максимальный RPS. Публичный failover работает 15 секунд, один клиент отправляет уникальные сообщения примерно раз в 0.1s, повторяя неопределённый POST с прежним ключом; до отказа 40 чтений проверяют наличие двух реплик. Для каждого запуска сохраняются successful_writes, failed_attempts и first_recovery_seconds. До испытания стенд ожидает Compose healthchecks; отдельный нагрузочный прогрев не заявлен. Остановка api-1: 97 подтверждённых записей, 2 ошибки, восстановление 1.785s (повтор: 106, 1, 1.470s); api-2: 108 записей, 2 ошибки, восстановление 2.068s. После каждого сценария обе реплики восстановлены. Итоги и реальные состояния контейнеров приведены в evidence, сессии и пароли не печатаются. Полный restart проверяется отдельно с сохранённым volume и прежним токеном.
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Отказ одного API-процесса выдерживается. LB, БД, диск и единственный Docker-host остаются SPOF; потеря их узла не исследована. Rolling update под нагрузкой, исследование масштабирования, p50/p95/p99 и уровни 4/5 не заявлены. CI приложения добавлен для GitHub Actions; Gitea этого форка не включает Actions, поэтому фактические доказательства — локальные проверки.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
`http.server` и соединение на каждый запрос — учебное упрощение. Нет TLS, ограничения числа клиентских потоков или rate limiting; HTTP допустим только для локальных синтетических данных. Истёкшие сессии и неиспользуемые ключи не чистятся фоновым заданием; истёкший ключ удаляется при повторном использовании его scope, поэтому размер БД растёт. БД должна иметь достаточно места для WAL; первому запуску мешал заполненный диск OrbStack, после очистки старого build-cache стенд успешно инициализирован. Другие лабораторные и их volumes не изменялись.
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
name: gavrilenko-lab3
|
||||
services:
|
||||
db:
|
||||
image: postgres:17.6-bookworm
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
|
||||
secrets: [db_password]
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
cpus: 1
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
migrate:
|
||||
build: .
|
||||
command: ["python", "src/db.py"]
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
secrets: [database_url]
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
cpus: 0.5
|
||||
mem_limit: 128m
|
||||
api:
|
||||
build: .
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 8080
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
secrets: [database_url]
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready', timeout=3)"]
|
||||
interval: 2s
|
||||
timeout: 4s
|
||||
retries: 15
|
||||
cpus: 0.5
|
||||
mem_limit: 256m
|
||||
stop_grace_period: 15s
|
||||
restart: unless-stopped
|
||||
lb:
|
||||
image: haproxy:3.2.6-alpine
|
||||
volumes:
|
||||
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
ports:
|
||||
- "127.0.0.1:${HOST_PORT:-8083}:8080"
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
cpus: 0.5
|
||||
mem_limit: 128m
|
||||
restart: unless-stopped
|
||||
secrets:
|
||||
db_password:
|
||||
file: ./secrets/db_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -0,0 +1,21 @@
|
||||
Date: 2026-11-13 (Europe/Moscow)
|
||||
Target: http://localhost:8083 (HAProxy -> 2 API processes -> PostgreSQL)
|
||||
|
||||
$ make check
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
$ make validate PYTHON=.venv/bin/python
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
$ make test BASE_URL=http://localhost:8083
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
$ python3 student-tests/check.py --base-url http://localhost:8083
|
||||
PASS: validation, access, Unicode, pagination and cursor scope
|
||||
PASS: malformed JSON and duplicate username
|
||||
PASS: Unicode/colon passwords, length boundaries, invalid chat creation
|
||||
$ python3 student-tests/idempotency.py --base-url http://localhost:8083
|
||||
PASS: 32 concurrent retries across >=2 replicas: one message; conflict, access, key scope and validation
|
||||
$ postman request http://localhost:8083/health/ready --script-post-request <health assertions>
|
||||
200 OK; 1 test passed (status, JSON and both tracing headers); exit 0
|
||||
$ docker compose exec -T api python - < student-tests/db_check.py
|
||||
PASS: repeated migrations preserve row counts; scrypt/token digests; FK and transaction rollback
|
||||
$ docker compose exec -T lb haproxy -c -f /usr/local/etc/haproxy/haproxy.cfg
|
||||
exit 0 (configuration valid)
|
||||
@@ -0,0 +1,3 @@
|
||||
$ docker compose run --rm -d --no-deps -e SESSION_TTL_SECONDS=2 -p 127.0.0.1:18083:8080 api
|
||||
$ python3 student-tests/expiry.py --base-url http://localhost:18083
|
||||
PASS: session expires with TTL=2; expired token cannot read or logout
|
||||
@@ -0,0 +1,123 @@
|
||||
$ docker compose ps --all
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
gavrilenko-lab3-api-1 gavrilenko-lab3-api "python src/server.py" api 2 minutes ago Up 13 seconds (healthy) 8080/tcp
|
||||
gavrilenko-lab3-api-2 gavrilenko-lab3-api "python src/server.py" api 2 minutes ago Up 12 seconds (healthy) 8080/tcp
|
||||
gavrilenko-lab3-db-1 postgres:17.6-bookworm "docker-entrypoint.s…" db 2 minutes ago Up 19 seconds (healthy) 5432/tcp
|
||||
gavrilenko-lab3-lb-1 haproxy:3.2.6-alpine "docker-entrypoint.s…" lb 2 minutes ago Up 2 seconds 127.0.0.1:8083->8080/tcp
|
||||
gavrilenko-lab3-migrate-1 gavrilenko-lab3-migrate "python src/db.py" migrate 2 minutes ago Exited (0) 13 seconds ago
|
||||
$ make test-failover BASE_URL=http://localhost:8083 ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8083"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 97, "failed_attempts": 2, "first_recovery_seconds": 1.785}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
$ docker compose ps --all
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
gavrilenko-lab3-api-1 gavrilenko-lab3-api "python src/server.py" api 2 minutes ago Exited (0) 14 seconds ago
|
||||
gavrilenko-lab3-api-2 gavrilenko-lab3-api "python src/server.py" api 2 minutes ago Up 30 seconds (healthy) 8080/tcp
|
||||
gavrilenko-lab3-db-1 postgres:17.6-bookworm "docker-entrypoint.s…" db 2 minutes ago Up 38 seconds (healthy) 5432/tcp
|
||||
gavrilenko-lab3-lb-1 haproxy:3.2.6-alpine "docker-entrypoint.s…" lb 2 minutes ago Up 21 seconds 127.0.0.1:8083->8080/tcp
|
||||
gavrilenko-lab3-migrate-1 gavrilenko-lab3-migrate "python src/db.py" migrate 2 minutes ago Exited (0) 32 seconds ago
|
||||
$ docker compose up -d --wait
|
||||
Container gavrilenko-lab3-db-1 Running
|
||||
Container gavrilenko-lab3-api-2 Running
|
||||
Container gavrilenko-lab3-lb-1 Running
|
||||
Container gavrilenko-lab3-db-1 Waiting
|
||||
Container gavrilenko-lab3-db-1 Healthy
|
||||
Container gavrilenko-lab3-migrate-1 Starting
|
||||
Container gavrilenko-lab3-migrate-1 Started
|
||||
Container gavrilenko-lab3-migrate-1 Waiting
|
||||
Container gavrilenko-lab3-migrate-1 Exited
|
||||
Container gavrilenko-lab3-api-1 Starting
|
||||
Container gavrilenko-lab3-api-1 Started
|
||||
Container gavrilenko-lab3-api-1 Waiting
|
||||
Container gavrilenko-lab3-api-2 Waiting
|
||||
Container gavrilenko-lab3-api-1 Healthy
|
||||
Container gavrilenko-lab3-api-2 Healthy
|
||||
Container gavrilenko-lab3-db-1 Waiting
|
||||
Container gavrilenko-lab3-migrate-1 Waiting
|
||||
Container gavrilenko-lab3-api-1 Waiting
|
||||
Container gavrilenko-lab3-api-2 Waiting
|
||||
Container gavrilenko-lab3-lb-1 Waiting
|
||||
Container gavrilenko-lab3-migrate-1 Exited
|
||||
Container gavrilenko-lab3-lb-1 Healthy
|
||||
Container gavrilenko-lab3-db-1 Healthy
|
||||
Container gavrilenko-lab3-api-1 Healthy
|
||||
Container gavrilenko-lab3-api-2 Healthy
|
||||
$ make test-failover BASE_URL=http://localhost:8083 ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8083"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 106, "failed_attempts": 1, "first_recovery_seconds": 1.47}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
$ docker compose ps --all
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
gavrilenko-lab3-api-1 gavrilenko-lab3-api "python src/server.py" api 2 minutes ago Exited (0) 15 seconds ago
|
||||
gavrilenko-lab3-api-2 gavrilenko-lab3-api "python src/server.py" api 2 minutes ago Up 56 seconds (healthy) 8080/tcp
|
||||
gavrilenko-lab3-db-1 postgres:17.6-bookworm "docker-entrypoint.s…" db 2 minutes ago Up About a minute (healthy) 5432/tcp
|
||||
gavrilenko-lab3-lb-1 haproxy:3.2.6-alpine "docker-entrypoint.s…" lb 2 minutes ago Up 47 seconds 127.0.0.1:8083->8080/tcp
|
||||
gavrilenko-lab3-migrate-1 gavrilenko-lab3-migrate "python src/db.py" migrate 2 minutes ago Exited (0) 20 seconds ago
|
||||
$ docker compose up -d --wait
|
||||
Container gavrilenko-lab3-api-2 Running
|
||||
Container gavrilenko-lab3-lb-1 Running
|
||||
Container gavrilenko-lab3-db-1 Running
|
||||
Container gavrilenko-lab3-db-1 Waiting
|
||||
Container gavrilenko-lab3-db-1 Healthy
|
||||
Container gavrilenko-lab3-migrate-1 Starting
|
||||
Container gavrilenko-lab3-migrate-1 Started
|
||||
Container gavrilenko-lab3-migrate-1 Waiting
|
||||
Container gavrilenko-lab3-migrate-1 Exited
|
||||
Container gavrilenko-lab3-api-1 Starting
|
||||
Container gavrilenko-lab3-api-1 Started
|
||||
Container gavrilenko-lab3-api-1 Waiting
|
||||
Container gavrilenko-lab3-api-2 Waiting
|
||||
Container gavrilenko-lab3-api-1 Healthy
|
||||
Container gavrilenko-lab3-api-2 Healthy
|
||||
Container gavrilenko-lab3-api-1 Waiting
|
||||
Container gavrilenko-lab3-api-2 Waiting
|
||||
Container gavrilenko-lab3-lb-1 Waiting
|
||||
Container gavrilenko-lab3-db-1 Waiting
|
||||
Container gavrilenko-lab3-migrate-1 Waiting
|
||||
Container gavrilenko-lab3-lb-1 Healthy
|
||||
Container gavrilenko-lab3-migrate-1 Exited
|
||||
Container gavrilenko-lab3-db-1 Healthy
|
||||
Container gavrilenko-lab3-api-1 Healthy
|
||||
Container gavrilenko-lab3-api-2 Healthy
|
||||
|
||||
One GET /health/ready through LB before the next run shifts round-robin to target the other replica.
|
||||
$ make test-failover BASE_URL=http://localhost:8083 ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8083"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 108, "failed_attempts": 2, "first_recovery_seconds": 2.068}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
$ docker compose ps --all
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
gavrilenko-lab3-api-1 gavrilenko-lab3-api "python src/server.py" api 3 minutes ago Up 58 seconds (healthy) 8080/tcp
|
||||
gavrilenko-lab3-api-2 gavrilenko-lab3-api "python src/server.py" api 3 minutes ago Exited (0) 14 seconds ago
|
||||
gavrilenko-lab3-db-1 postgres:17.6-bookworm "docker-entrypoint.s…" db 3 minutes ago Up 2 minutes (healthy) 5432/tcp
|
||||
gavrilenko-lab3-lb-1 haproxy:3.2.6-alpine "docker-entrypoint.s…" lb 3 minutes ago Up About a minute 127.0.0.1:8083->8080/tcp
|
||||
gavrilenko-lab3-migrate-1 gavrilenko-lab3-migrate "python src/db.py" migrate 3 minutes ago Exited (0) 58 seconds ago
|
||||
$ docker compose up -d --wait
|
||||
Container gavrilenko-lab3-db-1 Running
|
||||
Container gavrilenko-lab3-api-1 Running
|
||||
Container gavrilenko-lab3-lb-1 Running
|
||||
Container gavrilenko-lab3-db-1 Waiting
|
||||
Container gavrilenko-lab3-db-1 Healthy
|
||||
Container gavrilenko-lab3-migrate-1 Starting
|
||||
Container gavrilenko-lab3-migrate-1 Started
|
||||
Container gavrilenko-lab3-migrate-1 Waiting
|
||||
Container gavrilenko-lab3-migrate-1 Exited
|
||||
Container gavrilenko-lab3-api-2 Starting
|
||||
Container gavrilenko-lab3-api-2 Started
|
||||
Container gavrilenko-lab3-api-1 Waiting
|
||||
Container gavrilenko-lab3-api-2 Waiting
|
||||
Container gavrilenko-lab3-api-1 Healthy
|
||||
Container gavrilenko-lab3-api-2 Healthy
|
||||
Container gavrilenko-lab3-db-1 Waiting
|
||||
Container gavrilenko-lab3-migrate-1 Waiting
|
||||
Container gavrilenko-lab3-api-1 Waiting
|
||||
Container gavrilenko-lab3-api-2 Waiting
|
||||
Container gavrilenko-lab3-lb-1 Waiting
|
||||
Container gavrilenko-lab3-db-1 Healthy
|
||||
Container gavrilenko-lab3-migrate-1 Exited
|
||||
Container gavrilenko-lab3-lb-1 Healthy
|
||||
Container gavrilenko-lab3-api-1 Healthy
|
||||
Container gavrilenko-lab3-api-2 Healthy
|
||||
@@ -0,0 +1,14 @@
|
||||
$ docker inspect --format {{.Name}} hostname={{.Config.Hostname}} started={{.State.StartedAt}} state={{.State.Status}} e6aad67b69def6b3867741a9bcc71efdc72edd03885100c385b11d4ba2da453c f5ace66445e4404719b61bb2d5a767054aa2314d91dd207285f6e17f1d825936 881d45407c55b87e8083f274525af1df44ccf3e553d1749182f85fd8f623a976 a83705328a2f1d3c41fab0cc98bea420abc60fa5d6645a8f05ba3c47ea65c73f
|
||||
/gavrilenko-lab3-api-1 hostname=e6aad67b69de started=2026-11-12T22:26:19.8835515Z state=running
|
||||
/gavrilenko-lab3-api-2 hostname=f5ace66445e4 started=2026-11-12T22:26:20.026043451Z state=running
|
||||
/gavrilenko-lab3-db-1 hostname=881d45407c55 started=2026-11-12T22:26:14.633660903Z state=running
|
||||
/gavrilenko-lab3-lb-1 hostname=a83705328a2f started=2026-11-12T22:26:22.725809727Z state=running
|
||||
$ make test-persistence BASE_URL=http://localhost:8083 ACTION_SCRIPT=scripts/restart.sh
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8083"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
$ docker inspect --format {{.Name}} hostname={{.Config.Hostname}} started={{.State.StartedAt}} state={{.State.Status}} e6aad67b69def6b3867741a9bcc71efdc72edd03885100c385b11d4ba2da453c f5ace66445e4404719b61bb2d5a767054aa2314d91dd207285f6e17f1d825936 881d45407c55b87e8083f274525af1df44ccf3e553d1749182f85fd8f623a976 a83705328a2f1d3c41fab0cc98bea420abc60fa5d6645a8f05ba3c47ea65c73f
|
||||
/gavrilenko-lab3-api-1 hostname=e6aad67b69de started=2026-11-12T22:27:26.135706979Z state=running
|
||||
/gavrilenko-lab3-api-2 hostname=f5ace66445e4 started=2026-11-12T22:27:27.202190304Z state=running
|
||||
/gavrilenko-lab3-db-1 hostname=881d45407c55 started=2026-11-12T22:27:19.675343407Z state=running
|
||||
/gavrilenko-lab3-lb-1 hostname=a83705328a2f started=2026-11-12T22:27:36.411363828Z state=running
|
||||
@@ -0,0 +1,31 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 256
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
timeout connect 1s
|
||||
timeout client 10s
|
||||
timeout server 10s
|
||||
timeout check 1s
|
||||
retries 0
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 1s
|
||||
hold obsolete 1s
|
||||
hold nx 1s
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
default_backend messenger
|
||||
|
||||
backend messenger
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
server-template api 10 api:8080 check inter 1s fall 2 rise 1 resolvers docker init-addr libc,none
|
||||
@@ -0,0 +1,21 @@
|
||||
# Схема PostgreSQL (перенесена из lab2)
|
||||
|
||||
PostgreSQL — единственный источник истины. UUID назначает API, время — БД (timestamptz).
|
||||
|
||||
- users: PK id, UNIQUE username, display_name, created_at, соль и scrypt digest пароля.
|
||||
- chats: PK id, title, created_at.
|
||||
- chat_members: составной PK (chat_id, user_id), FK на chats/users; индекс (user_id, chat_id) для списка чатов.
|
||||
- messages: PK id, FK chat_id, составной FK (chat_id, sender_id) на членство,
|
||||
text, created_at; индекс (chat_id, created_at, id) для keyset истории.
|
||||
- sessions: PK SHA-256 случайного 256-битного токена, FK user_id, expires_at.
|
||||
Сам токен хранится только у клиента. Пароль хешируется scrypt, не SHA-256.
|
||||
- message_keys: составной PK (user_id, chat_id, key), FK на users/chats/messages, expires_at;
|
||||
сохраняется в той же транзакции, что и сообщение, после advisory lock по scope.
|
||||
- schema_migrations: PK имени применённого SQL-файла.
|
||||
|
||||
Каждый запрос использует отдельную транзакцию. Успешный ответ отправляется после
|
||||
COMMIT. Создание чата и всех участников — одна транзакция; ошибка откатывает всё.
|
||||
Регистрация опирается на UNIQUE БД, отзыв сессии — DELETE. Expiry проверяется
|
||||
по часам БД при каждом защищённом запросе, рестарт не меняет expires_at.
|
||||
Миграции выполняются отдельным Compose-service migrate под транзакционной advisory lock;
|
||||
повторный запуск пропускает записанные версии. API ждут успешного завершения миграций.
|
||||
@@ -0,0 +1,33 @@
|
||||
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 (length(btrim(display_name)) > 0),
|
||||
password_salt bytea NOT NULL,
|
||||
password_hash bytea NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title varchar(100) NOT NULL CHECK (length(btrim(title)) > 0),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX chat_members_user ON chat_members(user_id, chat_id);
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
sender_id uuid NOT NULL,
|
||||
text varchar(4000) NOT NULL CHECK (length(btrim(text)) > 0),
|
||||
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 ON messages(chat_id, created_at, id);
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE message_keys (
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
key varchar(128) NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages(id),
|
||||
expires_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (user_id, chat_id, key)
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
psycopg[binary]==3.2.10
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose stop lb api db
|
||||
docker compose up -d --wait
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 - <<'PY'
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
os.umask(0o077)
|
||||
root = Path('secrets')
|
||||
root.mkdir(exist_ok=True)
|
||||
password_file = root / 'db_password'
|
||||
if not password_file.exists():
|
||||
password_file.write_text(secrets.token_hex(32))
|
||||
password = password_file.read_text().strip()
|
||||
url = root / 'database_url'
|
||||
if not url.exists():
|
||||
from urllib.parse import quote
|
||||
url.write_text('postgresql://messenger:' + quote(password, safe='') + '@db:5432/messenger')
|
||||
# Private parent directory protects files on the host; API UID must read its mount.
|
||||
url.chmod(0o644)
|
||||
if not Path('.env').exists():
|
||||
Path('.env').write_text('HOST_PORT=8083\nSESSION_TTL_SECONDS=3600\n')
|
||||
print('Local secrets and .env ready (existing files preserved)')
|
||||
PY
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?Set TARGET_INSTANCE_ID from the API response}"
|
||||
for id in $(docker compose ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$id")
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop --time 5 "$id"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
echo 'Target is not a running API replica in this Compose project' >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,28 @@
|
||||
"""One transaction per connection; versioned migrations run as a separate job."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
|
||||
def connect():
|
||||
# shortcut: one connection per request; add a bounded pool before load testing.
|
||||
dsn = Path(os.environ['DATABASE_URL_FILE']).read_text().strip()
|
||||
return psycopg.connect(dsn, connect_timeout=3, row_factory=dict_row,
|
||||
options='-c statement_timeout=5000 -c timezone=UTC')
|
||||
|
||||
|
||||
def migrate():
|
||||
with connect() as db:
|
||||
db.execute('SELECT pg_advisory_xact_lock(2303002)')
|
||||
db.execute('CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)')
|
||||
for path in sorted((Path(__file__).resolve().parents[1] / 'migrations').glob('*.sql')):
|
||||
if not db.execute('SELECT 1 FROM schema_migrations WHERE version=%s', (path.name,)).fetchone():
|
||||
db.execute(path.read_text())
|
||||
db.execute('INSERT INTO schema_migrations VALUES (%s)', (path.name,))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
migrate()
|
||||
print('Migrations applied')
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
"""Shared PostgreSQL state and atomic message retries behind a load balancer."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import psycopg
|
||||
from db import connect
|
||||
|
||||
INSTANCE_ID = os.environ.get('HOSTNAME') or uuid.uuid4().hex
|
||||
IDEMPOTENCY_TTL = int(os.getenv('IDEMPOTENCY_TTL_SECONDS', '86400'))
|
||||
if IDEMPOTENCY_TTL < 86400:
|
||||
raise ValueError('IDEMPOTENCY_TTL_SECONDS must be at least 86400')
|
||||
|
||||
USER_FIELDS = 'id, username, display_name, created_at'
|
||||
SESSION_TTL = int(os.getenv('SESSION_TTL_SECONDS', '3600'))
|
||||
if SESSION_TTL <= 0:
|
||||
raise ValueError('SESSION_TTL_SECONDS must be positive')
|
||||
|
||||
|
||||
class APIError(Exception):
|
||||
def __init__(self, status, code):
|
||||
self.status, self.code = status, code
|
||||
|
||||
|
||||
def require(condition, status=400, code='invalid_request'):
|
||||
if not condition:
|
||||
raise APIError(status, code)
|
||||
|
||||
|
||||
def identifier(value):
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
raise APIError(400, 'invalid_request')
|
||||
|
||||
|
||||
def text(value, maximum):
|
||||
require(isinstance(value, str) and 0 < len(value) <= maximum and bool(value.strip()))
|
||||
try:
|
||||
value.encode('utf-8')
|
||||
except UnicodeEncodeError:
|
||||
raise APIError(400, 'invalid_request')
|
||||
require('\x00' not in value)
|
||||
|
||||
|
||||
def password_hash(password, salt):
|
||||
return hashlib.scrypt(password.encode('utf-8'), salt=salt, n=16384, r=8, p=1, dklen=64)
|
||||
|
||||
|
||||
def serial(value):
|
||||
if isinstance(value, datetime):
|
||||
return value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
if isinstance(value, uuid.UUID):
|
||||
return str(value)
|
||||
raise TypeError('Unsupported JSON value')
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def setup(self):
|
||||
super().setup()
|
||||
self.connection.settimeout(5)
|
||||
|
||||
def body(self, fields, optional=()):
|
||||
require(self.headers.get_content_type() == 'application/json', 415, 'unsupported_media_type')
|
||||
require('Transfer-Encoding' not in self.headers)
|
||||
try:
|
||||
length = int(self.headers.get('Content-Length', '0'))
|
||||
require(0 < length <= 65536)
|
||||
value = json.loads(self.rfile.read(length).decode('utf-8'))
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
raise APIError(400, 'invalid_request')
|
||||
require(type(value) is dict and set(fields) <= set(value) <= set(fields) | set(optional))
|
||||
return value
|
||||
|
||||
def credentials(self, scheme):
|
||||
parts = self.headers.get('Authorization', '').split()
|
||||
require(len(parts) == 2 and parts[0].lower() == scheme.lower(), 401, 'unauthorized')
|
||||
return parts[1]
|
||||
|
||||
def chat(self, db, chat_id):
|
||||
row = db.execute('SELECT * FROM chats WHERE id=%s', (chat_id,)).fetchone()
|
||||
members = db.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id', (chat_id,)).fetchall()
|
||||
row['member_ids'] = [x['user_id'] for x in members]
|
||||
return row
|
||||
|
||||
def page(self, db, table, scope, query, where, params):
|
||||
require(set(query) <= {'limit', 'cursor'} and all(len(v) == 1 for v in query.values()))
|
||||
raw = query.get('limit', ['50'])[0]
|
||||
require(re.fullmatch(r'[0-9]{1,3}', raw) is not None)
|
||||
limit = int(raw)
|
||||
require(1 <= limit <= 100)
|
||||
if 'cursor' in query:
|
||||
try:
|
||||
cursor = json.loads(base64.b64decode(query['cursor'][0], altchars=b'-_', validate=True))
|
||||
require(type(cursor) is list and len(cursor) == 3 and cursor[0] == scope)
|
||||
stamp = datetime.fromisoformat(cursor[1].replace('Z', '+00:00'))
|
||||
require(stamp.tzinfo is not None)
|
||||
last_id = identifier(cursor[2])
|
||||
except (ValueError, TypeError, AttributeError, UnicodeError, binascii.Error):
|
||||
raise APIError(400, 'invalid_request')
|
||||
require(db.execute(f'SELECT 1 FROM {table} WHERE {where} AND created_at=%s AND id=%s',
|
||||
(*params, stamp, last_id)).fetchone() is not None)
|
||||
where += ' AND (created_at, id) > (%s, %s)'
|
||||
params = (*params, stamp, last_id)
|
||||
# table and where are internal constants; every client value is a parameter.
|
||||
rows = db.execute(f'SELECT * FROM {table} WHERE {where} ORDER BY created_at, id LIMIT %s',
|
||||
(*params, limit + 1)).fetchall()
|
||||
selected = rows[:limit]
|
||||
cursor = None
|
||||
if len(rows) > limit:
|
||||
last = selected[-1]
|
||||
cursor = base64.urlsafe_b64encode(json.dumps([scope, last['created_at'], last['id']], default=serial).encode()).decode()
|
||||
if table == 'chats':
|
||||
selected = [self.chat(db, row['id']) for row in selected]
|
||||
return {'items': selected, 'next_cursor': cursor}
|
||||
|
||||
def dispatch(self, db, path, query):
|
||||
if self.command == 'GET' and path == '/health/ready':
|
||||
db.execute('SELECT 1')
|
||||
return 200, {'status': 'ok'}
|
||||
if self.command == 'POST' and path == '/api/v1/users':
|
||||
body = self.body(('username', 'display_name', 'password'))
|
||||
require(isinstance(body['username'], str) and re.fullmatch(r'[a-z0-9_]{3,32}', body['username']) is not None)
|
||||
text(body['display_name'], 100)
|
||||
text(body['password'], 128)
|
||||
require(len(body['password']) >= 12)
|
||||
salt = secrets.token_bytes(16)
|
||||
user = db.execute(f'INSERT INTO users (id, username, display_name, password_salt, password_hash) VALUES (%s,%s,%s,%s,%s) RETURNING {USER_FIELDS}',
|
||||
(uuid.uuid4(), body['username'], body['display_name'], salt, password_hash(body['password'], salt))).fetchone()
|
||||
return 201, user
|
||||
if self.command == 'POST' and path == '/api/v1/auth/sessions':
|
||||
credential = self.credentials('Basic')
|
||||
try:
|
||||
username, password = base64.b64decode(credential, validate=True).decode('utf-8').split(':', 1)
|
||||
require(re.fullmatch(r'[a-z0-9_]{3,32}', username) is not None and 12 <= len(password) <= 128, 401, 'unauthorized')
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
raise APIError(401, 'unauthorized')
|
||||
require(self.headers.get('Content-Length', '0') == '0' and 'Transfer-Encoding' not in self.headers)
|
||||
user = db.execute('SELECT * FROM users WHERE username=%s', (username,)).fetchone()
|
||||
# Run the same KDF for unknown users to avoid the cheap username timing oracle.
|
||||
digest = password_hash(password, user['password_salt'] if user else bytes(16))
|
||||
require(user is not None and hmac.compare_digest(digest, user['password_hash']), 401, 'unauthorized')
|
||||
token = secrets.token_urlsafe(32)
|
||||
session = db.execute("INSERT INTO sessions VALUES (%s,%s,clock_timestamp() + %s * interval '1 second') RETURNING expires_at",
|
||||
(hashlib.sha256(token.encode()).digest(), user['id'], SESSION_TTL)).fetchone()
|
||||
return 201, dict(session, token=token, token_type='Bearer', user={k: user[k] for k in ('id', 'username', 'display_name', 'created_at')})
|
||||
token = self.credentials('Bearer')
|
||||
token_digest = hashlib.sha256(token.encode()).digest()
|
||||
# shortcut: expired rows remain; add scheduled cleanup for a long-lived deployment.
|
||||
actor = db.execute('SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at > clock_timestamp()', (token_digest,)).fetchone()
|
||||
require(actor is not None, 401, 'unauthorized')
|
||||
actor = actor['user_id']
|
||||
if self.command == 'DELETE' and path == '/api/v1/auth/sessions/current':
|
||||
db.execute('DELETE FROM sessions WHERE token_hash=%s', (token_digest,))
|
||||
return 204, None
|
||||
if self.command == 'GET' and path == '/api/v1/users/me':
|
||||
return 200, db.execute(f'SELECT {USER_FIELDS} FROM users WHERE id=%s', (actor,)).fetchone()
|
||||
if path == '/api/v1/chats':
|
||||
if self.command == 'POST':
|
||||
body = self.body(('title', 'member_ids'))
|
||||
text(body['title'], 100)
|
||||
members = body['member_ids']
|
||||
require(type(members) is list and 1 <= len(members) <= 100)
|
||||
members = [identifier(x) for x in members]
|
||||
require(len(set(members)) == len(members) and str(actor) in members)
|
||||
existing = db.execute('SELECT id FROM users WHERE id = ANY(%s::uuid[])', (members,)).fetchall()
|
||||
require(len(existing) == len(members))
|
||||
chat_id = uuid.uuid4()
|
||||
db.execute('INSERT INTO chats (id, title) VALUES (%s,%s)', (chat_id, body['title']))
|
||||
with db.cursor() as cur:
|
||||
cur.executemany('INSERT INTO chat_members VALUES (%s,%s)', [(chat_id, member) for member in members])
|
||||
return 201, self.chat(db, chat_id)
|
||||
if self.command == 'GET':
|
||||
return 200, self.page(db, 'chats', 'chats:' + str(actor), query,
|
||||
'id IN (SELECT chat_id FROM chat_members WHERE user_id=%s)', (actor,))
|
||||
match = re.fullmatch(r'/api/v1/chats/([^/]+)(/messages)?', path)
|
||||
if match:
|
||||
chat_id = identifier(match[1])
|
||||
require(db.execute('SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s', (chat_id, actor)).fetchone() is not None, 404, 'not_found')
|
||||
if not match[2] and self.command == 'GET':
|
||||
return 200, self.chat(db, chat_id)
|
||||
if match[2]:
|
||||
if self.command == 'GET':
|
||||
return 200, self.page(db, 'messages', 'messages:' + chat_id, query, 'chat_id=%s', (chat_id,))
|
||||
if self.command == 'POST':
|
||||
key = self.headers.get('Idempotency-Key', '')
|
||||
require(re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key) is not None)
|
||||
body = self.body(('text',), ('attachment_ids',))
|
||||
text(body['text'], 4000)
|
||||
require(type(body.get('attachment_ids', [])) is list and body.get('attachment_ids', []) == [])
|
||||
# Serialize the same scope across replicas; lock, effect and key commit together.
|
||||
scope = json.dumps([str(actor), chat_id, key])
|
||||
db.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))', (scope,))
|
||||
db.execute('DELETE FROM message_keys WHERE user_id=%s AND chat_id=%s AND key=%s AND expires_at <= clock_timestamp()',
|
||||
(actor, chat_id, key))
|
||||
previous = db.execute('SELECT m.* FROM message_keys k JOIN messages m ON m.id=k.message_id WHERE k.user_id=%s AND k.chat_id=%s AND k.key=%s',
|
||||
(actor, chat_id, key)).fetchone()
|
||||
if previous:
|
||||
require(previous['text'] == body['text'], 409, 'conflict')
|
||||
return 201, previous
|
||||
message = db.execute('INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *',
|
||||
(uuid.uuid4(), chat_id, actor, body['text'])).fetchone()
|
||||
db.execute("INSERT INTO message_keys VALUES (%s,%s,%s,%s,clock_timestamp() + %s * interval '1 second')",
|
||||
(actor, chat_id, key, message['id'], IDEMPOTENCY_TTL))
|
||||
return 201, message
|
||||
raise APIError(404, 'not_found')
|
||||
|
||||
def handle_request(self):
|
||||
request_id = uuid.uuid4().hex
|
||||
path = urlsplit(self.path)
|
||||
try:
|
||||
if self.command == 'GET' and path.path == '/health/live':
|
||||
status, body = 200, {'status': 'ok'}
|
||||
else:
|
||||
with connect() as db:
|
||||
status, body = self.dispatch(db, path.path, parse_qs(path.query, keep_blank_values=True))
|
||||
except psycopg.errors.UniqueViolation:
|
||||
status, body = 409, 'conflict'
|
||||
except (psycopg.OperationalError, psycopg.errors.QueryCanceled):
|
||||
status, body = 503, 'unavailable'
|
||||
except APIError as exc:
|
||||
status, body = exc.status, exc.code
|
||||
except Exception:
|
||||
status, body = 500, 'internal_error'
|
||||
if status >= 400:
|
||||
body = {'error': {'code': body, 'message': body, 'request_id': request_id}}
|
||||
payload = b'' if status == 204 else json.dumps(body, ensure_ascii=False, default=serial).encode('utf-8')
|
||||
self.send_response(status)
|
||||
if status != 204:
|
||||
self.send_header('Content-Type', 'application/json; charset=utf-8')
|
||||
if status == 401:
|
||||
challenge = 'Basic realm="messenger", charset="UTF-8"' if path.path == '/api/v1/auth/sessions' else 'Bearer realm="messenger"'
|
||||
self.send_header('WWW-Authenticate', challenge)
|
||||
self.send_header('Content-Length', str(len(payload)))
|
||||
self.send_header('X-Request-Id', request_id)
|
||||
self.send_header('X-Instance-Id', INSTANCE_ID)
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
do_GET = do_POST = do_DELETE = do_PUT = do_PATCH = handle_request
|
||||
|
||||
def log_message(self, format, *args):
|
||||
# Paths may contain cursors; log only method and response status.
|
||||
print(self.command, args[1] if len(args) > 1 else '', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Non-daemon request threads finish their transactions before process exit.
|
||||
with ThreadingHTTPServer((os.getenv('APP_HOST', '0.0.0.0'), int(os.getenv('APP_PORT', '8080'))), Handler) as server:
|
||||
server.daemon_threads = False
|
||||
def stop(signum, frame):
|
||||
threading.Thread(target=server.shutdown, daemon=True).start()
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
server.serve_forever(poll_interval=0.1)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Additional checks against a running lab3 server."""
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments
|
||||
|
||||
args = arguments('Additional validation checks')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
a, b, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
c.call('POST', '/api/v1/users', 400, body={'username': 'BAD', 'display_name': 'X'})
|
||||
c.call('POST', '/api/v1/users', 400, body={'username': 'valid_name', 'display_name': ' '})
|
||||
c.call('POST', '/api/v1/users', 400, body=dict(a['registration'], extra=True))
|
||||
c.call('POST', path, 400, actor=a, body={'text': ' '}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
c.call('POST', path, 400, actor=a, body={'text': 'ok', 'sender_id': b['id']}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
c.call('GET', path, 404, actor=eve)
|
||||
c.call('GET', path + '?cursor=bad', 400, actor=a)
|
||||
c.call('GET', path + '?limit=1.5', 400, actor=a)
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': str(uuid.uuid4())})
|
||||
for i in range(5):
|
||||
c.message(a, chat, 'Юникод 👋 ' + str(i))
|
||||
p = c.call('GET', path + '?limit=2', actor=b, schema='MessagePage')['json']
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=a, body={'title': 'other', 'member_ids': [a['id']]}, schema='Chat')['json']
|
||||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + p['next_cursor'], 400, actor=a)
|
||||
items = p['items']
|
||||
while p['next_cursor']:
|
||||
p = c.call('GET', path + '?limit=2&cursor=' + p['next_cursor'], actor=b, schema='MessagePage')['json']
|
||||
items += p['items']
|
||||
assert len(items) == len({x['id'] for x in items}) == 5
|
||||
print('PASS: validation, access, Unicode, pagination and cursor scope')
|
||||
c.call('POST', '/api/v1/users', 400, raw=b'{', headers={'Content-Type': 'application/json'})
|
||||
c.call('POST', '/api/v1/users', 409, body=a['registration'])
|
||||
print('PASS: malformed JSON and duplicate username')
|
||||
import base64
|
||||
# All 128 Unicode code points, including colon, must survive KDF without truncation.
|
||||
registration = {'username': 'unicode_' + uuid.uuid4().hex[:12], 'display_name': 'Unicode', 'password': ':' + '🔐' * 127}
|
||||
u = c.call('POST', '/api/v1/users', 201, body=registration, schema='User')['json']
|
||||
credential = base64.b64encode((u['username'] + ':' + registration['password']).encode()).decode()
|
||||
session = c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
||||
assert session['user'] == u
|
||||
c.call('POST', '/api/v1/users', 400, body=dict(registration, password='a' * 11))
|
||||
c.call('POST', '/api/v1/users', 400, body=dict(registration, password='a' * 129))
|
||||
# Creating a chat with a missing participant must leave no visible chat behind.
|
||||
before = c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json']
|
||||
for members in ([a['id'], str(uuid.uuid4())], [a['id'], a['id']], [b['id']]):
|
||||
c.call('POST', '/api/v1/chats', 400, actor=a, body={'title': 'invalid', 'member_ids': members})
|
||||
assert c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json'] == before
|
||||
print('PASS: Unicode/colon passwords, length boundaries, invalid chat creation')
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Run inside API container: migrations, constraints, rollback and password storage."""
|
||||
import sys
|
||||
import uuid
|
||||
sys.path.insert(0, '/app/src')
|
||||
import psycopg
|
||||
from db import connect, migrate
|
||||
|
||||
|
||||
def counts():
|
||||
with connect() as db:
|
||||
return {name: db.execute('SELECT count(*) AS n FROM ' + name).fetchone()['n']
|
||||
for name in ('users', 'chats', 'chat_members', 'messages', 'sessions', 'message_keys', 'schema_migrations')}
|
||||
|
||||
|
||||
before = counts()
|
||||
migrate()
|
||||
migrate()
|
||||
assert counts() == before
|
||||
with connect() as db:
|
||||
assert db.execute('SELECT count(*) AS n FROM users').fetchone()['n'] > 0
|
||||
assert db.execute('SELECT 1 FROM users WHERE octet_length(password_salt) != 16 OR octet_length(password_hash) != 64').fetchone() is None
|
||||
assert db.execute('SELECT 1 FROM sessions WHERE octet_length(token_hash) != 32').fetchone() is None
|
||||
chat_id = uuid.uuid4()
|
||||
try:
|
||||
with connect() as db:
|
||||
db.execute('INSERT INTO chats (id,title) VALUES (%s,%s)', (chat_id, 'rollback check'))
|
||||
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat_id, uuid.uuid4()))
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Foreign key did not reject missing member')
|
||||
with connect() as db:
|
||||
assert db.execute('SELECT 1 FROM chats WHERE id=%s', (chat_id,)).fetchone() is None
|
||||
assert counts() == before
|
||||
print('PASS: repeated migrations preserve row counts; scrypt/token digests; FK and transaction rollback')
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Run against an API started with SESSION_TTL_SECONDS=2; tokens never printed."""
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments
|
||||
|
||||
args = arguments('Short-TTL session expiry')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
a = c.user('expiry')
|
||||
c.call('GET', '/api/v1/users/me', actor=a, schema='User')
|
||||
time.sleep(3)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=a)
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=a)
|
||||
print('PASS: session expires with TTL=2; expired token cannot read or logout')
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Concurrent retries through the LB must reach different real API processes."""
|
||||
import sys
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments
|
||||
|
||||
args = arguments('Shared idempotency across replicas')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
a, b, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
|
||||
def send(i):
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
body = {'text': 'Один результат 👋'}
|
||||
if i % 2:
|
||||
body['attachment_ids'] = []
|
||||
return client.call('POST', path, 201, actor=a, body=body,
|
||||
headers={'Idempotency-Key': key}, schema='Message')
|
||||
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
responses = list(pool.map(send, range(32)))
|
||||
assert len({r['headers']['X-Instance-Id'] for r in responses}) >= 2
|
||||
assert all(r['json'] == responses[0]['json'] for r in responses)
|
||||
page = c.call('GET', path, actor=b, schema='MessagePage')['json']
|
||||
assert page['items'] == [responses[0]['json']]
|
||||
c.call('POST', path, 409, actor=a, body={'text': 'Другой текст'}, headers={'Idempotency-Key': key})
|
||||
c.call('POST', path, 404, actor=eve, body={'text': 'Один результат 👋'}, headers={'Idempotency-Key': key})
|
||||
other = c.message(b, chat, 'Другой пользователь', key=key)['json']
|
||||
assert other['id'] != responses[0]['json']['id']
|
||||
second_chat = c.call('POST', '/api/v1/chats', 201, actor=a,
|
||||
body={'title': 'Другой чат', 'member_ids': [a['id']]}, schema='Chat')['json']
|
||||
assert c.message(a, second_chat, 'Другой чат', key=key)['json']['id'] != other['id']
|
||||
for bad_key in ('', 'has spaces', 'x' * 129):
|
||||
c.call('POST', path, 400, actor=a, body={'text': 'Invalid key'}, headers={'Idempotency-Key': bad_key})
|
||||
print('PASS: 32 concurrent retries across >=2 replicas: one message; conflict, access, key scope and validation')
|
||||
Reference in New Issue
Block a user