ЛР 3 — БПИ2304 — Кирюпина — на 3 #137
+2
-10
@@ -1,13 +1,5 @@
|
||||
# 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
|
||||
# Generate local .env and secrets using scripts/setup.py; never commit them.
|
||||
# Only the load balancer publishes a port. API replicas always listen on 8080.
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
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
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
*.sh text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
*.sql text eol=lf
|
||||
@@ -0,0 +1,9 @@
|
||||
FROM node:22.20.0-alpine
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev --ignore-scripts
|
||||
COPY src/ ./src/
|
||||
COPY migrations/ ./migrations/
|
||||
ENV APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab
|
||||
EXPOSE 8080
|
||||
CMD ["node", "src/server.js"]
|
||||
@@ -1,37 +1,73 @@
|
||||
# Отчёт — лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Кирюпина Александра Радиевна, БПИ2304.
|
||||
- Целевая оценка: 3, трек 5 не выбран.
|
||||
- Commit/PR: планируемая ветка `solution/bpi2304-kiryupina`, MR «ЛР 3 — БПИ2304 — Кирюпина — на 3». Ссылка — после создания MR.
|
||||
- Источники и библиотеки: реализация lab2, материалы курса, Node.js 22.20.0, pg 8.16.3, PostgreSQL 17.6, HAProxy 3.0.12.
|
||||
- Помощь ИИ: ChatGPT/Codex использовался при подготовке и проверке кода, тестов и отчёта.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Docker Desktop с Linux-контейнерами и Python 3.9+. Для собственного Node-теста — Node.js 22. Команды выполняются в PowerShell из папки с compose.yaml:
|
||||
|
||||
```powershell
|
||||
py -X utf8 scripts/setup.py
|
||||
docker compose up -d --build --wait
|
||||
py -X utf8 scripts/check_contract.py
|
||||
py -X utf8 tests/smoke.py --base-url http://localhost:8080
|
||||
py -X utf8 tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080
|
||||
py -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-one.cmd --base-url http://localhost:8080
|
||||
py -X utf8 scripts/control.py restore
|
||||
```
|
||||
|
||||
setup.py создаёт .env и локальные секреты, не заменяя существующие. Они исключены из Git. APP_PORT задаёт внешний порт (8080), SESSION_TTL_SECONDS — срок сессии (3600), IDEMPOTENCY_TTL_SECONDS — срок ключа (86400, не менее суток). Если 8080 занят, нужно изменить APP_PORT в .env и адрес в тестах.
|
||||
|
||||
Миграции запускает отдельный сервис migrate перед API. PostgreSQL хранит данные в именованном volume pgdata. Повторная сборка и запуск — той же командой docker compose up -d --build --wait. Остановка с сохранением данных — docker compose down; намеренное удаление учебной БД — docker compose down -v. При проверке сохранности -v не используется. Секреты нужно сохранять вместе с существующей БД.
|
||||
|
||||
Дополнительные проверки:
|
||||
|
||||
```powershell
|
||||
node student-tests/check.js --lifecycle
|
||||
Get-Content student-tests/storage.js -Raw | docker compose exec -T api1 node
|
||||
```
|
||||
|
||||
В Linux используются make check, make test и make test-persistence / make test-failover с ACTION_SCRIPT=scripts/restart.sh / scripts/stop-one.sh. Перед запуском: chmod +x scripts/restart.sh scripts/stop-one.sh. Проверки выполнены в Windows; Linux-обёртки проверены синтаксически. Отдельный запуск из нового clone не выполнялся, сборка проверена из рабочей папки на пустом volume.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Клиент → HAProxy → две API-реплики → общая PostgreSQL. Из lab2 сохранены пользователи, чаты, сообщения, сессии, хеширование паролей, проверки доступа и пагинация. Сервисы: lb, api1, api2, db и migrate. Наружу опубликован только порт LB; порты API и БД доступны внутри сети Compose.
|
||||
|
||||
HAProxy распределяет запросы round-robin без sticky sessions. Проверки /health/ready выполняются раз в секунду: две неудачи исключают реплику, одна удача возвращает её. Таймаут подключения и проверки — 1 секунда. Адреса обновляются через Docker DNS. Каждая API добавляет X-Instance-Id — случайный идентификатор процесса, меняющийся после рестарта. Обе реплики проверяют одну и ту же сессию в PostgreSQL.
|
||||
|
||||
POST сообщения требует Idempotency-Key. Область ключа — пользователь и чат. Проверка ключа, запись сообщения и сохранение ответа выполняются одной транзакцией с общей PostgreSQL-блокировкой. Повтор с тем же текстом возвращает прежнее сообщение и 201, с другим текстом — 409. Ошибки не сохраняются как успешный результат. Сначала всегда проверяются сессия и доступ. После истечения ключа его можно использовать снова, старое сообщение не удаляется.
|
||||
|
||||
Миграции версионируются и повторно применяются без дублирования данных. API самостоятельно миграции не запускают. restart hook перезапускает LB, обе API и БД без удаления volume. stop-one сопоставляет TARGET_INSTANCE_ID с реальным контейнером и останавливает только его. После теста реплика восстанавливается командой restore.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Критерий на 3 | Проверка и результат | Доказательство |
|
||||
| --- | --- | --- |
|
||||
| Воспроизводимый стенд | Docker-сборка и запуск успешны | evidence/build.txt, evidence/containers.txt |
|
||||
| Публичный smoke | PASS через LB | evidence/smoke.txt |
|
||||
| Одна сессия на двух репликах | Получены два X-Instance-Id без повторного входа | evidence/student-tests.txt |
|
||||
| Конкурентная идемпотентность | 16 запросов с одним ключом через обе API создали одно сообщение | evidence/student-tests.txt |
|
||||
| Сохранность при полном рестарте | Прежняя сессия читает прежние данные, повтор ключа возвращает прежнее сообщение | evidence/persistence.txt, evidence/restart-scope.json, evidence/student-tests.txt |
|
||||
| Отказ API | Публичный failover прошёл, восстановление за 4,14 с | evidence/failover.txt |
|
||||
| Остановка любой реплики | api1 — 5,496 с; api2 — 5,930 с, данные сохранены | evidence/student-tests.txt, evidence/stop-api1.json, evidence/stop-api2.json |
|
||||
| Миграции и срок ключа | Повторные миграции не меняют данные; проверены срок ключа и откат ошибки | evidence/storage.txt |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Контракт и публичные tests/ не изменялись. Результаты относятся к локальным проверкам 12 ноября 2026 года. Вместо make в Windows запускались соответствующие Python-скрипты.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
В публичном failover наблюдались две реплики: 8 успешных записей, 0 неудачных попыток, первое восстановление за 4,14 с. В отдельной проверке поочерёдно остановлены api1 и api2: по 3 кратких ошибки, затем успешные чтение, запись и повтор прежнего ключа. Обе реплики восстановлены.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
После полного рестарта сохранились сообщения, действующая сессия, курсор и результат идемпотентной отправки. Потеря подтверждённых сообщений не обнаружена. Срок отдельного тестового ключа искусственно переведён в прошлое: новая отправка создала новое сообщение, старое осталось.
|
||||
|
||||
Это функциональные проверки. Нагрузочный трек не выполнялся; RPS, p95/p99, CPU/RAM и отдельное время SIGTERM не измерялись. Лимиты ресурсов не задавались. Время восстановления зависит от машины и включает работу проверочного сценария.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Стенд выдерживает отказ одной API при работающей другой. БД, балансировщик и Docker-host остаются единичными точками отказа. Volume не защищает от потери диска и не заменяет backup.
|
||||
|
||||
Redis, rolling update, автоматическое масштабирование сверх двух API и очистка старых сессий/ключей по расписанию не реализованы. Идемпотентность действует только для отправки сообщений. HTTP используется на локальном учебном стенде; для удалённого размещения нужен TLS. Уровни 4 и 5 не заявлены.
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
name: mtusi-lab3
|
||||
x-api: &api
|
||||
image: mtusi-messenger:lab3
|
||||
build: .
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 8080
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
secrets: [database_url]
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:8080/health/ready').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
|
||||
interval: 2s
|
||||
timeout: 4s
|
||||
retries: 20
|
||||
stop_grace_period: 10s
|
||||
services:
|
||||
db:
|
||||
image: postgres:17.6-alpine
|
||||
environment:
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
secrets: [postgres_password]
|
||||
volumes: [pgdata:/var/lib/postgresql/data]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
migrate:
|
||||
image: mtusi-messenger:lab3
|
||||
build: .
|
||||
command: ["node", "src/migrate.js"]
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
secrets: [database_url]
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
api1:
|
||||
<<: *api
|
||||
api2:
|
||||
<<: *api
|
||||
lb:
|
||||
image: haproxy:3.0.12-alpine
|
||||
ports: ["127.0.0.1:${APP_PORT:-8080}:8080"]
|
||||
volumes: [./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro]
|
||||
depends_on:
|
||||
api1:
|
||||
condition: service_healthy
|
||||
api2:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
pgdata:
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
@@ -0,0 +1,524 @@
|
||||
Image haproxy:3.0.12-alpine Pulling
|
||||
4f4fb700ef54 Pulling fs layer 0B
|
||||
014e56e61396 Pulling fs layer 0B
|
||||
36b2d67b2251 Pulling fs layer 0B
|
||||
b471f8e34c0c Pulling fs layer 0B
|
||||
ca8574a1f7ef Pulling fs layer 0B
|
||||
073a9f62df9f Pulling fs layer 0B
|
||||
ddff05df3548 Download complete 0B
|
||||
2979ead73fb0 Download complete 0B
|
||||
4f4fb700ef54 Download complete 0B
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
b471f8e34c0c Download complete 0B
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
073a9f62df9f Download complete 0B
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
ca8574a1f7ef Download complete 0B
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 1.049MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 2.097MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 3.146MB
|
||||
014e56e61396 Downloading 3.146MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
014e56e61396 Download complete 0B
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
014e56e61396 Extracting 1B
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
b471f8e34c0c Extracting 1B
|
||||
014e56e61396 Pull complete 0B
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
b471f8e34c0c Extracting 1B
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
b471f8e34c0c Pull complete 0B
|
||||
ca8574a1f7ef Pull complete 0B
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 4.194MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 5.243MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 6.291MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 7.34MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 8.389MB
|
||||
36b2d67b2251 Downloading 9.437MB
|
||||
36b2d67b2251 Downloading 9.437MB
|
||||
36b2d67b2251 Downloading 9.437MB
|
||||
36b2d67b2251 Downloading 9.437MB
|
||||
36b2d67b2251 Downloading 9.437MB
|
||||
36b2d67b2251 Download complete 0B
|
||||
36b2d67b2251 Extracting 1B
|
||||
073a9f62df9f Pull complete 0B
|
||||
36b2d67b2251 Pull complete 0B
|
||||
4f4fb700ef54 Pull complete 0B
|
||||
Image haproxy:3.0.12-alpine Pulled
|
||||
Image mtusi-messenger:lab3 Building
|
||||
Image mtusi-messenger:lab3 Building
|
||||
Image mtusi-messenger:lab3 Building
|
||||
#1 [internal] load local bake definitions
|
||||
#1 reading from stdin 1.77kB 0.0s done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [migrate internal] load build definition from Dockerfile
|
||||
#2 transferring dockerfile: 292B 0.0s done
|
||||
#2 DONE 0.0s
|
||||
|
||||
#3 [migrate internal] load metadata for docker.io/library/node:22.20.0-alpine
|
||||
#3 ...
|
||||
|
||||
#4 [auth] library/node:pull token for registry-1.docker.io
|
||||
#4 DONE 0.0s
|
||||
|
||||
#3 [migrate internal] load metadata for docker.io/library/node:22.20.0-alpine
|
||||
#3 DONE 6.2s
|
||||
|
||||
#5 [migrate internal] load .dockerignore
|
||||
#5 transferring context: 196B done
|
||||
#5 DONE 0.0s
|
||||
|
||||
#6 [api2 1/6] FROM docker.io/library/node:22.20.0-alpine@sha256:dbcedd8aeab47fbc0f4dd4bffa55b7c3c729a707875968d467aaaea42d6225af
|
||||
#6 resolve docker.io/library/node:22.20.0-alpine@sha256:dbcedd8aeab47fbc0f4dd4bffa55b7c3c729a707875968d467aaaea42d6225af 0.0s done
|
||||
#6 DONE 0.0s
|
||||
|
||||
#7 [migrate internal] load build context
|
||||
#7 transferring context: 25.18kB 0.0s done
|
||||
#7 DONE 0.1s
|
||||
|
||||
#8 [api2 2/6] WORKDIR /app
|
||||
#8 CACHED
|
||||
|
||||
#8 [migrate 2/6] WORKDIR /app
|
||||
#8 CACHED
|
||||
|
||||
#9 [migrate 3/6] COPY package.json package-lock.json ./
|
||||
#9 DONE 0.1s
|
||||
|
||||
#10 [api1 4/6] RUN npm ci --omit=dev --ignore-scripts
|
||||
#10 13.31 npm notice This endpoint is being retired. Use the bulk advisory endpoint instead. See the following docs for more info: https://api-docs.npmjs.com/#tag/Audit
|
||||
#10 21.29
|
||||
#10 21.29 added 14 packages in 21s
|
||||
#10 21.29 npm notice
|
||||
#10 21.29 npm notice New major version of npm available! 10.9.3 -> 12.2.2
|
||||
#10 21.29 npm notice Changelog: https://github.com/npm/cli/releases/tag/v12.2.2
|
||||
#10 21.29 npm notice To update run: npm install -g npm@12.2.2
|
||||
#10 21.29 npm notice
|
||||
#10 DONE 21.4s
|
||||
|
||||
#11 [migrate 5/6] COPY src/ ./src/
|
||||
#11 DONE 0.1s
|
||||
|
||||
#11 [api1 5/6] COPY src/ ./src/
|
||||
#11 DONE 0.1s
|
||||
|
||||
#12 [api1 6/6] COPY migrations/ ./migrations/
|
||||
#12 DONE 0.0s
|
||||
|
||||
#13 [migrate] exporting to image
|
||||
#13 exporting layers
|
||||
#13 exporting layers 0.3s done
|
||||
#13 exporting manifest sha256:880c37fd35d6cacd17e882a3db0cfb54baf855ab8bb286b8b909890b468d1009 0.0s done
|
||||
#13 exporting config sha256:3481b13645a046cdb9fa7cf46c6b94d6cb4450fafc4b165db9944025357fa7a6 0.0s done
|
||||
#13 exporting attestation manifest sha256:f2d286f830b220ed525b550431da8ed55097ca4e421d9d5cfc7f6e4d8c871e0e
|
||||
#13 exporting attestation manifest sha256:f2d286f830b220ed525b550431da8ed55097ca4e421d9d5cfc7f6e4d8c871e0e 0.1s done
|
||||
#13 exporting manifest list sha256:c5e764dc81ca25932f37377bf3f8658c16bc4ccad145f9c2feff0ff781821d40 0.0s done
|
||||
#13 naming to docker.io/library/mtusi-messenger:lab3
|
||||
#13 naming to docker.io/library/mtusi-messenger:lab3 0.0s done
|
||||
#13 unpacking to docker.io/library/mtusi-messenger:lab3
|
||||
#13 unpacking to docker.io/library/mtusi-messenger:lab3 0.3s done
|
||||
#13 DONE 0.8s
|
||||
|
||||
#14 [api1] exporting to image
|
||||
#14 exporting layers 0.3s done
|
||||
#14 exporting manifest sha256:5faf207f69dbdaf55f7cc85f0ffe5a5c86c5e1115c851ccb78702997bdadd712 0.0s done
|
||||
#14 exporting config sha256:2fb8c7dc0aba453b6f559e1c4cb17c84e5f45bb631b7e5e4941599cc9d50a991 0.0s done
|
||||
#14 exporting attestation manifest sha256:63da079de8f0e8dfa1fd05d3c829fb57872f7e25e299b1a0befb3cdac12fc0fb 0.0s done
|
||||
#14 exporting manifest list sha256:53942ae151825fbe86cc409053b95bbdfcbb04bd1348d77b165e2e350712cf1b 0.0s done
|
||||
#14 naming to docker.io/library/mtusi-messenger:lab3 0.0s done
|
||||
#14 unpacking to docker.io/library/mtusi-messenger:lab3 0.3s done
|
||||
#14 DONE 0.8s
|
||||
|
||||
#15 [api2] exporting to image
|
||||
#15 exporting layers 0.3s done
|
||||
#15 exporting manifest sha256:e35152b49a06faaec3cd1aadfc290bfc9e8e599ace186f4418874732f8ed0f17 0.0s done
|
||||
#15 exporting config sha256:86d8988d253aea9d1a741e2397356f1ca2b7547865e726acaa31837342f861c4 0.0s done
|
||||
#15 exporting attestation manifest sha256:1aefc8c735afb16a68aa72fb26f426f96797185d09330bb1a8baa970c7cac520 0.1s done
|
||||
#15 exporting manifest list sha256:1ade29bf01319978b3cac27e72a637f673fd6461bf8b8e5d0204baf5ceb06ecb 0.0s done
|
||||
#15 naming to docker.io/library/mtusi-messenger:lab3 done
|
||||
#15 unpacking to docker.io/library/mtusi-messenger:lab3 0.3s done
|
||||
#15 DONE 0.8s
|
||||
|
||||
#16 [api1] resolving provenance for metadata file
|
||||
#16 DONE 0.1s
|
||||
|
||||
#17 [api2] resolving provenance for metadata file
|
||||
#17 DONE 0.1s
|
||||
|
||||
#18 [migrate] resolving provenance for metadata file
|
||||
#18 DONE 0.0s
|
||||
Image mtusi-messenger:lab3 Built
|
||||
Image mtusi-messenger:lab3 Built
|
||||
Image mtusi-messenger:lab3 Built
|
||||
Network mtusi-lab3_default Creating
|
||||
Volume mtusi-lab3_pgdata Creating
|
||||
Volume mtusi-lab3_pgdata Creating
|
||||
Network mtusi-lab3_default Creating
|
||||
Volume mtusi-lab3_pgdata Created
|
||||
Volume mtusi-lab3_pgdata Created
|
||||
Network mtusi-lab3_default Created
|
||||
Network mtusi-lab3_default Created
|
||||
Container mtusi-lab3-db-1 Creating
|
||||
Container mtusi-lab3-db-1 Created
|
||||
Container mtusi-lab3-migrate-1 Creating
|
||||
Container mtusi-lab3-migrate-1 Created
|
||||
Container mtusi-lab3-api2-1 Creating
|
||||
Container mtusi-lab3-api1-1 Creating
|
||||
Container mtusi-lab3-api1-1 Created
|
||||
Container mtusi-lab3-api2-1 Created
|
||||
Container mtusi-lab3-lb-1 Creating
|
||||
Container mtusi-lab3-lb-1 Created
|
||||
Container mtusi-lab3-db-1 Starting
|
||||
Container mtusi-lab3-db-1 Started
|
||||
Container mtusi-lab3-db-1 Waiting
|
||||
Container mtusi-lab3-db-1 Healthy
|
||||
Container mtusi-lab3-migrate-1 Starting
|
||||
Container mtusi-lab3-migrate-1 Started
|
||||
Container mtusi-lab3-migrate-1 Waiting
|
||||
Container mtusi-lab3-migrate-1 Waiting
|
||||
Container mtusi-lab3-migrate-1 Exited
|
||||
Container mtusi-lab3-migrate-1 Exited
|
||||
Container mtusi-lab3-api2-1 Starting
|
||||
Container mtusi-lab3-api1-1 Starting
|
||||
Container mtusi-lab3-api2-1 Started
|
||||
Container mtusi-lab3-api1-1 Started
|
||||
Container mtusi-lab3-api1-1 Waiting
|
||||
Container mtusi-lab3-api2-1 Waiting
|
||||
Container mtusi-lab3-api2-1 Healthy
|
||||
Container mtusi-lab3-api1-1 Healthy
|
||||
Container mtusi-lab3-lb-1 Starting
|
||||
Container mtusi-lab3-lb-1 Started
|
||||
Container mtusi-lab3-lb-1 Waiting
|
||||
Container mtusi-lab3-db-1 Waiting
|
||||
Container mtusi-lab3-migrate-1 Waiting
|
||||
Container mtusi-lab3-api1-1 Waiting
|
||||
Container mtusi-lab3-api2-1 Waiting
|
||||
Container mtusi-lab3-api1-1 Healthy
|
||||
Container mtusi-lab3-db-1 Healthy
|
||||
Container mtusi-lab3-api2-1 Healthy
|
||||
Container mtusi-lab3-migrate-1 Exited
|
||||
Container mtusi-lab3-lb-1 Healthy
|
||||
@@ -0,0 +1 @@
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,6 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi-lab3-api1-1 mtusi-messenger:lab3 "docker-entrypoint.s…" api1 6 minutes ago Up 12 seconds (healthy) 8080/tcp
|
||||
mtusi-lab3-api2-1 mtusi-messenger:lab3 "docker-entrypoint.s…" api2 6 minutes ago Up 2 seconds (healthy) 8080/tcp
|
||||
mtusi-lab3-db-1 postgres:17.6-alpine "docker-entrypoint.s…" db 6 minutes ago Up 27 seconds (healthy) 5432/tcp
|
||||
mtusi-lab3-lb-1 haproxy:3.0.12-alpine "docker-entrypoint.s…" lb 6 minutes ago Up 19 seconds 127.0.0.1:8080->8080/tcp
|
||||
mtusi-lab3-migrate-1 mtusi-messenger:lab3 "docker-entrypoint.s…" migrate 6 minutes ago Exited (0) 6 minutes ago
|
||||
@@ -0,0 +1 @@
|
||||
PASS: public tests and contracts match the original archive.
|
||||
@@ -0,0 +1,3 @@
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 8, "failed_attempts": 0, "first_recovery_seconds": 4.14}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1 @@
|
||||
PASS: haproxy -c -f /usr/local/etc/haproxy/haproxy.cfg exited 0.
|
||||
@@ -0,0 +1,2 @@
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"before": [
|
||||
{
|
||||
"service": "api1",
|
||||
"container": "7a544460999be0a492d470d5405eb7de664a6ba0d7c7e5f5b87380656b472f3f",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:02:57.540112271Z",
|
||||
"finished_at": "2026-11-12T15:02:39.424279829Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "api2",
|
||||
"container": "a48a69ce0119685403c3d0089606a65d50a0b6f60485f8e961c408887fb1ed9c",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:00:46.864284509Z",
|
||||
"finished_at": "2026-11-12T15:00:41.716504689Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "db",
|
||||
"container": "7d39044be1430f97c6720e95ecd4b6034b61eb0108e2b7b6629228bdbff7b484",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:00:42.702643922Z",
|
||||
"finished_at": "2026-11-12T15:00:42.068900714Z",
|
||||
"volumes": [
|
||||
"mtusi-lab3_pgdata"
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "lb",
|
||||
"container": "f5840cdd4baf2941b8a5ea95a7d957a455d7384ae052499e1b9ad4ba12f3558a",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:00:49.93880892Z",
|
||||
"finished_at": "2026-11-12T15:00:41.399576651Z",
|
||||
"volumes": []
|
||||
}
|
||||
],
|
||||
"after": [
|
||||
{
|
||||
"service": "api1",
|
||||
"container": "7a544460999be0a492d470d5405eb7de664a6ba0d7c7e5f5b87380656b472f3f",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:07.279571304Z",
|
||||
"finished_at": "2026-11-12T15:03:02.323870408Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "api2",
|
||||
"container": "a48a69ce0119685403c3d0089606a65d50a0b6f60485f8e961c408887fb1ed9c",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:07.44111824Z",
|
||||
"finished_at": "2026-11-12T15:03:02.326250394Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "db",
|
||||
"container": "7d39044be1430f97c6720e95ecd4b6034b61eb0108e2b7b6629228bdbff7b484",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:03.311328241Z",
|
||||
"finished_at": "2026-11-12T15:03:02.656514582Z",
|
||||
"volumes": [
|
||||
"mtusi-lab3_pgdata"
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "lb",
|
||||
"container": "f5840cdd4baf2941b8a5ea95a7d957a455d7384ae052499e1b9ad4ba12f3558a",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:10.519232292Z",
|
||||
"finished_at": "2026-11-12T15:03:01.984133405Z",
|
||||
"volumes": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"target_instance": "21af9ca5-df7b-4c67-80fa-ab17dca13711",
|
||||
"selected_service": "api1",
|
||||
"before": [
|
||||
{
|
||||
"service": "api1",
|
||||
"container": "7a544460999be0a492d470d5405eb7de664a6ba0d7c7e5f5b87380656b472f3f",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:07.279571304Z",
|
||||
"finished_at": "2026-11-12T15:03:02.323870408Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "api2",
|
||||
"container": "a48a69ce0119685403c3d0089606a65d50a0b6f60485f8e961c408887fb1ed9c",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:07.44111824Z",
|
||||
"finished_at": "2026-11-12T15:03:02.326250394Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "db",
|
||||
"container": "7d39044be1430f97c6720e95ecd4b6034b61eb0108e2b7b6629228bdbff7b484",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:03.311328241Z",
|
||||
"finished_at": "2026-11-12T15:03:02.656514582Z",
|
||||
"volumes": [
|
||||
"mtusi-lab3_pgdata"
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "lb",
|
||||
"container": "f5840cdd4baf2941b8a5ea95a7d957a455d7384ae052499e1b9ad4ba12f3558a",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:10.519232292Z",
|
||||
"finished_at": "2026-11-12T15:03:01.984133405Z",
|
||||
"volumes": []
|
||||
}
|
||||
],
|
||||
"after": [
|
||||
{
|
||||
"service": "api1",
|
||||
"container": "7a544460999be0a492d470d5405eb7de664a6ba0d7c7e5f5b87380656b472f3f",
|
||||
"running": false,
|
||||
"started_at": "2026-11-12T15:03:07.279571304Z",
|
||||
"finished_at": "2026-11-12T15:03:13.382026213Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "api2",
|
||||
"container": "a48a69ce0119685403c3d0089606a65d50a0b6f60485f8e961c408887fb1ed9c",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:07.44111824Z",
|
||||
"finished_at": "2026-11-12T15:03:02.326250394Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "db",
|
||||
"container": "7d39044be1430f97c6720e95ecd4b6034b61eb0108e2b7b6629228bdbff7b484",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:03.311328241Z",
|
||||
"finished_at": "2026-11-12T15:03:02.656514582Z",
|
||||
"volumes": [
|
||||
"mtusi-lab3_pgdata"
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "lb",
|
||||
"container": "f5840cdd4baf2941b8a5ea95a7d957a455d7384ae052499e1b9ad4ba12f3558a",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:10.519232292Z",
|
||||
"finished_at": "2026-11-12T15:03:01.984133405Z",
|
||||
"volumes": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"target_instance": "f50c3850-ddde-4ce7-99a1-5ebc59143608",
|
||||
"selected_service": "api2",
|
||||
"before": [
|
||||
{
|
||||
"service": "api1",
|
||||
"container": "7a544460999be0a492d470d5405eb7de664a6ba0d7c7e5f5b87380656b472f3f",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:17.945077862Z",
|
||||
"finished_at": "2026-11-12T15:03:13.382026213Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "api2",
|
||||
"container": "a48a69ce0119685403c3d0089606a65d50a0b6f60485f8e961c408887fb1ed9c",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:07.44111824Z",
|
||||
"finished_at": "2026-11-12T15:03:02.326250394Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "db",
|
||||
"container": "7d39044be1430f97c6720e95ecd4b6034b61eb0108e2b7b6629228bdbff7b484",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:03.311328241Z",
|
||||
"finished_at": "2026-11-12T15:03:02.656514582Z",
|
||||
"volumes": [
|
||||
"mtusi-lab3_pgdata"
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "lb",
|
||||
"container": "f5840cdd4baf2941b8a5ea95a7d957a455d7384ae052499e1b9ad4ba12f3558a",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:10.519232292Z",
|
||||
"finished_at": "2026-11-12T15:03:01.984133405Z",
|
||||
"volumes": []
|
||||
}
|
||||
],
|
||||
"after": [
|
||||
{
|
||||
"service": "api1",
|
||||
"container": "7a544460999be0a492d470d5405eb7de664a6ba0d7c7e5f5b87380656b472f3f",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:17.945077862Z",
|
||||
"finished_at": "2026-11-12T15:03:13.382026213Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "api2",
|
||||
"container": "a48a69ce0119685403c3d0089606a65d50a0b6f60485f8e961c408887fb1ed9c",
|
||||
"running": false,
|
||||
"started_at": "2026-11-12T15:03:07.44111824Z",
|
||||
"finished_at": "2026-11-12T15:03:22.913342968Z",
|
||||
"volumes": []
|
||||
},
|
||||
{
|
||||
"service": "db",
|
||||
"container": "7d39044be1430f97c6720e95ecd4b6034b61eb0108e2b7b6629228bdbff7b484",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:03.311328241Z",
|
||||
"finished_at": "2026-11-12T15:03:02.656514582Z",
|
||||
"volumes": [
|
||||
"mtusi-lab3_pgdata"
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "lb",
|
||||
"container": "f5840cdd4baf2941b8a5ea95a7d957a455d7384ae052499e1b9ad4ba12f3558a",
|
||||
"running": true,
|
||||
"started_at": "2026-11-12T15:03:10.519232292Z",
|
||||
"finished_at": "2026-11-12T15:03:01.984133405Z",
|
||||
"volumes": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
PASS: migrations repeat without data changes; 24-hour retention; conflict inserts no duplicate; expired key may be reused without deleting old message; FK failure leaves no idempotency result.
|
||||
@@ -0,0 +1,6 @@
|
||||
PASS: one session on 2 replicas; 16 concurrent same-key requests across both yield 1 message; changed payload=409; user/chat scope isolated; invalid request does not consume key.
|
||||
PASS: full restart preserves session, signed cursor and idempotency response.
|
||||
{"stopped":"api1","recovery_ms":5496,"transient_failures":3,"confirmed_messages_preserved":true}
|
||||
{"stopped":"api2","recovery_ms":5930,"transient_failures":3,"confirmed_messages_preserved":true}
|
||||
PASS: either replica can stop; surviving replica reads, writes and replays without duplicates. Both replicas restored.
|
||||
PASS: replay after logout cannot bypass authentication.
|
||||
@@ -0,0 +1,36 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
timeout connect 1s
|
||||
timeout client 15s
|
||||
timeout server 15s
|
||||
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 nx 1s
|
||||
hold timeout 1s
|
||||
hold refused 1s
|
||||
hold other 1s
|
||||
hold obsolete 1s
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
default_backend messenger
|
||||
|
||||
backend messenger
|
||||
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 check inter 1s fall 2 rise 1 resolvers docker init-addr last,libc,none
|
||||
server api1 api1:8080
|
||||
server api2 api2:8080
|
||||
@@ -0,0 +1,32 @@
|
||||
# Изменения после lab2
|
||||
|
||||
Миграция 001 сохранена. PostgreSQL хранит users, chats, chat_members, messages,
|
||||
sessions, app_settings. schema_migrations хранит версии и checksum миграций.
|
||||
|
||||
Миграция 002 добавляет message_requests:
|
||||
- составной PK (user_id, chat_id, key);
|
||||
- внешние ключи на users, chats и messages;
|
||||
- исходный text, message_id, полный response JSONB и expires_at;
|
||||
- индекс expires_at для последующей очистки.
|
||||
|
||||
Операция отправки:
|
||||
1. API проверяет Bearer, членство, ключ и JSON.
|
||||
2. BEGIN на одном соединении PostgreSQL.
|
||||
3. pg_advisory_xact_lock по хешу (user_id, chat_id, key).
|
||||
4. Если ключ истёк, удалить только его запись, не сообщение.
|
||||
5. Если ключ есть: вернуть прежний response или 409 при другом text.
|
||||
6. Если ключа нет: INSERT сообщения и INSERT результата операции.
|
||||
7. COMMIT, затем HTTP 201. При ошибке ROLLBACK, результат ошибки не фиксируется.
|
||||
|
||||
Область ключа соответствует пользователю + POST + каноническому пути чата.
|
||||
Другие методы/маршруты не используют message_requests. Хеш используется только
|
||||
для блокировки: полное сравнение ключа идёт по PK, поэтому коллизия хеша не
|
||||
смешивает результаты. Она может лишь временно сериализовать разные операции.
|
||||
|
||||
Отказ до COMMIT откатывает транзакцию. Отказ после COMMIT, но до получения ответа
|
||||
клиентом, безопасно разрешается повтором с тем же ключом. Обе реплики используют
|
||||
одну БД и не хранят локальный кэш результатов. Сессии и ключ подписи курсоров
|
||||
также общие и сохраняются при перезапуске.
|
||||
|
||||
Миграции выполняет отдельный сервис migrate до запуска API. Сами API миграции
|
||||
не запускают. Новая схема аддитивна, но rolling update под нагрузкой не проверялся.
|
||||
@@ -0,0 +1,35 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz(3) NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at timestamptz(3) 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 TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz(3) NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||
);
|
||||
CREATE TABLE sessions (
|
||||
token_hash text PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz(3) NOT NULL
|
||||
);
|
||||
CREATE TABLE app_settings (key text PRIMARY KEY, value text NOT NULL);
|
||||
CREATE INDEX messages_history ON messages(chat_id, created_at, id);
|
||||
CREATE INDEX chats_order ON chats(created_at, id);
|
||||
CREATE INDEX member_chats ON chat_members(user_id, chat_id);
|
||||
CREATE INDEX sessions_expiry ON sessions(expires_at);
|
||||
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE message_requests (
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
key text NOT NULL,
|
||||
text text NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages(id),
|
||||
response jsonb NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (user_id, chat_id, key)
|
||||
);
|
||||
CREATE INDEX message_requests_expiry ON message_requests(expires_at);
|
||||
Generated
+162
@@ -0,0 +1,162 @@
|
||||
{
|
||||
"name": "mtusi-lab3-messenger",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "mtusi-lab3-messenger",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"pg": "8.16.3"
|
||||
}
|
||||
},
|
||||
"node_modules/pg": {
|
||||
"version": "8.16.3",
|
||||
"resolved": "https://registry.npmjs.org/pg/-/pg-8.16.3.tgz",
|
||||
"integrity": "sha512-enxc1h0jA/aq5oSDMvqyW3q89ra6XIIDZgCX9vkMrnz5DFTw/Ny3Li2lFQ+pt3L6MCgm/5o2o8HW9hiJji+xvw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-connection-string": "^2.9.1",
|
||||
"pg-pool": "^3.10.1",
|
||||
"pg-protocol": "^1.10.3",
|
||||
"pg-types": "2.2.0",
|
||||
"pgpass": "1.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"pg-cloudflare": "^1.2.7"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"pg-native": ">=3.0.1"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"pg-native": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/pg-cloudflare": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
|
||||
"integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/pg-connection-string": {
|
||||
"version": "2.14.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
|
||||
"integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-int8": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
|
||||
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pg-pool": {
|
||||
"version": "3.14.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
|
||||
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"pg": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pg-protocol": {
|
||||
"version": "1.16.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
|
||||
"integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-types": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
|
||||
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-int8": "1.0.1",
|
||||
"postgres-array": "~2.0.0",
|
||||
"postgres-bytea": "~1.0.0",
|
||||
"postgres-date": "~1.0.4",
|
||||
"postgres-interval": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/pgpass": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
|
||||
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"split2": "^4.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-array": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-bytea": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
|
||||
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-date": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
|
||||
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-interval": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
|
||||
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"xtend": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/split2": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
|
||||
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">= 10.x"
|
||||
}
|
||||
},
|
||||
"node_modules/xtend": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.4"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "mtusi-lab3-messenger",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": { "start": "node src/server.js", "migrate": "node src/migrate.js" },
|
||||
"dependencies": { "pg": "8.16.3" }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Explicit lab3-only lifecycle hooks. Never delete volumes or print credentials."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
os.chdir(ROOT)
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(['docker', *args], text=True).strip()
|
||||
|
||||
def compose(*args):
|
||||
return docker('compose', *args)
|
||||
|
||||
def snapshot():
|
||||
result = []
|
||||
containers = compose('ps', '-a', '-q').splitlines()
|
||||
if not containers:
|
||||
return result
|
||||
# One bulk inspect keeps the stop hook well below its 10-second budget.
|
||||
# Only these selected fields are written; Config/Env are never logged.
|
||||
for container in json.loads(docker('inspect', *containers)):
|
||||
service = container['Config']['Labels']['com.docker.compose.service']
|
||||
if service not in ('lb', 'api1', 'api2', 'db'):
|
||||
continue
|
||||
state, mounts = container['State'], container['Mounts']
|
||||
result.append({'service': service, 'container': container['Id'], 'running': state['Running'],
|
||||
'started_at': state['StartedAt'], 'finished_at': state['FinishedAt'],
|
||||
'volumes': [m['Name'] for m in mounts if m['Type'] == 'volume']})
|
||||
return result
|
||||
|
||||
def save(name, value):
|
||||
(ROOT / 'evidence').mkdir(exist_ok=True)
|
||||
(ROOT / 'evidence' / name).write_text(json.dumps(value, indent=2) + '\n', encoding='utf-8')
|
||||
|
||||
def main():
|
||||
action = sys.argv[1]
|
||||
if action == 'restart':
|
||||
before = snapshot()
|
||||
compose('stop', 'lb', 'api1', 'api2', 'db')
|
||||
compose('up', '-d', '--wait', '--wait-timeout', '30', 'db')
|
||||
compose('run', '--rm', '--no-deps', 'migrate')
|
||||
compose('up', '-d', '--no-deps', '--wait', '--wait-timeout', '30', 'api1', 'api2')
|
||||
compose('up', '-d', '--no-deps', 'lb')
|
||||
save('restart-scope.json', {'before': before, 'after': snapshot()})
|
||||
elif action == 'stop-one':
|
||||
target = os.environ.get('TARGET_INSTANCE_ID')
|
||||
if not target:
|
||||
raise RuntimeError('TARGET_INSTANCE_ID required')
|
||||
before = snapshot()
|
||||
selected = None
|
||||
for service in ('api1', 'api2'):
|
||||
code = "fetch('http://127.0.0.1:8080/health/live').then(r=>console.log(r.headers.get('x-instance-id'))).catch(()=>process.exit(1))"
|
||||
instance = compose('exec', '-T', service, 'node', '-e', code)
|
||||
if instance == target:
|
||||
selected = service
|
||||
break
|
||||
if selected is None:
|
||||
raise RuntimeError('Target is not a running API in this lab')
|
||||
compose('stop', '-t', '2', selected)
|
||||
after = snapshot()
|
||||
assert not next(s for s in after if s['service'] == selected)['running']
|
||||
assert all(s['running'] for s in after if s['service'] != selected)
|
||||
save('stop-' + selected + '.json', {'target_instance': target, 'selected_service': selected, 'before': before, 'after': after})
|
||||
elif action == 'restore':
|
||||
compose('up', '-d', '--no-deps', '--wait', '--wait-timeout', '30', 'api1', 'api2')
|
||||
else:
|
||||
raise RuntimeError('Unknown action')
|
||||
print('PASS: ' + action + ' completed for mtusi-lab3')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
if defined LAB_PYTHON (
|
||||
"%LAB_PYTHON%" -X utf8 "%~dp0control.py" restart
|
||||
) else (
|
||||
py -X utf8 "%~dp0control.py" restart
|
||||
)
|
||||
exit /b %errorlevel%
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/control.py restart
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Generate local credentials once; never print or rotate existing secrets."""
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
directory = root / 'secrets'
|
||||
directory.mkdir(exist_ok=True)
|
||||
password_file = directory / 'postgres_password'
|
||||
url_file = directory / 'database_url'
|
||||
if password_file.exists() != url_file.exists():
|
||||
raise SystemExit('Incomplete secrets: restore the missing file; do not rotate an existing database password.')
|
||||
if not password_file.exists():
|
||||
password = secrets.token_hex(32)
|
||||
password_file.write_text(password + '\n', encoding='utf-8')
|
||||
url_file.write_text('postgresql://messenger:' + password + '@db:5432/messenger\n', encoding='utf-8')
|
||||
password_file.chmod(0o600)
|
||||
url_file.chmod(0o600)
|
||||
if not (root / '.env').exists():
|
||||
shutil.copyfile(root / '.env.example', root / '.env')
|
||||
print('Local .env and secrets ready; values are not printed. Existing credentials preserved.')
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
if defined LAB_PYTHON (
|
||||
"%LAB_PYTHON%" -X utf8 "%~dp0control.py" stop-one
|
||||
) else (
|
||||
py -X utf8 "%~dp0control.py" stop-one
|
||||
)
|
||||
exit /b %errorlevel%
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/control.py stop-one
|
||||
@@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
const { readFileSync } = require('node:fs');
|
||||
const { Pool } = require('pg');
|
||||
const pool = new Pool({
|
||||
connectionString: readFileSync(process.env.DATABASE_URL_FILE || '/run/secrets/database_url', 'utf8').trim(),
|
||||
max: 10, connectionTimeoutMillis: 3000, idleTimeoutMillis: 10000,
|
||||
statement_timeout: 5000,
|
||||
});
|
||||
pool.on('error', () => console.error('Database connection unavailable'));
|
||||
async function transaction(work) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const result = await work(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw error;
|
||||
} finally { client.release(); }
|
||||
}
|
||||
module.exports = { pool, transaction };
|
||||
@@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const { transaction } = require('./db');
|
||||
const retention = Number(process.env.IDEMPOTENCY_TTL_SECONDS || 86400);
|
||||
if (!Number.isSafeInteger(retention) || retention < 86400) throw new Error('Idempotency retention must be at least 24 hours');
|
||||
|
||||
async function sendMessage(userId, chatId, key, text) {
|
||||
return transaction(async client => {
|
||||
// Shared PostgreSQL lock serializes this operation across all API replicas.
|
||||
// Hash collisions only serialize unrelated keys; the actual lookup uses the full scope.
|
||||
const scope = JSON.stringify([userId, chatId, key]);
|
||||
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [scope]);
|
||||
await client.query(`DELETE FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3
|
||||
AND expires_at <= clock_timestamp()`, [userId, chatId, key]);
|
||||
const prior = await client.query('SELECT text,response FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3', [userId, chatId, key]);
|
||||
if (prior.rowCount) {
|
||||
if (prior.rows[0].text !== text) throw Object.assign(new Error('Key already used for another message'), { status: 409, code: 'conflict' });
|
||||
return prior.rows[0].response;
|
||||
}
|
||||
const message = (await client.query(`INSERT INTO messages(id,chat_id,sender_id,text)
|
||||
VALUES($1,$2,$3,$4) RETURNING *`, [randomUUID(), chatId, userId, text])).rows[0];
|
||||
await client.query(`INSERT INTO message_requests(user_id,chat_id,key,text,message_id,response,expires_at)
|
||||
VALUES($1,$2,$3,$4,$5,$6::jsonb,clock_timestamp()+$7*interval '1 second')`,
|
||||
[userId, chatId, key, text, message.id, JSON.stringify(message), retention]);
|
||||
// The HTTP handler returns 201 only after transaction() completes COMMIT.
|
||||
return message;
|
||||
});
|
||||
}
|
||||
module.exports = { sendMessage };
|
||||
@@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
const { readFileSync, readdirSync } = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createHash, randomBytes } = require('node:crypto');
|
||||
const { pool } = require('./db');
|
||||
async function migrate() {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('SELECT pg_advisory_lock(202602)');
|
||||
await client.query(`CREATE TABLE IF NOT EXISTS schema_migrations
|
||||
(version text PRIMARY KEY, checksum text NOT NULL)`);
|
||||
const dir = path.join(__dirname, '..', 'migrations');
|
||||
for (const version of readdirSync(dir).filter(f => /^\d+.*\.sql$/.test(f)).sort()) {
|
||||
const sql = readFileSync(path.join(dir, version), 'utf8');
|
||||
const checksum = createHash('sha256').update(sql).digest('hex');
|
||||
const existing = await client.query('SELECT checksum FROM schema_migrations WHERE version=$1', [version]);
|
||||
if (existing.rowCount) {
|
||||
if (existing.rows[0].checksum !== checksum) throw new Error('Migration checksum mismatch');
|
||||
continue;
|
||||
}
|
||||
await client.query('BEGIN');
|
||||
try {
|
||||
await client.query(sql);
|
||||
await client.query('INSERT INTO schema_migrations VALUES ($1,$2)', [version, checksum]);
|
||||
await client.query('COMMIT');
|
||||
} catch (error) { await client.query('ROLLBACK'); throw error; }
|
||||
console.log('Applied migration ' + version);
|
||||
}
|
||||
await client.query(`INSERT INTO app_settings VALUES ('cursor_secret',$1) ON CONFLICT DO NOTHING`, [randomBytes(32).toString('hex')]);
|
||||
} finally {
|
||||
await client.query('SELECT pg_advisory_unlock(202602)').catch(() => {});
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
module.exports = { migrate };
|
||||
if (require.main === module) migrate().then(() => console.log('Migrations up to date'))
|
||||
.catch(() => { console.error('Migration failed'); process.exitCode = 1; }).finally(() => pool.end());
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
'use strict';
|
||||
const http = require('node:http');
|
||||
const { randomUUID, randomBytes, createHash, createHmac, scrypt, timingSafeEqual } = require('node:crypto');
|
||||
const { promisify } = require('node:util');
|
||||
const { pool, transaction } = require('./db');
|
||||
const { sendMessage } = require('./messages');
|
||||
const instanceId = randomUUID();
|
||||
let stopping = false;
|
||||
const derive = promisify(scrypt);
|
||||
const kdfOptions = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
|
||||
const ttl = Number(process.env.SESSION_TTL_SECONDS || 3600);
|
||||
if (!Number.isSafeInteger(ttl) || ttl < 1) throw new Error('Invalid SESSION_TTL_SECONDS');
|
||||
let cursorSecret;
|
||||
const userColumns = 'id, username, display_name, created_at';
|
||||
const chatSelect = `SELECT c.id,c.title,c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id) AS member_ids FROM chats c`;
|
||||
function fail(status, code, message) { throw Object.assign(new Error(message), { status, code }); }
|
||||
function invalid(message = 'Invalid request') { fail(400, 'invalid_request', message); }
|
||||
function unauthorized() { fail(401, 'unauthorized', 'Invalid credentials or session'); }
|
||||
function uuid(value) {
|
||||
if (typeof value !== 'string' || value.length !== 36 || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)) invalid('Invalid UUID');
|
||||
return value.toLowerCase();
|
||||
}
|
||||
function fields(body, names) {
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body) ||
|
||||
Object.keys(body).length !== names.length || !names.every(k => Object.hasOwn(body, k))) invalid('Invalid fields');
|
||||
}
|
||||
function string(value, max, min = 1) {
|
||||
if (typeof value !== 'string' || !value.isWellFormed() || /^[\p{White_Space}\uFEFF]*$/u.test(value) ||
|
||||
[...value].length < min || [...value].length > max || value.includes('\0')) invalid('Invalid string');
|
||||
return value;
|
||||
}
|
||||
function username(value) {
|
||||
if (typeof value !== 'string' || value.length < 3 || value.length > 32 || /[^a-z0-9_]/.test(value)) invalid('Invalid username');
|
||||
}
|
||||
function password(value) {
|
||||
if (typeof value !== 'string' || !value.isWellFormed() || [...value].length < 12 || [...value].length > 128 ||
|
||||
/^[\p{White_Space}\uFEFF]*$/u.test(value)) invalid('Invalid password');
|
||||
}
|
||||
function digest(token) { return createHash('sha256').update(token).digest('hex'); }
|
||||
async function hashPassword(value) {
|
||||
const salt = randomBytes(16).toString('hex');
|
||||
const hash = await derive(value, salt, 64, kdfOptions);
|
||||
return `scrypt$32768$8$1$${salt}$${hash.toString('hex')}`;
|
||||
}
|
||||
const dummySalt = randomBytes(16).toString('hex');
|
||||
async function verifyPassword(value, encoded) {
|
||||
const parts = encoded?.split('$');
|
||||
const salt = parts ? parts[4] : dummySalt;
|
||||
const expected = parts ? Buffer.from(parts[5], 'hex') : Buffer.alloc(64);
|
||||
const actual = await derive(value, salt, 64, kdfOptions);
|
||||
return Boolean(encoded) && expected.length === actual.length && timingSafeEqual(expected, actual);
|
||||
}
|
||||
async function rawBody(req) {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of req) {
|
||||
size += chunk.length;
|
||||
if (size > 1024 * 1024) fail(413, 'payload_too_large', 'Request body too large');
|
||||
chunks.push(chunk);
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
async function body(req) {
|
||||
if (req.headers['content-type']?.split(';')[0].trim().toLowerCase() !== 'application/json')
|
||||
fail(415, 'unsupported_media_type', 'Expected application/json');
|
||||
const bytes = await rawBody(req);
|
||||
try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
|
||||
catch { invalid('Invalid JSON'); }
|
||||
}
|
||||
async function identity(req) {
|
||||
const match = /^Bearer ([A-Za-z0-9_-]{43})$/i.exec(req.headers.authorization || '');
|
||||
if (!match) unauthorized();
|
||||
const tokenHash = digest(match[1]);
|
||||
const result = await pool.query(`SELECT u.id,u.username,u.display_name,u.created_at
|
||||
FROM sessions s JOIN users u ON u.id=s.user_id
|
||||
WHERE token_hash=$1 AND expires_at > clock_timestamp()`, [tokenHash]);
|
||||
if (!result.rowCount) unauthorized();
|
||||
return { user: result.rows[0], tokenHash };
|
||||
}
|
||||
async function accessible(id, user) {
|
||||
const result = await pool.query(chatSelect + ` WHERE c.id=$1 AND EXISTS
|
||||
(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2)`, [uuid(id), user.id]);
|
||||
if (!result.rowCount) fail(404, 'not_found', 'Object not found');
|
||||
return result.rows[0];
|
||||
}
|
||||
function signature(payload) { return createHmac('sha256', cursorSecret).update(payload).digest('base64url'); }
|
||||
function pagination(query, scope) {
|
||||
if (query.getAll('limit').length > 1 || query.getAll('cursor').length > 1) invalid();
|
||||
const raw = query.get('limit') ?? '50';
|
||||
if (!/^\d+$/.test(raw) || Number(raw) < 1 || Number(raw) > 100) invalid('Invalid limit');
|
||||
let after = null;
|
||||
if (query.has('cursor')) {
|
||||
try {
|
||||
const token = query.get('cursor');
|
||||
if (!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token)) throw new Error();
|
||||
const [payload, mac] = token.split('.');
|
||||
if (signature(payload) !== mac) throw new Error();
|
||||
after = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
||||
if (after.scope !== scope || typeof after.created_at !== 'string' || !Number.isFinite(Date.parse(after.created_at))) throw new Error();
|
||||
uuid(after.id);
|
||||
} catch { invalid('Invalid cursor'); }
|
||||
}
|
||||
return { limit: Number(raw), after, scope };
|
||||
}
|
||||
function page(rows, paging) {
|
||||
const items = rows.slice(0, paging.limit);
|
||||
let next_cursor = null;
|
||||
if (rows.length > paging.limit) {
|
||||
const last = items.at(-1);
|
||||
const payload = Buffer.from(JSON.stringify({ scope: paging.scope, created_at: last.created_at, id: last.id })).toString('base64url');
|
||||
next_cursor = payload + '.' + signature(payload);
|
||||
}
|
||||
return { items, next_cursor };
|
||||
}
|
||||
async function route(req) {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
const path = url.pathname, method = req.method;
|
||||
if (method === 'GET' && path === '/health/live') return [200, { status: 'ok' }];
|
||||
if (stopping) fail(503, 'unavailable', 'Server is stopping');
|
||||
if (method === 'GET' && path === '/health/ready') {
|
||||
try { await pool.query('SELECT 1'); }
|
||||
catch { fail(503, 'unavailable', 'Database unavailable'); }
|
||||
return [200, { status: 'ok' }];
|
||||
}
|
||||
if (method === 'POST' && path === '/api/v1/users') {
|
||||
const data = await body(req);
|
||||
fields(data, ['username', 'display_name', 'password']);
|
||||
username(data.username); string(data.display_name, 100); password(data.password);
|
||||
const hash = await hashPassword(data.password);
|
||||
try {
|
||||
const result = await pool.query(`INSERT INTO users(id,username,display_name,password_hash)
|
||||
VALUES($1,$2,$3,$4) RETURNING ${userColumns}`, [randomUUID(), data.username, data.display_name, hash]);
|
||||
return [201, result.rows[0]];
|
||||
} catch (error) {
|
||||
if (error.code === '23505') fail(409, 'conflict', 'Username already exists');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (method === 'POST' && path === '/api/v1/auth/sessions') {
|
||||
const match = /^Basic ([A-Za-z0-9+/]+={0,2})$/i.exec(req.headers.authorization || '');
|
||||
if (!match) unauthorized();
|
||||
let name, value;
|
||||
try {
|
||||
const bytes = Buffer.from(match[1], 'base64');
|
||||
if (bytes.toString('base64') !== match[1]) throw new Error();
|
||||
const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
||||
const colon = decoded.indexOf(':');
|
||||
if (colon < 0) throw new Error();
|
||||
name = decoded.slice(0, colon); value = decoded.slice(colon + 1);
|
||||
username(name); password(value);
|
||||
} catch { unauthorized(); }
|
||||
if ((await rawBody(req)).length) invalid('Login must not have a body');
|
||||
const result = await pool.query(`SELECT ${userColumns},password_hash FROM users WHERE username=$1`, [name]);
|
||||
const row = result.rows[0];
|
||||
if (!await verifyPassword(value, row?.password_hash)) unauthorized();
|
||||
const { password_hash, ...user } = row;
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const session = await pool.query(`INSERT INTO sessions(token_hash,user_id,expires_at)
|
||||
VALUES($1,$2,clock_timestamp()+$3*interval '1 second') RETURNING expires_at`, [digest(token), user.id, ttl]);
|
||||
return [201, { token, token_type: 'Bearer', expires_at: session.rows[0].expires_at, user }];
|
||||
}
|
||||
const { user, tokenHash } = await identity(req);
|
||||
if (method === 'DELETE' && path === '/api/v1/auth/sessions/current') {
|
||||
await pool.query('DELETE FROM sessions WHERE token_hash=$1', [tokenHash]);
|
||||
return [204, null];
|
||||
}
|
||||
if (method === 'GET' && path === '/api/v1/users/me') return [200, user];
|
||||
if (path === '/api/v1/chats' && method === 'POST') {
|
||||
const data = await body(req);
|
||||
fields(data, ['title', 'member_ids']); string(data.title, 100);
|
||||
if (!Array.isArray(data.member_ids) || data.member_ids.length < 1 || data.member_ids.length > 100) invalid('Invalid members');
|
||||
const ids = data.member_ids.map(uuid);
|
||||
if (new Set(ids).size !== ids.length || !ids.includes(user.id)) invalid('Invalid members');
|
||||
return [201, await transaction(async client => {
|
||||
const known = await client.query('SELECT id FROM users WHERE id=ANY($1::uuid[])', [ids]);
|
||||
if (known.rowCount !== ids.length) invalid('Unknown member');
|
||||
const chat = (await client.query('INSERT INTO chats(id,title) VALUES($1,$2) RETURNING *', [randomUUID(), data.title])).rows[0];
|
||||
await client.query('INSERT INTO chat_members(chat_id,user_id) SELECT $1,unnest($2::uuid[])', [chat.id, ids]);
|
||||
return { ...chat, member_ids: ids.sort() };
|
||||
})];
|
||||
}
|
||||
if (path === '/api/v1/chats' && method === 'GET') {
|
||||
const paging = pagination(url.searchParams, 'chats:' + user.id);
|
||||
const rows = (await pool.query(chatSelect + ` WHERE EXISTS
|
||||
(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$1)
|
||||
AND ($2::timestamptz IS NULL OR (c.created_at,c.id)>($2::timestamptz,$3::uuid))
|
||||
ORDER BY c.created_at,c.id LIMIT $4`, [user.id, paging.after?.created_at ?? null, paging.after?.id ?? null, paging.limit + 1])).rows;
|
||||
return [200, page(rows, paging)];
|
||||
}
|
||||
const match = path.match(/^\/api\/v1\/chats\/([^/]+)(\/messages)?$/);
|
||||
if (match) {
|
||||
const chat = await accessible(match[1], user);
|
||||
if (!match[2] && method === 'GET') return [200, chat];
|
||||
if (match[2] && method === 'POST') {
|
||||
const key = req.headers['idempotency-key'];
|
||||
if (typeof key !== 'string' || key.length < 1 || key.length > 128 || /[^A-Za-z0-9._:-]/.test(key)) invalid('Invalid Idempotency-Key');
|
||||
const data = await body(req); fields(data, ['text']); string(data.text, 4000);
|
||||
return [201, await sendMessage(user.id, chat.id, key, data.text)];
|
||||
}
|
||||
if (match[2] && method === 'GET') {
|
||||
const paging = pagination(url.searchParams, 'messages:' + chat.id);
|
||||
const result = await pool.query(`SELECT * FROM messages WHERE chat_id=$1
|
||||
AND ($2::timestamptz IS NULL OR (created_at,id)>($2::timestamptz,$3::uuid))
|
||||
ORDER BY created_at,id LIMIT $4`, [chat.id, paging.after?.created_at ?? null, paging.after?.id ?? null, paging.limit + 1]);
|
||||
return [200, page(result.rows, paging)];
|
||||
}
|
||||
}
|
||||
fail(404, 'not_found', 'Object not found');
|
||||
}
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const request_id = randomUUID();
|
||||
let status, data;
|
||||
const headers = { 'Content-Type': 'application/json; charset=utf-8', 'X-Request-Id': request_id, 'X-Instance-Id': instanceId };
|
||||
try { [status, data] = await route(req); }
|
||||
catch (error) {
|
||||
status = error.status || (/^(08|53|57)/.test(error.code || '') || ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT'].includes(error.code) ? 503 : 500);
|
||||
data = { error: { code: error.status ? error.code : status === 503 ? 'unavailable' : 'internal_error',
|
||||
message: error.status ? error.message : status === 503 ? 'Database unavailable' : 'Internal error', request_id } };
|
||||
if (status === 401) headers['WWW-Authenticate'] = req.url.split('?')[0] === '/api/v1/auth/sessions'
|
||||
? 'Basic realm="messenger", charset="UTF-8"' : 'Bearer realm="messenger"';
|
||||
}
|
||||
res.writeHead(status, headers);
|
||||
res.end(status === 204 ? undefined : JSON.stringify(data));
|
||||
});
|
||||
async function main() {
|
||||
cursorSecret = (await pool.query("SELECT value FROM app_settings WHERE key='cursor_secret'")).rows[0].value;
|
||||
server.listen(Number(process.env.APP_PORT || 8080), process.env.APP_HOST || '0.0.0.0', () => console.log('Messenger lab3 ready; instance=' + instanceId));
|
||||
}
|
||||
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => {
|
||||
stopping = true;
|
||||
server.close(() => pool.end());
|
||||
setTimeout(() => process.exit(1), 9000).unref();
|
||||
});
|
||||
main().catch(() => { console.error('Startup failed: check database and migrations'); process.exitCode = 1; pool.end(); });
|
||||
@@ -0,0 +1,110 @@
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const base = process.env.BASE_URL || 'http://localhost:8080';
|
||||
async function call(method, path, expected = 200, actor, body, headers = {}) {
|
||||
const response = await fetch(base + path, { method, headers: {
|
||||
...(actor ? { Authorization: 'Bearer ' + actor.token } : {}),
|
||||
...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...headers },
|
||||
body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(5000) });
|
||||
assert.equal(response.status, expected, `${method} ${path}: unexpected status`);
|
||||
assert.ok(response.headers.get('x-request-id'));
|
||||
assert.ok(response.headers.get('x-instance-id'));
|
||||
const data = response.status === 204 ? null : await response.json();
|
||||
if (expected >= 400) assert.equal(data.error.request_id, response.headers.get('x-request-id'));
|
||||
return { data, instance: response.headers.get('x-instance-id') };
|
||||
}
|
||||
async function user() {
|
||||
const username = 'u_' + randomUUID().replaceAll('-', '').slice(0, 16);
|
||||
const password = 'Password-' + randomUUID();
|
||||
const created = await call('POST', '/api/v1/users', 201, null, { username, password, display_name: 'Студент 😀' });
|
||||
const login = await call('POST', '/api/v1/auth/sessions', 201, null, undefined,
|
||||
{ Authorization: 'Basic ' + Buffer.from(username + ':' + password).toString('base64') });
|
||||
return { id: created.data.id, token: login.data.token };
|
||||
}
|
||||
async function main() {
|
||||
const a = await user(), b = await user(), outsider = await user();
|
||||
const instances = new Set();
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const result = await call('GET', '/api/v1/users/me', 200, a);
|
||||
assert.equal(result.data.id, a.id);
|
||||
instances.add(result.instance);
|
||||
}
|
||||
assert.equal(instances.size, 2, 'One session must work through both replicas');
|
||||
const chat = (await call('POST', '/api/v1/chats', 201, a, { title: 'Идемпотентность', member_ids: [a.id, b.id] })).data;
|
||||
const path = '/api/v1/chats/' + chat.id + '/messages';
|
||||
const key = randomUUID();
|
||||
const results = await Promise.all(Array.from({ length: 16 }, () => call('POST', path, 201, a,
|
||||
{ text: 'Один ключ — одно сообщение 👋' }, { 'Idempotency-Key': key })));
|
||||
assert.equal(new Set(results.map(r => r.instance)).size, 2);
|
||||
for (const result of results) assert.deepEqual(result.data, results[0].data);
|
||||
let history = (await call('GET', path, 200, b)).data;
|
||||
assert.equal(history.items.length, 1);
|
||||
await call('POST', path, 409, a, { text: 'Другой текст' }, { 'Idempotency-Key': key });
|
||||
await call('POST', path, 400, a, { text: 'Без ключа' });
|
||||
await call('POST', path, 400, a, { text: 'Неверный ключ' }, { 'Idempotency-Key': 'bad key' });
|
||||
await call('POST', path, 404, outsider, { text: 'Один ключ — одно сообщение 👋' }, { 'Idempotency-Key': key });
|
||||
await call('POST', path, 201, b, { text: 'Другой пользователь' }, { 'Idempotency-Key': key });
|
||||
const otherChat = (await call('POST', '/api/v1/chats', 201, a, { title: 'Другой чат', member_ids: [a.id] })).data;
|
||||
await call('POST', '/api/v1/chats/' + otherChat.id + '/messages', 201, a, { text: 'Другой чат' }, { 'Idempotency-Key': key });
|
||||
const retryKey = randomUUID();
|
||||
await call('POST', path, 400, a, { text: '\u0085' }, { 'Idempotency-Key': retryKey });
|
||||
await call('POST', path, 201, a, { text: 'После ошибки можно повторить' }, { 'Idempotency-Key': retryKey });
|
||||
const raceKey = randomUUID();
|
||||
const race = await Promise.all(['Первый', 'Второй'].map(text => fetch(base + path, { method: 'POST',
|
||||
headers: { Authorization: 'Bearer ' + a.token, 'Content-Type': 'application/json', 'Idempotency-Key': raceKey }, body: JSON.stringify({ text }) }).then(r => r.status)));
|
||||
assert.deepEqual(race.sort(), [201, 409]);
|
||||
history = (await call('GET', path, 200, b)).data;
|
||||
assert.equal(history.items.length, 4);
|
||||
console.log('PASS: one session on 2 replicas; 16 concurrent same-key requests across both yield 1 message; changed payload=409; user/chat scope isolated; invalid request does not consume key.');
|
||||
if (process.argv.includes('--lifecycle')) {
|
||||
const python = process.env.LAB_PYTHON || (process.platform === 'win32' ? 'py' : 'python3');
|
||||
const control = action => execFileSync(python, ['scripts/control.py', action], { stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
// Also prove that an idempotency result and cursor survive a full stack restart.
|
||||
const firstPage = (await call('GET', path + '?limit=1', 200, a)).data;
|
||||
control('restart');
|
||||
await waitForReady(a);
|
||||
const replay = await call('POST', path, 201, a, { text: 'Один ключ — одно сообщение 👋' }, { 'Idempotency-Key': key });
|
||||
assert.deepEqual(replay.data, results[0].data);
|
||||
const secondPage = (await call('GET', path + '?limit=100&cursor=' + encodeURIComponent(firstPage.next_cursor), 200, a)).data;
|
||||
assert.equal(firstPage.items.length + secondPage.items.length, 4);
|
||||
console.log('PASS: full restart preserves session, signed cursor and idempotency response.');
|
||||
for (const service of ['api1', 'api2']) {
|
||||
const code = "fetch('http://127.0.0.1:8080/health/live').then(r=>console.log(r.headers.get('x-instance-id')))";
|
||||
const target = execFileSync('docker', ['compose', 'exec', '-T', service, 'node', '-e', code], { encoding: 'utf8' }).trim();
|
||||
process.env.TARGET_INSTANCE_ID = target;
|
||||
const started = Date.now();
|
||||
control('stop-one');
|
||||
let recovered = false, failures = 0;
|
||||
const writeKey = randomUUID();
|
||||
while (Date.now() - started < 10000) {
|
||||
try {
|
||||
const result = await call('POST', path, 201, a, { text: 'Один ключ — одно сообщение 👋' }, { 'Idempotency-Key': key });
|
||||
assert.deepEqual(result.data, results[0].data);
|
||||
assert.notEqual(result.instance, target);
|
||||
await call('POST', path, 201, b, { text: 'После отказа ' + service }, { 'Idempotency-Key': writeKey });
|
||||
const read = await call('GET', path, 200, b);
|
||||
assert.ok(read.data.items.some(m => m.id === results[0].data.id));
|
||||
recovered = true;
|
||||
console.log(JSON.stringify({ stopped: service, recovery_ms: Date.now() - started, transient_failures: failures, confirmed_messages_preserved: true }));
|
||||
break;
|
||||
} catch { failures++; await new Promise(r => setTimeout(r, 100)); }
|
||||
}
|
||||
try { assert.ok(recovered, service + ' did not recover within 10 seconds'); }
|
||||
finally { control('restore'); await waitForReady(a); }
|
||||
}
|
||||
console.log('PASS: either replica can stop; surviving replica reads, writes and replays without duplicates. Both replicas restored.');
|
||||
}
|
||||
await call('DELETE', '/api/v1/auth/sessions/current', 204, a);
|
||||
await call('POST', path, 401, a, { text: 'Один ключ — одно сообщение 👋' }, { 'Idempotency-Key': key });
|
||||
console.log('PASS: replay after logout cannot bypass authentication.');
|
||||
}
|
||||
async function waitForReady(actor) {
|
||||
for (let i = 0; i < 40; i++) {
|
||||
try { await call('GET', '/api/v1/users/me', 200, actor); return; }
|
||||
catch { await new Promise(r => setTimeout(r, 250)); }
|
||||
}
|
||||
throw new Error('LB did not become ready');
|
||||
}
|
||||
main().catch(error => { console.error('FAIL: ' + error.message); process.exitCode = 1; });
|
||||
@@ -0,0 +1,43 @@
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const { pool, transaction } = require('./src/db');
|
||||
const { migrate } = require('./src/migrate');
|
||||
const { sendMessage } = require('./src/messages');
|
||||
async function counts() {
|
||||
const result = {};
|
||||
for (const table of ['users', 'chats', 'chat_members', 'messages', 'sessions', 'message_requests'])
|
||||
result[table] = (await pool.query(`SELECT count(*) AS n FROM ${table}`)).rows[0].n;
|
||||
return result;
|
||||
}
|
||||
async function main() {
|
||||
const before = await counts();
|
||||
await migrate(); await migrate();
|
||||
assert.deepEqual(await counts(), before);
|
||||
assert.equal((await pool.query('SELECT count(*)::int AS n FROM schema_migrations')).rows[0].n, 2);
|
||||
const user = randomUUID(), chat = randomUUID(), key = randomUUID();
|
||||
await transaction(async client => {
|
||||
await client.query('INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)',
|
||||
[user, 'ttl_' + user.replaceAll('-', '').slice(0, 16), 'Synthetic TTL test', 'unusable-test-hash']);
|
||||
await client.query('INSERT INTO chats(id,title) VALUES($1,$2)', [chat, 'Retention test']);
|
||||
await client.query('INSERT INTO chat_members VALUES($1,$2)', [chat, user]);
|
||||
});
|
||||
const first = await sendMessage(user, chat, key, 'Original');
|
||||
await assert.rejects(sendMessage(user, chat, key, 'Changed'), e => e.status === 409);
|
||||
assert.equal((await pool.query('SELECT count(*)::int AS n FROM messages WHERE chat_id=$1', [chat])).rows[0].n, 1);
|
||||
const hours = (await pool.query(`SELECT extract(epoch FROM (expires_at-clock_timestamp()))/3600 AS hours
|
||||
FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3`, [user, chat, key])).rows[0].hours;
|
||||
assert.ok(Number(hours) > 23.9);
|
||||
// Simulate expiry only for the synthetic record, without waiting 24 hours.
|
||||
await pool.query(`UPDATE message_requests SET expires_at=clock_timestamp()-interval '1 second'
|
||||
WHERE user_id=$1 AND chat_id=$2 AND key=$3`, [user, chat, key]);
|
||||
const second = await sendMessage(user, chat, key, 'After expiry');
|
||||
assert.notEqual(first.id, second.id);
|
||||
assert.equal((await pool.query('SELECT count(*)::int AS n FROM messages WHERE chat_id=$1', [chat])).rows[0].n, 2);
|
||||
assert.equal((await pool.query('SELECT count(*)::int AS n FROM message_requests WHERE chat_id=$1', [chat])).rows[0].n, 1);
|
||||
const missingChat = randomUUID();
|
||||
await assert.rejects(sendMessage(user, missingChat, randomUUID(), 'Must rollback'), e => e.code === '23503');
|
||||
assert.equal((await pool.query('SELECT count(*)::int AS n FROM message_requests WHERE chat_id=$1', [missingChat])).rows[0].n, 0);
|
||||
console.log('PASS: migrations repeat without data changes; 24-hour retention; conflict inserts no duplicate; expired key may be reused without deleting old message; FK failure leaves no idempotency result.');
|
||||
}
|
||||
main().catch(error => { console.error('FAIL: storage check (' + (error.code || error.name) + ')'); process.exitCode = 1; }).finally(() => pool.end());
|
||||
Reference in New Issue
Block a user