ЛР 3 - БПИ-2301 - Антонов - на 4 #86
@@ -16,5 +16,9 @@ backups
|
||||
.venv
|
||||
__pycache__
|
||||
node_modules
|
||||
dist
|
||||
coverage
|
||||
evidence
|
||||
.DS_Store
|
||||
.idea
|
||||
.vscode
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
* text=auto eol=lf
|
||||
*.png binary
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"useTabs": true,
|
||||
"tabWidth": 4,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM node:20.17.0-slim AS base
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends openssl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /app
|
||||
|
||||
FROM base AS deps
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
FROM deps AS build
|
||||
COPY prisma ./prisma
|
||||
RUN npx prisma generate
|
||||
COPY tsconfig.json tsconfig.build.json nest-cli.json ./
|
||||
COPY src ./src
|
||||
RUN npm run build
|
||||
|
||||
FROM build AS test
|
||||
COPY contracts/openapi.json ./contracts/openapi.json
|
||||
COPY test ./test
|
||||
CMD ["npm", "test"]
|
||||
|
||||
FROM build AS migrate
|
||||
CMD ["sh", "-c", "DATABASE_URL=\"$(cat \"$DATABASE_URL_FILE\")\" exec npx prisma migrate deploy"]
|
||||
|
||||
FROM build AS prod-deps
|
||||
RUN npm prune --omit=dev
|
||||
|
||||
FROM base AS runtime
|
||||
ENV NODE_ENV=production
|
||||
COPY package.json ./
|
||||
COPY --from=prod-deps /app/node_modules ./node_modules
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY contracts/openapi.json ./contracts/openapi.json
|
||||
|
||||
USER node
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=5s --timeout=2s --start-period=5s --retries=3 \
|
||||
CMD node -e "require('http').get('http://127.0.0.1:8080/health/ready',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"
|
||||
|
||||
CMD ["node", "dist/main.js"]
|
||||
@@ -1,37 +1,201 @@
|
||||
# Отчёт — лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Антонов Егор, БПИ2301
|
||||
- Целевая оценка; выбранный трек 5, если нужен: **4**, трек 5 не заявляется
|
||||
- Commit/PR: ветка `solution/БПИ2301-Antonov`; ссылка на PR — после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: документация Docker Compose (services, deploy, volumes subpath), HAProxy 3.0 (resolvers, server-template, health checks, retry-on, http-error), NestJS/Fastify (lifecycle, close), Prisma (migrate deploy, transactions), PostgreSQL (`INSERT … ON CONFLICT`). Библиотеки — как в lab2: `@nestjs/*` 10, `prisma` 6.1.0, `ioredis` 5.4.1, `argon2` 0.41.1, `jest` + `supertest`. ИИ-ассистент использовался как парный программист: код, тесты, скрипты экспериментов и текст отчёта по моим решениям (Compose + HAProxy, Redis остаётся кэшем, идемпотентность в PostgreSQL) с последующим ревью; все проверки воспроизведены мной на своём стенде.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
На хосте нужен **только Docker** (Engine + Compose v2); python/node/make/sh на хосте не требуются, команды одинаковы в PowerShell и bash. Проверено: Docker 29.3.1, Compose v5.1.1 (внутри `tools` — v2.31.0), Docker Desktop (WSL2), 12 vCPU, 8 GiB RAM.
|
||||
|
||||
| Компонент | Версия |
|
||||
| --- | --- |
|
||||
| API runtime | `node:20.17.0-slim` + openssl, NestJS 10 / Fastify, Prisma 6.1.0 |
|
||||
| Балансировщик | `haproxy:3.0.6-alpine` |
|
||||
| PostgreSQL | `postgres:17.2-alpine` |
|
||||
| Redis | `redis:7.4.1-alpine` |
|
||||
| secrets-init | `alpine:3.20.3` |
|
||||
| tools (проверки) | `docker:27.3.1-cli` + python3, make, git |
|
||||
|
||||
```sh
|
||||
# 1. Запуск: secrets-init → postgres, redis → migrate (один раз) → api ×2 → lb; ждёт healthcheck
|
||||
docker compose up -d --build --wait
|
||||
|
||||
# 2. Публичные проверки внутри контейнера tools (BASE_URL=http://lb:8080)
|
||||
docker compose run --rm --build tools make check
|
||||
docker compose run --rm tools make test
|
||||
docker compose run --rm tools make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
docker compose run --rm tools make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
# вернуть остановленную реплику (без пересоздания остальных)
|
||||
docker compose up -d --no-deps --wait api
|
||||
|
||||
# 3. Эксперименты уровня 4 (JSON в stdout или --output)
|
||||
docker compose run --rm tools python3 scripts/experiment.py idempotency
|
||||
docker compose run --rm tools python3 scripts/experiment.py failover # docker stop каждой реплики по очереди
|
||||
docker compose run --rm tools python3 scripts/experiment.py failover --kill # SIGKILL каждой реплики по очереди
|
||||
docker compose build api
|
||||
docker compose run --rm tools python3 scripts/experiment.py rolling
|
||||
|
||||
# 4. Собственные тесты: отдельные postgres (tmpfs) и redis
|
||||
docker compose -f compose.test.yaml run --rm --build tests
|
||||
docker compose -f compose.test.yaml down
|
||||
|
||||
# 5. Все доказательства в evidence/ одной командой (~7 минут)
|
||||
docker compose run --rm tools sh scripts/collect-evidence.sh
|
||||
|
||||
# Безопасная остановка (данные и секреты сохраняются)
|
||||
docker compose stop # или: docker compose down
|
||||
# Намеренное удаление учебных данных и сгенерированных секретов
|
||||
docker compose down -v
|
||||
```
|
||||
|
||||
- **`.env` необязателен**: в `compose.yaml` те же значения по умолчанию. Для своих: `cp .env.example .env`, затем `docker compose --env-file .env up -d --build --wait`.
|
||||
- **Число реплик**: `API_REPLICAS` (по умолчанию 2) или `docker compose up -d --scale api=3`; HAProxy принимает до 4 реплик без правки конфигурации.
|
||||
- **Секреты** создаёт one-shot сервис `secrets-init`: случайные пароли PostgreSQL и Redis (24 байта из `/dev/urandom`) и строки подключения в именованном volume `secrets`, разложенные по подкаталогам. Каждый сервис монтирует read-only только свой подкаталог (`volume.subpath`). Уже созданные пароли не перезаписываются; файлы из плоской раскладки lab2 переносятся. Действий оператора не требуется; секреты не попадают в Git, образы и логи.
|
||||
- **Наружу опубликован только LB** на `127.0.0.1:8080`. API, PostgreSQL и Redis доступны только во внутренней сети compose.
|
||||
- **Swagger UI**: http://localhost:8080/docs (через LB). Это обязательный контракт `contracts/openapi.json` 1.3.0 без изменений, дополненный в памяти инструкцией и именованными примерами (`src/docs/examples.ts`), включая `Idempotency-Key`; примеры проверяются по JSON Schema контракта в `test/docs.e2e-spec.ts`.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```
|
||||
client ──HTTP──▶ lb (HAProxy, 127.0.0.1:8080) ──round robin, без sticky──▶ api ×2 (без опубликованных портов)
|
||||
│ проверка GET /health/ready каждые 1 s │
|
||||
│ адреса реплик — Docker DNS (имя сервиса api) ├──SQL (pool 10 на реплику)──▶ postgres ── volume pgdata
|
||||
└──кэш сессий──▶ redis (без persistence)
|
||||
|
||||
secrets-init ──▶ volume secrets: postgres/ redis/ api/ migrate/ (каждому сервису — свой подкаталог, ro)
|
||||
migrate ── prisma migrate deploy (один раз, до api) ──▶ postgres
|
||||
```
|
||||
|
||||
| Роль | Service | Health/readiness | Volume | Сеть/порт | Credentials | Лимиты |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| Балансировщик | `lb` | — (проверяет backends сам) | — | `127.0.0.1:8080` | — | 0.25 CPU, 64M |
|
||||
| API ×2 | `api` | Docker HEALTHCHECK и HAProxy: `/health/ready` (`SELECT 1`, при остановке — 503) | — (stateless) | внутренняя, 8080 | `DATABASE_URL_FILE`, `CACHE_URL_FILE` из `secrets/api` | 0.5 CPU, 256M каждая |
|
||||
| БД | `postgres` | `pg_isready` | `pgdata` | внутренняя | `POSTGRES_PASSWORD_FILE` из `secrets/postgres` | 1 CPU, 512M |
|
||||
| Кэш сессий | `redis` | `redis-cli ping` | — | внутренняя | `requirepass` из `secrets/redis` | 0.25 CPU, 128M |
|
||||
| Миграции | `migrate` | exit 0 | — | внутренняя | `secrets/migrate` | 0.5 CPU, 512M |
|
||||
| Bootstrap секретов | `secrets-init` | exit 0 | `secrets` | — | генерирует | 0.1 CPU, 32M |
|
||||
|
||||
`container_name` нигде не задан, поэтому один compose-service масштабируется (`api-1`, `api-2`, … — имена назначает Compose).
|
||||
|
||||
**Общее состояние, а не локальное.** Реплики API ничего не хранят у себя: пользователи, чаты, сообщения, сессии и ключи идемпотентности — в PostgreSQL (источник истины), кэш проверки сессий — в одном общем Redis. Поэтому любой запрос пользователя может обслужить любая реплика без повторного входа, и sticky session не нужна (`balance roundrobin`; в `evidence/smoke.txt` одна сессия чередует две реплики).
|
||||
|
||||
**X-Instance-Id.** Хук Fastify `onRequest` ставит заголовок во все ответы API, включая ошибки и health. Значение — hostname контейнера, который Docker делает равным короткому id контейнера: оно стабильно на всё время жизни процесса и однозначно указывает на контейнер (`docker stop <X-Instance-Id>`). Ответы, созданные самим LB (502/503/504), этого заголовка не имеют, как разрешает контракт, но приходят в общем формате ошибки с `X-Request-Id`.
|
||||
|
||||
**Идемпотентность отправки сообщения** (`src/messages/messages.service.ts`, миграция `20261101000000_idempotency_keys`).
|
||||
- Таблица `idempotency_keys`: PK `(user_id, chat_id, key)` — область уникальности контракта (пользователь + путь чата + ключ; метод с ключом один — POST), `request_hash` = sha256 разобранного тела (порядок ключей JSON не влияет; `attachment_ids: []` равен отсутствию поля, как требует `contracts/README.md`, — вложений до lab4 нет, поэтому непустой список, `null` или не массив дают `400`), `message_id` → `messages` (CASCADE), `created_at`. CHECK формата ключа дублирует проверку API.
|
||||
- Ключ проверяется в контроллере: нет или не `[A-Za-z0-9._:-]{1,128}` → `400`. Аутентификация и членство в чате проверяются до ключа при каждом запросе, в том числе при повторе.
|
||||
- Одна транзакция: удалить этот ключ, если он старше `IDEMPOTENCY_TTL_SECONDS` (24 ч) → `INSERT` сообщения → `INSERT` ключа `ON CONFLICT DO NOTHING`. Если ключ уже занят, транзакция откатывается вместе с лишним сообщением, и ответ строится по сохранённой записи: то же тело → тот же `201` и то же Message, другое → `409`.
|
||||
- Параллельные повторы через разные реплики: второй `INSERT` того же PK ждёт фиксации первой транзакции в PostgreSQL, затем получает конфликт — сообщение создаётся ровно одно. Сообщение и ключ фиксируются атомарно: транзиентная ошибка (5xx) откатывает обе записи, и повтор выполняется заново.
|
||||
- Ключ обязателен только для сообщений; HAProxy сам повторяет запрос только при `conn-failure`, когда запрос до API не дошёл, поэтому прозрачных повторов POST без ключа нет.
|
||||
|
||||
**Logout согласованно на всех репликах** (`src/auth/auth.service.ts`). Сначала в общий Redis записывается tombstone `revoked` (60 с, дольше любой записи кэша), и только затем удаляется строка сессии. Если Redis для этой реплики недоступен, ответ `503 unavailable`, сессия не удаляется. Иначе другая реплика, у которой сессия лежит в кэше, принимала бы отозванный токен до 60 с (автотест «logout через реплику без связи с Redis…»). Остальное поведение кэша — как в lab2: read-through, `SET NX`, TTL ≤ 60 с, при ошибке Redis — обход кэша через PostgreSQL и `FLUSHDB` перед повторным использованием.
|
||||
|
||||
**Проверки готовности, таймауты и остановка** (согласованы между собой):
|
||||
|
||||
| Параметр | Значение | Где |
|
||||
| --- | --- | --- |
|
||||
| Период проверки backend | `inter 1s`, `timeout check 1s` | `infra/haproxy/haproxy.cfg` |
|
||||
| Исключение / возврат backend | `fall 2` / `rise 2` | там же |
|
||||
| **Макс. время обнаружения отказа** | внезапный отказ (процесс убит, readiness не отвечает): ≤ 2 × 1 s + 1 s = **3 s**; штатная остановка: readiness 503 сразу → исключение ≤ 2 s | там же |
|
||||
| Повтор запроса LB | `retries 2`, `option redispatch`, `retry-on conn-failure` — только если соединение не установлено | там же |
|
||||
| Таймауты LB | connect 1 s, server 10 s, client 30 s, http-request 10 s, queue 5 s | там же |
|
||||
| Обновление адресов | Docker DNS `127.0.0.11`, `hold valid/obsolete 5s`, `server-template api 1-4` | там же |
|
||||
| Остановка API (SIGTERM) | readiness → 503 сразу, через `SHUTDOWN_DELAY_MS=3000` закрытие сервера с ожиданием текущих запросов, `exit 0` | `src/health/shutdown.ts` |
|
||||
| Grace period | `stop_grace_period: 10s`; `stop-one.sh` — `docker stop -t 8` | `compose.yaml`, `scripts/stop-one.sh` |
|
||||
| БД | `pool_timeout=5`, `connect_timeout=5`, `socket_timeout=10`, `statement_timeout=5000 ms`, `connection_limit=10` на реплику | строка подключения в `secrets/api/database_url` |
|
||||
| Redis | `commandTimeout 200 ms`, `connectTimeout 1 s`, без offline-очереди | `src/cache/cache.service.ts` |
|
||||
| Docker HEALTHCHECK | `/health/ready` каждые 5 s (для `--wait` и rolling update) | `Dockerfile` |
|
||||
|
||||
Задержка закрытия 3 s больше времени исключения при штатной остановке (≤ 2 s), поэтому к моменту закрытия LB уже не отправляет на реплику новые запросы, а начатые завершаются.
|
||||
|
||||
**Критичные зависимости readiness.** `/health/ready` проверяет только PostgreSQL (`SELECT 1`) и состояние остановки процесса: без БД обязательный путь невозможен. Redis не критичен — при его недоступности вход, проверка токена и бизнес-запросы идут через PostgreSQL, недоступен только logout (`503`, см. выше). `/health/live` проверяет только жизнь процесса.
|
||||
|
||||
**Миграции.** Отдельный one-shot сервис `migrate` выполняет `prisma migrate deploy` до запуска API (`depends_on: service_completed_successfully`); реплики API миграции не запускают, гонки нет. Повторный запуск безопасен: применённые миграции записаны в `_prisma_migrations`, Prisma берёт advisory lock на время применения. Миграция lab3 только добавляет таблицу (expand), поэтому совместима с работающей предыдущей версией API; rolling update выполняет миграцию один раз перед заменой реплик. Ограничение: несовместимые изменения схемы (удаление или переименование колонок) потребовали бы двух релизов expand → contract; в этой работе их нет.
|
||||
|
||||
**Rolling update** (`scripts/experiment.py rolling`): `docker compose run migrate` → для каждой старой реплики `docker compose up -d --no-deps --no-recreate --scale api=3 --wait api` (новая реплика с новым образом, ждём healthy) → `docker stop` (graceful) и `docker rm` старой. Compose не делает rolling update сам (`deploy.update_config` — только Swarm), поэтому замена выполняется поочерёдно этой процедурой.
|
||||
|
||||
**Перенесено из lab2:** весь API, Prisma/PostgreSQL, сессии с Redis-кэшем, Argon2id, Dockerfile, `secrets-init`, `migrate`, тесты, Swagger. **Изменено:** `X-Instance-Id`; `member_ids` приводятся к нижнему регистру до проверки дублей (один UUID в разных регистрах — `400`, а не ошибка вставки); повторённые `limit`/`cursor` — `400`; обязательный `Idempotency-Key` и таблица ключей; graceful shutdown и readiness 503 при остановке; logout сначала пишет tombstone; HEALTHCHECK образа — `/health/ready`; compose: LB, реплики без портов, лимиты, раздельные секреты; `restart.sh` перезапускает и LB; новые `stop-one.sh`, `experiment.py`.
|
||||
|
||||
**Соответствие `.env.example`:**
|
||||
|
||||
| Переменная | Где используется |
|
||||
| --- | --- |
|
||||
| `APP_HOST`, `APP_PORT` | API слушает `0.0.0.0:8080` внутри сети; `APP_PORT` в `.env` — опубликованный порт LB на `127.0.0.1` |
|
||||
| `APP_ENV` | передаётся в API, поведение не меняет |
|
||||
| `SESSION_TTL_SECONDS` | TTL сессии, по умолчанию 3600 |
|
||||
| `DATABASE_URL_FILE` | `/run/secrets/database_url` (подкаталог `api` или `migrate` тома `secrets`); в тестах — `DATABASE_URL` |
|
||||
| `SESSION_STORE=postgres` | фиксировано: источник истины сессий — PostgreSQL |
|
||||
| `CACHE_URL_FILE` | `/run/secrets/cache_url`; в тестах — `CACHE_URL` |
|
||||
| `API_REPLICAS` | `deploy.replicas` сервиса `api`, по умолчанию 2 |
|
||||
| `IDEMPOTENCY_TTL_SECONDS` | срок хранения ключа, по умолчанию 86400 |
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
Файлы собраны `docker compose run --rm tools sh scripts/collect-evidence.sh`; в заголовке каждого `.txt` — дата и commit, в `.json` — дата.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Публичный smoke | `make test` через LB | `PASS: lab3 public API scenario` | [evidence/smoke.txt](evidence/smoke.txt) |
|
||||
| Структура контракта | `make check` | `PASS: offline skeleton structure` | [evidence/smoke.txt](evidence/smoke.txt) |
|
||||
| **3**: стенд одной командой; ≥2 реплики, одна точка входа, общие БД и хранилище сессий | `docker compose up -d --build --wait` | `api-N` ×2 без портов, `lb` — `127.0.0.1:8080`, один `postgres`, один `redis` | [evidence/container.txt](evidence/container.txt) |
|
||||
| **3**: разные запросы одного пользователя — разные реплики без повторного входа | `probe.py instances 6` | одна сессия, `X-Instance-Id` чередуется между двумя id контейнеров | [evidence/smoke.txt](evidence/smoke.txt) |
|
||||
| **3**: остановка любой реплики, чтение/запись продолжаются ≤ 10 s | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` дважды, вторая реплика после восстановления первой | оба PASS; 0 ошибок, запись через 3,51–3,67 s от старта hook; остановлены разные контейнеры (`Exited (0)`); HAProxy: `is DOWN … code: 503` | [evidence/failover.txt](evidence/failover.txt) |
|
||||
| **3**: повтор POST с тем же ключом без дубля, в т. ч. конкурентно и через другую реплику | smoke; тесты `idempotency.e2e-spec.ts`; `experiment.py idempotency` | 20 параллельных запросов через LB → все `201`, один id, обслужены обеими репликами, в истории одно сообщение; другое тело → `409` | [evidence/idempotency.json](evidence/idempotency.json), [evidence/tests.txt](evidence/tests.txt) |
|
||||
| **3**: persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS; `started=` сменился у postgres, redis, обеих api, lb | [evidence/persistence.txt](evidence/persistence.txt) |
|
||||
| **3**: миграции отдельно, без гонки реплик | сервис `migrate`, повторный запуск | `No pending migrations to apply`; `migrate diff` — `No difference detected`; 3 миграции | [evidence/container.txt](evidence/container.txt) |
|
||||
| **4**: health/readiness, таймауты, прекращение приёма по SIGTERM; LB исключает недоступный backend; период и время обнаружения | таблица выше; `docker stop` и `docker kill` реплик; живая реплика без доступа к PostgreSQL (`pg_hba reject` только для её IP) | при SIGTERM реплика исключается до закрытия: 0 ошибок, `Exited (0)`; при SIGKILL — 0–3 ошибки и пауза записи ≤ 0,99 s; реплика без БД (`live 200`, `ready 503`) исключена (`is DOWN … 503`), 0 из 10 бизнес-запросов, после возврата доступа снова в ротации; все реплики остановлены → LB `503` в формате контракта | [evidence/failover-stop.json](evidence/failover-stop.json), [evidence/failover-kill.json](evidence/failover-kill.json), [evidence/failures.txt](evidence/failures.txt) §4–5 |
|
||||
| **4**: последовательная остановка каждой реплики с восстановлением; RPS, ошибки, время восстановления | `experiment.py failover` и `failover --kill` | см. «Эксперименты»; потерь и дублей подтверждённых сообщений 0 | [evidence/failover-stop.json](evidence/failover-stop.json), [evidence/failover-kill.json](evidence/failover-kill.json) |
|
||||
| **4**: параллельные запросы с одним ключом | `experiment.py idempotency`; тест «20 параллельных запросов… через два экземпляра» | одно сообщение | [evidence/idempotency.json](evidence/idempotency.json), [evidence/tests.txt](evidence/tests.txt) |
|
||||
| **4**: CPU/RAM-лимиты; API без портов в обход LB; секреты общие только где нужно; нет `container_name` | `docker inspect`, `docker compose ps`, `ls /run/secrets` в каждом сервисе | лимиты у всех контейнеров; порт только у `lb`; postgres видит только `pg_password`, redis — `redis_password`, api — `database_url` и `cache_url`, lb — ничего; `container_name` — 0 | [evidence/container.txt](evidence/container.txt) |
|
||||
| **4**: rolling update под нагрузкой | `experiment.py rolling` после `docker compose build api` | реплики заменены на новый образ по одной; 0 ошибок, пауза записи ≤ 0,16 s; 0 потерь и дублей; после замены и при `--scale` 2→3→4→2 LB обслуживает все реплики через 0–1 s (Docker DNS) | [evidence/rolling.json](evidence/rolling.json) |
|
||||
| **4**: миграции однократно и совместимы | см. «Миграции» | expand-only миграция, применяется до замены реплик | [evidence/rolling.json](evidence/rolling.json), [evidence/container.txt](evidence/container.txt) |
|
||||
| lab2: logout, expiry, отказы Redis/БД | `probe.py logout`, `probe.py expiry 2`, остановка redis/postgres | без Redis: вход и `/me` работают, logout `503`, токен действует; с Redis: `204` → `401`; без БД: `503` без деталей, аноним `401`; TTL 2 s: `200` → `401` | [evidence/failures.txt](evidence/failures.txt) |
|
||||
| Собственные тесты | `docker compose -f compose.test.yaml run --rm --build tests` | `Tests: 80 passed, 80 total` | [evidence/tests.txt](evidence/tests.txt) |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Какие процессы реально остановлены, видно не по заголовку, а по `docker inspect`: в `failover.txt` до/после каждого прогона указаны имя, id и `exit`/`finished` контейнера, а в журнале HAProxy — исключение соответствующего backend.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
**Методика.** `scripts/experiment.py` (stdlib, HTTP-клиент из `tests/client.py`) в контейнере `tools` создаёт пользователей и чат и запускает 4 потока closed-loop `POST` сообщений через LB (таймаут клиента 2 s). Неудачный запрос повторяется **с тем же `Idempotency-Key`** до успеха. Окна: 5 s до воздействия, 10 s после команды остановки плюс время самой команды, 5 s после восстановления. «Пауза записи» — максимальный интервал между соседними успешными ответами в окне; это и есть время восстановления записи для клиента. В конце вся история чата читается постранично и сверяется с подтверждёнными ответами. Для каждого окна считаются успешные RPS, ошибки и их доля, p50/p95/p99 задержки **успешных** запросов; после прогрева снимается `docker stats` (CPU/RAM). Стенд: лимиты из таблицы выше (API 0.5 CPU на реплику), Docker Desktop WSL2, 12 vCPU, 8 GiB. Объём данных: в таблице `messages` 93 579 строк перед первым экспериментом, 112 337 после последнего. Один прогон каждого сценария.
|
||||
|
||||
**Ресурсы под нагрузкой** (4 потока, обе реплики, `docker stats` после прогрева): каждая api 41–50 % CPU (лимит 0.5 CPU, то есть у предела) и 93–131 MiB из 256 MiB; postgres 26–27 % CPU, 70–85 MiB; lb 14–15 % CPU, 13–16 MiB; redis 2 % CPU, 10 MiB. Узкое место этого профиля — CPU реплик API.
|
||||
|
||||
| Сценарий, окно | Успешных RPS | Ошибки (доля) | p50 / p95 / p99, ms: до → отказ | Макс. пауза записи |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `docker stop` api-11: до / отказ / после возврата | 150 / 117 / 141 | 0 / 0 / 0 | 11,4/80,2/164 → 12,0/89,6/107 | 0,18 s |
|
||||
| `docker stop` api-12: до / отказ / после возврата | 140 / 100 / 148 | 0 / 0 / 0 | 12,7/81,5/96,2 → 15,2/95,8/105 | 0,18 s |
|
||||
| `docker kill` api-11: до / отказ / после | 149 / 70 / 149 | 0 / 3 (0,41 %) / 0 | 11,4/80,5/171 → 12,7/100/1014 | 0,99 s |
|
||||
| `docker kill` api-12: до / отказ / после | 149 / 92 / 152 | 0 / 0 / 0 | 11,1/82,7/140 → 11,6/93,7/185 | 0,99 s |
|
||||
| Rolling update, всё время замены (31,0 s) | 156 | 0 | 12,3 / 78,8 / 105 | 0,16 s |
|
||||
|
||||
Окно «отказ» начинается с команды остановки и длится 10 s после её завершения, поэтому при `docker stop` в него входят ~3,4 s штатного дренажа, когда реплика ещё обслуживает начатые запросы.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| `docker stop` api-11, затем (после возврата) api-12 | реплика исключается до закрытия, ошибок нет | ошибок 0 / 0; остановленная реплика дообслуживала начатые запросы 1,7–2,0 s, команда `docker stop` — 3,5 s, контейнер `Exited (0)` | пауза записи ≤ 0,18 s; вернувшаяся реплика снова получает запросы через 3,5 s после `docker start`; потерь и дублей 0 из 6945 |
|
||||
| `docker kill` (SIGKILL) каждой реплики по очереди | обрыв начатых запросов, обнаружение ≤ 3 s, повтор с ключом без дубля | ошибок 3 / 0; p99 в окне до ~1 s (повторы после обрыва) | пауза записи 0,99 / 0,99 s; потерь и дублей 0 из 5749 |
|
||||
| Rolling update двух реплик на новый образ | замена без ошибок | ошибок 0; в ответах 4 разных реплики (2 старых, 2 новых); новая реплика готова за 6,6–6,8 s, шаг ~10,3 s | пауза записи ≤ 0,16 s; потерь и дублей 0 из 6064 |
|
||||
| 20 параллельных `POST` с одним ключом | одно сообщение | все `201`, 1 id, обслужены 2 репликами | 1 сообщение в истории |
|
||||
| Одна живая реплика без доступа к PostgreSQL (`pg_hba reject` для её IP) | LB исключает её по readiness | `live 200`, `ready 503`; HAProxy `is DOWN … 503`; 10 из 10 запросов обслужила вторая реплика | после возврата доступа `ready 200`, реплика снова в ротации без перезапуска |
|
||||
| `make test-failover` ×2 (разные реплики) | ≤ 10 s, без дублей | 0 ошибок, первая успешная запись после hook через 3,51–3,67 s | PASS |
|
||||
| `restart.sh`: рестарт postgres, redis, api ×2, lb | данные и токен сохраняются | PASS | потерь нет |
|
||||
| `docker compose stop redis` | вход и Bearer через PostgreSQL; logout не может отозвать токен на всех репликах | `/me` `200`, logout `503`, токен действует | после `start` logout `204` → `401` |
|
||||
| `docker compose stop postgres` | `503` без деталей | `/chats` с токеном `503 database unavailable`; аноним `401` | готов после `start` |
|
||||
| `docker compose stop api` (все реплики) | LB отвечает сам | `503 no API replica available` в формате контракта | после `start` готов |
|
||||
|
||||
Почему падает RPS при одной реплике: каждая реплика ограничена 0.5 CPU и под этой нагрузкой работает у предела, поэтому с одной репликой успешных записей меньше (−22…−29 % в окне штатной остановки, куда входит ещё и дренаж). При SIGKILL падение сильнее: начатые запросы оборваны, клиент ждёт ответа до разрыва, повторяет с тем же ключом (отсюда p99 ~1 s), а до исключения HAProxy (≤ 3 s) новые соединения к убитому контейнеру сразу получают отказ и перенаправляются на живую реплику (`retry-on conn-failure`). Повторы не дали дублей.
|
||||
|
||||
Ограничения измерения: closed-loop генератор (coordinated omission), клиент на том же хосте, один прогон каждого сценария, ноутбук — абсолютные RPS не переносятся на другое железо. Образ в rolling update собран из того же commit; id образа отличается, потому что сборка не побайтно воспроизводима. Замена процедуры при этом та же, что и для нового кода.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- **Отказ процесса, а не узла.** Все контейнеры на одном хосте Docker: отказ хоста останавливает весь стенд. LB, PostgreSQL и Redis — по одному экземпляру (SPOF); выдерживается отказ одной реплики API. Отказ узла и перенос — трек 5.2, не заявлен.
|
||||
- **Redis как зависимость logout.** Пока реплика не может записать tombstone в Redis, logout через неё отвечает `503`: согласованность отзыва выбрана вместо доступности logout. Вход, проверка токена и бизнес-запросы без Redis работают.
|
||||
- **Очистка ключей идемпотентности.** Просроченный ключ удаляется при повторном использовании, фоновой очистки нет — таблица растёт, на корректность не влияет. Аналогично для истёкших сессий.
|
||||
- **`FLUSHDB` при переподключении** одной реплики очищает общий кэш для всех: безопасно (кэш прогревается из PostgreSQL), но кратко увеличивает число SQL-запросов.
|
||||
- **Compose не делает rolling update сам**: поочерёдная замена выполняется скриптом; при `docker compose up -d` с изменённой конфигурацией Compose пересоздаёт реплики без этой процедуры.
|
||||
- **Несовместимые миграции** (expand → contract в два релиза) в этой работе не понадобились и не проверялись.
|
||||
- HTTP без TLS — допустимо только для локального стенда с синтетическими данными (TLS — lab7). `X-Instance-Id` раскрывает короткий id контейнера; в lab7 по контракту нужен непрозрачный alias.
|
||||
- Подтверждено измерением: продолжение записи без потерь и дублей при штатной и аварийной остановке каждой реплики и при rolling update. Гипотеза, не измерена: насыщение БД/LB/пула при росте числа реплик (трек 5.1).
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
name: messenger-lab3-test
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17.2-alpine
|
||||
environment:
|
||||
POSTGRES_USER: test
|
||||
POSTGRES_PASSWORD: test
|
||||
POSTGRES_DB: messenger_test
|
||||
tmpfs:
|
||||
- /var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD", "pg_isready", "-U", "test", "-d", "messenger_test"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 15
|
||||
|
||||
redis:
|
||||
image: redis:7.4.1-alpine
|
||||
command: ["redis-server", "--save", "", "--appendonly", "no"]
|
||||
|
||||
tests:
|
||||
build:
|
||||
context: .
|
||||
target: test
|
||||
image: mtusi-messenger-lab3-test:dev
|
||||
environment:
|
||||
DATABASE_URL: postgresql://test:test@postgres:5432/messenger_test?connection_limit=20
|
||||
CACHE_URL: redis://redis:6379/0
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_started
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
name: messenger-lab3
|
||||
|
||||
services:
|
||||
secrets-init:
|
||||
image: alpine:3.20.3
|
||||
volumes:
|
||||
- secrets:/secrets
|
||||
command:
|
||||
- sh
|
||||
- -ec
|
||||
- |
|
||||
cd /secrets
|
||||
mkdir -p postgres redis api migrate
|
||||
for name in pg_password:postgres redis_password:redis; do
|
||||
file=$${name%%:*}; dir=$${name##*:}
|
||||
[ ! -s "$$file" ] || mv "$$file" "$$dir/$$file"
|
||||
[ -s "$$dir/$$file" ] || head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > "$$dir/$$file"
|
||||
done
|
||||
rm -f database_url cache_url
|
||||
printf 'postgresql://messenger:%s@postgres:5432/messenger?connection_limit=10&pool_timeout=5&connect_timeout=5&socket_timeout=10&application_name=api&options=-c%%20statement_timeout%%3D5000' "$$(cat postgres/pg_password)" > api/database_url
|
||||
printf 'redis://:%s@redis:6379/0' "$$(cat redis/redis_password)" > api/cache_url
|
||||
printf 'postgresql://messenger:%s@postgres:5432/messenger' "$$(cat postgres/pg_password)" > migrate/database_url
|
||||
chmod 0444 postgres/* redis/* api/* migrate/*
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.1", memory: 32M }
|
||||
|
||||
postgres:
|
||||
image: postgres:17.2-alpine
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/pg_password
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: postgres } }
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "1.0", memory: 512M }
|
||||
healthcheck:
|
||||
test: ["CMD", "pg_isready", "-U", "messenger", "-d", "messenger"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
depends_on:
|
||||
secrets-init:
|
||||
condition: service_completed_successfully
|
||||
restart: unless-stopped
|
||||
|
||||
redis:
|
||||
image: redis:7.4.1-alpine
|
||||
user: redis
|
||||
command:
|
||||
- sh
|
||||
- -c
|
||||
- exec redis-server --save '' --appendonly no --maxmemory 64mb --maxmemory-policy allkeys-lru --requirepass "$$(cat /run/secrets/redis_password)"
|
||||
volumes:
|
||||
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: redis } }
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.25", memory: 128M }
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "redis-cli --no-auth-warning -a \"$$(cat /run/secrets/redis_password)\" ping | grep -q PONG"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
depends_on:
|
||||
secrets-init:
|
||||
condition: service_completed_successfully
|
||||
restart: unless-stopped
|
||||
|
||||
migrate:
|
||||
build:
|
||||
context: .
|
||||
target: migrate
|
||||
image: mtusi-messenger-lab3-migrate:dev
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
volumes:
|
||||
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: migrate } }
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.5", memory: 512M }
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
target: runtime
|
||||
image: mtusi-messenger-lab3-api:dev
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 8080
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
SHUTDOWN_DELAY_MS: 3000
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
volumes:
|
||||
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: api } }
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits: { cpus: "0.5", memory: 256M }
|
||||
stop_grace_period: 10s
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_started
|
||||
restart: unless-stopped
|
||||
|
||||
lb:
|
||||
image: haproxy:3.0.6-alpine
|
||||
ports:
|
||||
- "127.0.0.1:${APP_PORT:-8080}:8080"
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.25", memory: 64M }
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
tools:
|
||||
profiles: [tools]
|
||||
build:
|
||||
dockerfile_inline: |
|
||||
FROM docker:27.3.1-cli
|
||||
RUN apk add --no-cache python3 make git && git config --global --add safe.directory /work
|
||||
WORKDIR /work
|
||||
image: mtusi-messenger-lab3-tools:dev
|
||||
environment:
|
||||
BASE_URL: http://lb:8080
|
||||
volumes:
|
||||
- .:/work
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "1.0", memory: 256M }
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
secrets:
|
||||
@@ -0,0 +1,82 @@
|
||||
# Стенд: сервисы, порты, лимиты, секреты, миграции
|
||||
# date: 2026-11-01T14:53:14Z
|
||||
# commit: 252ebd0
|
||||
|
||||
$ docker compose ps -a --format table {{.Service}}\t{{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}
|
||||
SERVICE NAME IMAGE STATUS PORTS
|
||||
api messenger-lab3-api-11 sha256:be7b642a4d66d1cd16c6e249edd4c8d3ce687b18ede4343ace709bdfd1ffd1bb Up 24 minutes (healthy) 8080/tcp
|
||||
api messenger-lab3-api-12 sha256:be7b642a4d66d1cd16c6e249edd4c8d3ce687b18ede4343ace709bdfd1ffd1bb Up 24 minutes (healthy) 8080/tcp
|
||||
lb messenger-lab3-lb-1 haproxy:3.0.6-alpine Up 28 minutes 127.0.0.1:8080->8080/tcp
|
||||
migrate messenger-lab3-migrate-1 sha256:fd6f6ebce3f423be91d91b792682f0810ee2b6c332003270e1106ac056b6e947 Exited (0) 25 minutes ago
|
||||
postgres messenger-lab3-postgres-1 postgres:17.2-alpine Up 25 minutes (healthy) 5432/tcp
|
||||
redis messenger-lab3-redis-1 redis:7.4.1-alpine Up 25 minutes (healthy) 6379/tcp
|
||||
secrets-init messenger-lab3-secrets-init-1 alpine:3.20.3 Exited (0) 25 minutes ago
|
||||
tools messenger-lab3-tools-run-d672896c194d mtusi-messenger-lab3-tools:dev Up 2 seconds
|
||||
|
||||
## CPU/RAM-лимиты (NanoCpus: 1e9 = 1 CPU; Memory в байтах)
|
||||
$ sh -c docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}}' $(docker compose ps -q)
|
||||
/messenger-lab3-api-11 cpus=500000000 memory=268435456
|
||||
/messenger-lab3-api-12 cpus=500000000 memory=268435456
|
||||
/messenger-lab3-lb-1 cpus=250000000 memory=67108864
|
||||
/messenger-lab3-postgres-1 cpus=1000000000 memory=536870912
|
||||
/messenger-lab3-redis-1 cpus=250000000 memory=134217728
|
||||
|
||||
## container_name не задан (одно имя сервиса масштабируется)
|
||||
$ sh -c docker compose config | grep -c container_name || true
|
||||
0
|
||||
|
||||
## Секреты: каждый сервис видит только свои файлы
|
||||
$ docker compose exec -T postgres ls /run/secrets
|
||||
pg_password
|
||||
|
||||
$ docker compose exec -T redis ls /run/secrets
|
||||
redis_password
|
||||
|
||||
$ docker compose exec -T api ls /run/secrets
|
||||
cache_url
|
||||
database_url
|
||||
|
||||
$ docker compose exec -T lb sh -c ls /run/secrets 2>/dev/null || echo "no /run/secrets"
|
||||
no /run/secrets
|
||||
|
||||
$ docker compose exec -T lb haproxy -v
|
||||
HAProxy version 3.0.6-c2c0090 2024/11/07 - https://haproxy.org/
|
||||
Status: long-term supported branch - will stop receiving fixes around Q2 2029.
|
||||
Known bugs: http://www.haproxy.org/bugs/bugs-3.0.6.html
|
||||
Running on: Linux 5.15.153.1-microsoft-standard-WSL2 #1 SMP Fri Mar 29 23:14:13 UTC 2024 x86_64
|
||||
|
||||
$ docker compose exec -T postgres postgres --version
|
||||
postgres (PostgreSQL) 17.2
|
||||
|
||||
$ docker compose exec -T redis redis-server --version
|
||||
Redis server v=7.4.1 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=a93ce81042b3a6d7
|
||||
|
||||
## Миграции: отдельный one-shot сервис, повторный запуск ничего не применяет
|
||||
$ docker compose run --rm migrate
|
||||
Container messenger-lab3-secrets-init-1 Created
|
||||
Container messenger-lab3-postgres-1 Running
|
||||
Container messenger-lab3-secrets-init-1 Starting
|
||||
Container messenger-lab3-secrets-init-1 Started
|
||||
Container messenger-lab3-secrets-init-1 Waiting
|
||||
Container messenger-lab3-secrets-init-1 Exited
|
||||
Prisma schema loaded from prisma/schema.prisma
|
||||
Datasource "db": PostgreSQL database "messenger", schema "public" at "postgres:5432"
|
||||
|
||||
3 migrations found in prisma/migrations
|
||||
|
||||
|
||||
No pending migrations to apply.
|
||||
|
||||
$ docker compose run --rm --no-deps migrate sh -c export DATABASE_URL="$(cat "$DATABASE_URL_FILE")"; npx prisma migrate diff --from-url "$DATABASE_URL" --to-schema-datamodel prisma/schema.prisma --exit-code
|
||||
No difference detected.
|
||||
|
||||
|
||||
$ docker compose exec -T postgres psql -U messenger -d messenger -c SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY started_at
|
||||
migration_name | finished_at
|
||||
---------------------------------+-------------------------------
|
||||
20261021000000_init | 2026-11-01 10:26:06.913822+00
|
||||
20261021010000_auth_sessions | 2026-11-01 10:26:06.924458+00
|
||||
20261101000000_idempotency_keys | 2026-11-01 11:03:29.670935+00
|
||||
(3 rows)
|
||||
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
{
|
||||
"scenario": "sequential failover of each api replica",
|
||||
"resources_under_load": [
|
||||
"messenger-lab3-api-11 cpu=41.10% mem=97.37MiB / 256MiB",
|
||||
"messenger-lab3-api-12 cpu=48.76% mem=113.1MiB / 256MiB",
|
||||
"messenger-lab3-lb-1 cpu=13.94% mem=14.84MiB / 64MiB",
|
||||
"messenger-lab3-postgres-1 cpu=25.65% mem=78.69MiB / 512MiB",
|
||||
"messenger-lab3-redis-1 cpu=2.24% mem=9.797MiB / 128MiB"
|
||||
],
|
||||
"replicas": [
|
||||
{
|
||||
"container": "/messenger-lab3-api-11 running image=be7b642a4d66",
|
||||
"action": "docker kill (SIGKILL)",
|
||||
"before": {
|
||||
"seconds": 5.0,
|
||||
"successful_writes": 746,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 149.2,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.4,
|
||||
"p95": 80.5,
|
||||
"p99": 170.9
|
||||
},
|
||||
"max_write_gap_seconds": 0.15,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"e0c31d893858"
|
||||
]
|
||||
},
|
||||
"stop_command_seconds": 0.522,
|
||||
"target_last_success_after_stop_seconds": null,
|
||||
"outage_window": {
|
||||
"seconds": 10.522,
|
||||
"successful_writes": 732,
|
||||
"failed_attempts": 3,
|
||||
"error_ratio": 0.0041,
|
||||
"successful_rps": 69.6,
|
||||
"latency_ms_successful": {
|
||||
"p50": 12.7,
|
||||
"p95": 100.2,
|
||||
"p99": 1013.9
|
||||
},
|
||||
"max_write_gap_seconds": 0.985,
|
||||
"instances": [
|
||||
"229dcf033bdc"
|
||||
]
|
||||
},
|
||||
"restore_until_healthy_seconds": 5.97,
|
||||
"restore_until_serving_seconds": 2.451,
|
||||
"after_restore": {
|
||||
"seconds": 5.024,
|
||||
"successful_writes": 749,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 149.1,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.1,
|
||||
"p95": 82.7,
|
||||
"p99": 140.0
|
||||
},
|
||||
"max_write_gap_seconds": 0.091,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"e0c31d893858"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"container": "/messenger-lab3-api-12 running image=be7b642a4d66",
|
||||
"action": "docker kill (SIGKILL)",
|
||||
"before": {
|
||||
"seconds": 5.0,
|
||||
"successful_writes": 744,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 148.8,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.1,
|
||||
"p95": 82.7,
|
||||
"p99": 140.0
|
||||
},
|
||||
"max_write_gap_seconds": 0.091,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"e0c31d893858"
|
||||
]
|
||||
},
|
||||
"stop_command_seconds": 0.515,
|
||||
"target_last_success_after_stop_seconds": null,
|
||||
"outage_window": {
|
||||
"seconds": 10.515,
|
||||
"successful_writes": 966,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 91.9,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.6,
|
||||
"p95": 93.7,
|
||||
"p99": 184.9
|
||||
},
|
||||
"max_write_gap_seconds": 0.992,
|
||||
"instances": [
|
||||
"e0c31d893858"
|
||||
]
|
||||
},
|
||||
"restore_until_healthy_seconds": 5.676,
|
||||
"restore_until_serving_seconds": 3.757,
|
||||
"after_restore": {
|
||||
"seconds": 5.024,
|
||||
"successful_writes": 765,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 152.3,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.8,
|
||||
"p95": 78.2,
|
||||
"p99": 92.4
|
||||
},
|
||||
"max_write_gap_seconds": 0.152,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"e0c31d893858"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"dataset": {
|
||||
"messages_in_db_before": 100524,
|
||||
"messages_in_db_after": 106273
|
||||
},
|
||||
"history": {
|
||||
"confirmed": 5749,
|
||||
"stored": 5749,
|
||||
"lost_confirmed": 0,
|
||||
"duplicates": 0
|
||||
},
|
||||
"load": {
|
||||
"workers": 4,
|
||||
"model": "closed loop, POST message",
|
||||
"warmup_seconds": 5,
|
||||
"client_timeout_seconds": 2,
|
||||
"retry": "same Idempotency-Key until success"
|
||||
},
|
||||
"date": "2026-11-01T14:56:32Z"
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
{
|
||||
"scenario": "sequential failover of each api replica",
|
||||
"resources_under_load": [
|
||||
"messenger-lab3-api-11 cpu=49.93% mem=130.7MiB / 256MiB",
|
||||
"messenger-lab3-api-12 cpu=49.39% mem=92.76MiB / 256MiB",
|
||||
"messenger-lab3-lb-1 cpu=14.25% mem=12.9MiB / 64MiB",
|
||||
"messenger-lab3-postgres-1 cpu=26.61% mem=70.14MiB / 512MiB",
|
||||
"messenger-lab3-redis-1 cpu=2.03% mem=9.797MiB / 128MiB"
|
||||
],
|
||||
"replicas": [
|
||||
{
|
||||
"container": "/messenger-lab3-api-11 running image=be7b642a4d66",
|
||||
"action": "docker stop (SIGTERM, graceful)",
|
||||
"before": {
|
||||
"seconds": 5.0,
|
||||
"successful_writes": 751,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 150.2,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.4,
|
||||
"p95": 80.2,
|
||||
"p99": 163.6
|
||||
},
|
||||
"max_write_gap_seconds": 0.085,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"e0c31d893858"
|
||||
]
|
||||
},
|
||||
"stop_command_seconds": 3.515,
|
||||
"target_last_success_after_stop_seconds": 1.954,
|
||||
"outage_window": {
|
||||
"seconds": 13.515,
|
||||
"successful_writes": 1585,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 117.3,
|
||||
"latency_ms_successful": {
|
||||
"p50": 12.0,
|
||||
"p95": 89.6,
|
||||
"p99": 106.6
|
||||
},
|
||||
"max_write_gap_seconds": 0.183,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"e0c31d893858"
|
||||
]
|
||||
},
|
||||
"restore_until_healthy_seconds": 5.743,
|
||||
"restore_until_serving_seconds": 3.546,
|
||||
"after_restore": {
|
||||
"seconds": 5.031,
|
||||
"successful_writes": 709,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 140.9,
|
||||
"latency_ms_successful": {
|
||||
"p50": 12.7,
|
||||
"p95": 81.5,
|
||||
"p99": 96.2
|
||||
},
|
||||
"max_write_gap_seconds": 0.074,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"e0c31d893858"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"container": "/messenger-lab3-api-12 running image=be7b642a4d66",
|
||||
"action": "docker stop (SIGTERM, graceful)",
|
||||
"before": {
|
||||
"seconds": 5.0,
|
||||
"successful_writes": 702,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 140.4,
|
||||
"latency_ms_successful": {
|
||||
"p50": 12.7,
|
||||
"p95": 81.5,
|
||||
"p99": 96.2
|
||||
},
|
||||
"max_write_gap_seconds": 0.074,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"e0c31d893858"
|
||||
]
|
||||
},
|
||||
"stop_command_seconds": 3.513,
|
||||
"target_last_success_after_stop_seconds": 1.676,
|
||||
"outage_window": {
|
||||
"seconds": 13.513,
|
||||
"successful_writes": 1348,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 99.8,
|
||||
"latency_ms_successful": {
|
||||
"p50": 15.2,
|
||||
"p95": 95.8,
|
||||
"p99": 105.3
|
||||
},
|
||||
"max_write_gap_seconds": 0.18,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"e0c31d893858"
|
||||
]
|
||||
},
|
||||
"restore_until_healthy_seconds": 5.745,
|
||||
"restore_until_serving_seconds": 3.471,
|
||||
"after_restore": {
|
||||
"seconds": 5.022,
|
||||
"successful_writes": 742,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 147.7,
|
||||
"latency_ms_successful": {
|
||||
"p50": 11.9,
|
||||
"p95": 77.6,
|
||||
"p99": 151.5
|
||||
},
|
||||
"max_write_gap_seconds": 0.141,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"e0c31d893858"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"dataset": {
|
||||
"messages_in_db_before": 93579,
|
||||
"messages_in_db_after": 100524
|
||||
},
|
||||
"history": {
|
||||
"confirmed": 6945,
|
||||
"stored": 6945,
|
||||
"lost_confirmed": 0,
|
||||
"duplicates": 0
|
||||
},
|
||||
"load": {
|
||||
"workers": 4,
|
||||
"model": "closed loop, POST message",
|
||||
"warmup_seconds": 5,
|
||||
"client_timeout_seconds": 2,
|
||||
"retry": "same Idempotency-Key until success"
|
||||
},
|
||||
"date": "2026-11-01T14:55:41Z"
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
# make test-failover: stop-one.sh останавливает реплику, обслужившую тест; затем вторую
|
||||
# date: 2026-11-01T14:54:02Z
|
||||
# commit: 252ebd0
|
||||
|
||||
## Прогон 1
|
||||
### до
|
||||
/messenger-lab3-api-11 id=e0c31d893858 running exit=0 finished=2026-11-01T14:53:57.668890771Z
|
||||
/messenger-lab3-api-12 id=229dcf033bdc running exit=0 finished=2026-11-01T14:53:57.66803913Z
|
||||
|
||||
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://lb:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 132, "failed_attempts": 0, "first_recovery_seconds": 3.509}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
### после: остановленная реплика Exited (0) — штатное завершение по SIGTERM
|
||||
/messenger-lab3-api-11 id=e0c31d893858 exited exit=0 finished=2026-11-01T14:54:05.746763923Z
|
||||
/messenger-lab3-api-12 id=229dcf033bdc running exit=0 finished=2026-11-01T14:53:57.66803913Z
|
||||
|
||||
### журнал HAProxy
|
||||
Server api/api2 is DOWN, reason: Layer7 wrong status, code: 503, info: "Service Unavailable", check duration: 2ms. 1 active and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
|
||||
Server api/api2 was DOWN and now enters maintenance (No IP for server ).
|
||||
|
||||
## Прогон 2
|
||||
### до
|
||||
/messenger-lab3-api-11 id=e0c31d893858 running exit=0 finished=2026-11-01T14:54:05.746763923Z
|
||||
/messenger-lab3-api-12 id=229dcf033bdc running exit=0 finished=2026-11-01T14:53:57.66803913Z
|
||||
|
||||
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://lb:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 131, "failed_attempts": 0, "first_recovery_seconds": 3.668}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
### после: остановленная реплика Exited (0) — штатное завершение по SIGTERM
|
||||
/messenger-lab3-api-11 id=e0c31d893858 running exit=0 finished=2026-11-01T14:54:05.746763923Z
|
||||
/messenger-lab3-api-12 id=229dcf033bdc exited exit=0 finished=2026-11-01T14:54:25.301405146Z
|
||||
|
||||
### журнал HAProxy
|
||||
Server api/api1 is DOWN, reason: Layer7 wrong status, code: 503, info: "Service Unavailable", check duration: 1ms. 1 active and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
|
||||
Server api/api1 was DOWN and now enters maintenance (No IP for server ).
|
||||
|
||||
## Проверка guard: stop-one.sh отказывается останавливать не api
|
||||
$ env TARGET_INSTANCE_ID=eb4e6be5ba1d sh scripts/stop-one.sh
|
||||
refusing to stop eb4e6be5ba1d: not an api replica of messenger-lab3 (messenger-lab3/postgres)
|
||||
EXIT CODE 1
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
# Отказы зависимостей, ошибки LB, expiry
|
||||
# date: 2026-11-01T14:57:16Z
|
||||
# commit: 252ebd0
|
||||
|
||||
## 1. Redis остановлен: вход и Bearer через PostgreSQL; logout — 503 без отзыва (токен остаётся действующим)
|
||||
$ docker compose stop redis
|
||||
Container messenger-lab3-redis-1 Stopping
|
||||
Container messenger-lab3-redis-1 Stopped
|
||||
|
||||
$ python3 scripts/probe.py logout
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T15:57:17.123Z
|
||||
GET /api/v1/users/me -> 200
|
||||
DELETE /api/v1/auth/sessions/current -> 503 {"error": {"code": "unavailable", "message": "session cache unavailable", "request_id": "98fedb58-4eb5-4e13-a7cb-e6469a78d258"}}
|
||||
GET /api/v1/users/me -> 200
|
||||
|
||||
$ docker compose start redis
|
||||
Container messenger-lab3-secrets-init-1 Starting
|
||||
Container messenger-lab3-secrets-init-1 Started
|
||||
Container messenger-lab3-secrets-init-1 Waiting
|
||||
Container messenger-lab3-secrets-init-1 Exited
|
||||
Container messenger-lab3-redis-1 Starting
|
||||
Container messenger-lab3-redis-1 Started
|
||||
|
||||
## 2. Redis снова доступен: logout отзывает токен на всех репликах
|
||||
$ python3 scripts/probe.py logout
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T15:57:21.659Z
|
||||
GET /api/v1/users/me -> 200
|
||||
DELETE /api/v1/auth/sessions/current -> 204
|
||||
GET /api/v1/users/me -> 401
|
||||
|
||||
## 3. PostgreSQL остановлен: live 200, запрос с токеном — 503 без внутренних деталей, аноним — 401
|
||||
$ docker compose stop postgres
|
||||
Container messenger-lab3-postgres-1 Stopping
|
||||
Container messenger-lab3-postgres-1 Stopped
|
||||
|
||||
$ python3 scripts/probe.py status GET /health/live
|
||||
GET /health/live (anonymous) -> 200 {"status": "ok"}
|
||||
|
||||
$ python3 scripts/probe.py status GET /api/v1/chats Bearer unknown-token
|
||||
GET /api/v1/chats (Bearer unknown-token) -> 503 {"error": {"code": "unavailable", "message": "database unavailable", "request_id": "0ff1f01f-8cd5-40f7-b590-02e64814442f"}}
|
||||
|
||||
$ python3 scripts/probe.py status GET /api/v1/users/me
|
||||
GET /api/v1/users/me (anonymous) -> 503 {"error": {"code": "unavailable", "message": "no API replica available", "request_id": "3bbc22fc-5459-4c57-af1f-d63e72844729"}}
|
||||
|
||||
$ docker compose start postgres
|
||||
Container messenger-lab3-secrets-init-1 Starting
|
||||
Container messenger-lab3-secrets-init-1 Started
|
||||
Container messenger-lab3-secrets-init-1 Waiting
|
||||
Container messenger-lab3-secrets-init-1 Exited
|
||||
Container messenger-lab3-postgres-1 Starting
|
||||
Container messenger-lab3-postgres-1 Started
|
||||
|
||||
$ python3 scripts/probe.py ready
|
||||
ready
|
||||
|
||||
## 4. Все реплики API остановлены: LB отвечает 503 в формате ошибки контракта
|
||||
$ docker compose stop api
|
||||
Container messenger-lab3-api-13 Stopping
|
||||
Container messenger-lab3-api-14 Stopping
|
||||
Container messenger-lab3-api-14 Stopped
|
||||
Container messenger-lab3-api-13 Stopped
|
||||
|
||||
$ python3 scripts/probe.py status GET /api/v1/users/me
|
||||
GET /api/v1/users/me (anonymous) -> 503 {"error": {"code": "unavailable", "message": "no API replica available", "request_id": "1f889229-367b-4fa7-8ca1-2c1cda2dce86"}}
|
||||
|
||||
$ docker compose start api
|
||||
Container messenger-lab3-secrets-init-1 Starting
|
||||
Container messenger-lab3-secrets-init-1 Started
|
||||
Container messenger-lab3-secrets-init-1 Waiting
|
||||
Container messenger-lab3-secrets-init-1 Waiting
|
||||
Container messenger-lab3-secrets-init-1 Exited
|
||||
Container messenger-lab3-secrets-init-1 Exited
|
||||
Container messenger-lab3-postgres-1 Waiting
|
||||
Container messenger-lab3-postgres-1 Healthy
|
||||
Container messenger-lab3-migrate-1 Starting
|
||||
Container messenger-lab3-migrate-1 Started
|
||||
Container messenger-lab3-migrate-1 Waiting
|
||||
Container messenger-lab3-migrate-1 Exited
|
||||
Container messenger-lab3-api-14 Starting
|
||||
Container messenger-lab3-api-14 Started
|
||||
Container messenger-lab3-api-13 Starting
|
||||
Container messenger-lab3-api-13 Started
|
||||
|
||||
$ python3 scripts/probe.py ready
|
||||
ready
|
||||
|
||||
## 5. Живая, но неготовая реплика: PostgreSQL отклоняет подключения только от одной API (pg_hba reject)
|
||||
target=dfa1f6b6a59a ip=172.25.0.6
|
||||
$ docker exec dfa1f6b6a59a node -e let n=0;const g=p=>require('http').get('http://127.0.0.1:8080'+p,r=>{console.log(p,r.statusCode);r.resume();if(++n===2)process.exit(0)});g('/health/live');g('/health/ready')
|
||||
/health/live 200
|
||||
/health/ready 503
|
||||
|
||||
$ python3 scripts/probe.py instances 10
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T15:57:47.146Z
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
|
||||
Server api/api1 is UP, reason: Layer7 check passed, code: 200, check duration: 2ms. 2 active and 0 backup servers online. 0 sessions requeued, 0 total in queue.
|
||||
Server api/api2 is DOWN, reason: Layer7 wrong status, code: 503, info: "Service Unavailable", check duration: 6ms. 1 active and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
|
||||
|
||||
### доступ возвращён: реплика снова готова и получает запросы
|
||||
$ python3 scripts/probe.py instances 6
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T15:57:52.149Z
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: dfa1f6b6a59a
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: dfa1f6b6a59a
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 358dc1d93af4
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: dfa1f6b6a59a
|
||||
|
||||
## 6. Expiry: реплики пересозданы с SESSION_TTL_SECONDS=2
|
||||
$ sh -c docker exec $(docker compose ps -q api | head -1) printenv SESSION_TTL_SECONDS
|
||||
2
|
||||
|
||||
$ python3 scripts/probe.py expiry 2
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T14:58:04.884Z
|
||||
GET /api/v1/users/me (fresh) -> 200
|
||||
GET /api/v1/users/me (after 3s) -> 401
|
||||
|
||||
$ python3 scripts/probe.py ready
|
||||
ready
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"scenario": "parallel POST with one Idempotency-Key through LB",
|
||||
"requests": 20,
|
||||
"all_201": true,
|
||||
"distinct_message_ids": 1,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"e0c31d893858"
|
||||
],
|
||||
"messages_in_history": 1,
|
||||
"date": "2026-11-01T14:54:43Z"
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
# make test-persistence: restart.sh перезапускает postgres, redis, api, lb с сохранением volumes
|
||||
# date: 2026-11-01T14:53:52Z
|
||||
# commit: 252ebd0
|
||||
|
||||
## до
|
||||
/messenger-lab3-api-11 running started=2026-11-01T14:28:36.182340349Z
|
||||
/messenger-lab3-api-12 running started=2026-11-01T14:28:35.862975268Z
|
||||
/messenger-lab3-lb-1 running started=2026-11-01T14:24:20.477359115Z
|
||||
/messenger-lab3-postgres-1 running started=2026-11-01T14:27:53.458295909Z
|
||||
/messenger-lab3-redis-1 running started=2026-11-01T14:27:42.722637458Z
|
||||
|
||||
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://lb:8080"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
## после
|
||||
/messenger-lab3-api-11 running started=2026-11-01T14:53:58.288108033Z
|
||||
/messenger-lab3-api-12 running started=2026-11-01T14:53:58.128282449Z
|
||||
/messenger-lab3-lb-1 running started=2026-11-01T14:53:54.339107937Z
|
||||
/messenger-lab3-postgres-1 running started=2026-11-01T14:53:53.926693488Z
|
||||
/messenger-lab3-redis-1 running started=2026-11-01T14:53:54.188226051Z
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"scenario": "rolling replacement: migrate once, then add new replica, wait healthy, stop old one",
|
||||
"resources_under_load": [
|
||||
"messenger-lab3-api-11 cpu=46.51% mem=96.45MiB / 256MiB",
|
||||
"messenger-lab3-api-12 cpu=47.86% mem=113.1MiB / 256MiB",
|
||||
"messenger-lab3-lb-1 cpu=14.55% mem=16.07MiB / 64MiB",
|
||||
"messenger-lab3-postgres-1 cpu=26.26% mem=84.64MiB / 512MiB",
|
||||
"messenger-lab3-redis-1 cpu=2.31% mem=9.805MiB / 128MiB"
|
||||
],
|
||||
"before": [
|
||||
"/messenger-lab3-api-11 running image=be7b642a4d66",
|
||||
"/messenger-lab3-api-12 running image=be7b642a4d66"
|
||||
],
|
||||
"after": [
|
||||
"/messenger-lab3-api-13 running image=e01eb7165388",
|
||||
"/messenger-lab3-api-14 running image=e01eb7165388"
|
||||
],
|
||||
"steps": [
|
||||
{
|
||||
"replaced": "e0c31d893858",
|
||||
"new_replica_ready_seconds": 6.586,
|
||||
"step_seconds": 10.193
|
||||
},
|
||||
{
|
||||
"replaced": "229dcf033bdc",
|
||||
"new_replica_ready_seconds": 6.773,
|
||||
"step_seconds": 10.365
|
||||
}
|
||||
],
|
||||
"during_update": {
|
||||
"seconds": 31.012,
|
||||
"successful_writes": 4823,
|
||||
"failed_attempts": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 155.5,
|
||||
"latency_ms_successful": {
|
||||
"p50": 12.3,
|
||||
"p95": 78.8,
|
||||
"p99": 105.4
|
||||
},
|
||||
"max_write_gap_seconds": 0.16,
|
||||
"instances": [
|
||||
"229dcf033bdc",
|
||||
"358dc1d93af4",
|
||||
"dfa1f6b6a59a",
|
||||
"e0c31d893858"
|
||||
]
|
||||
},
|
||||
"dataset": {
|
||||
"messages_in_db_before": 106273,
|
||||
"messages_in_db_after": 112337
|
||||
},
|
||||
"history": {
|
||||
"confirmed": 6064,
|
||||
"stored": 6064,
|
||||
"lost_confirmed": 0,
|
||||
"duplicates": 0
|
||||
},
|
||||
"load": {
|
||||
"workers": 4,
|
||||
"model": "closed loop, POST message",
|
||||
"warmup_seconds": 5,
|
||||
"client_timeout_seconds": 2,
|
||||
"retry": "same Idempotency-Key until success"
|
||||
},
|
||||
"date": "2026-11-01T14:57:16Z"
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
# Публичные проверки через LB; разные реплики обслуживают одну сессию
|
||||
# date: 2026-11-01T14:53:50Z
|
||||
# commit: 252ebd0
|
||||
|
||||
$ make check
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
|
||||
$ make test
|
||||
python3 tests/smoke.py --base-url "http://lb:8080"
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
$ sh -c docker compose ps -q api | cut -c1-12
|
||||
e0c31d893858
|
||||
229dcf033bdc
|
||||
|
||||
$ python3 scripts/probe.py instances 6
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-11-01T15:53:52.273Z
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: e0c31d893858
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 229dcf033bdc
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: e0c31d893858
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 229dcf033bdc
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: e0c31d893858
|
||||
GET /api/v1/users/me -> 200 X-Instance-Id: 229dcf033bdc
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# Собственные e2e-тесты (PostgreSQL + Redis из compose.test.yaml)
|
||||
# date: 2026-11-01T14:53:23Z
|
||||
# commit: 252ebd0
|
||||
|
||||
$ docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose
|
||||
Network messenger-lab3-test_default Creating
|
||||
Network messenger-lab3-test_default Created
|
||||
Container messenger-lab3-test-redis-1 Creating
|
||||
Container messenger-lab3-test-postgres-1 Creating
|
||||
Container messenger-lab3-test-redis-1 Created
|
||||
Container messenger-lab3-test-postgres-1 Created
|
||||
Container messenger-lab3-test-redis-1 Starting
|
||||
Container messenger-lab3-test-postgres-1 Starting
|
||||
Container messenger-lab3-test-postgres-1 Started
|
||||
Container messenger-lab3-test-redis-1 Started
|
||||
Prisma schema loaded from prisma/schema.prisma
|
||||
Datasource "db": PostgreSQL database "messenger_test", schema "public" at "postgres:5432"
|
||||
|
||||
3 migrations found in prisma/migrations
|
||||
|
||||
Applying migration `20261021000000_init`
|
||||
Applying migration `20261021010000_auth_sessions`
|
||||
Applying migration `20261101000000_idempotency_keys`
|
||||
|
||||
The following migration(s) have been applied:
|
||||
|
||||
migrations/
|
||||
└─ 20261021000000_init/
|
||||
└─ migration.sql
|
||||
└─ 20261021010000_auth_sessions/
|
||||
└─ migration.sql
|
||||
└─ 20261101000000_idempotency_keys/
|
||||
└─ migration.sql
|
||||
|
||||
All migrations have been successfully applied.
|
||||
PASS test/docs.e2e-spec.ts (8.308 s)
|
||||
Swagger UI и примеры (e2e)
|
||||
✓ отдаёт Swagger UI и документ контракта со всеми путями (79 ms)
|
||||
✓ каждый пример запроса и ответа проходит JSON Schema контракта (452 ms)
|
||||
|
||||
PASS test/concurrency.e2e-spec.ts (9.326 s)
|
||||
Безопасность при конкурентном доступе (e2e)
|
||||
✓ принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных (1479 ms)
|
||||
✓ регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username (200 ms)
|
||||
|
||||
PASS test/auth.e2e-spec.ts (9.593 s)
|
||||
Аутентификация и сессии (e2e)
|
||||
регистрация
|
||||
✓ требует password (89 ms)
|
||||
✓ отклоняет password короче 12 code points (22 ms)
|
||||
✓ хранит пароль как Argon2id-хеш, а не открытым текстом (287 ms)
|
||||
POST /api/v1/auth/sessions
|
||||
✓ выдаёт непрозрачный Bearer-токен с expires_at и пользователем (511 ms)
|
||||
✓ принимает пароль с двоеточием и не-ASCII символами (128 ms)
|
||||
✓ отвечает одинаковым 401 на неверный пароль и неизвестного пользователя (285 ms)
|
||||
✓ отклоняет JSON body при входе даже с верным Basic (84 ms)
|
||||
✓ отвечает 401 без заголовка Authorization (6 ms)
|
||||
защищённые endpoint
|
||||
✓ не принимают Basic (99 ms)
|
||||
✓ не принимают X-User-Id сам по себе (114 ms)
|
||||
✓ игнорируют X-User-Id рядом с Bearer (151 ms)
|
||||
✓ отвечают 401 на неизвестный токен (5 ms)
|
||||
DELETE /api/v1/auth/sessions/current
|
||||
✓ отзывает только текущий токен: 204, затем 401 на повтор (110 ms)
|
||||
|
||||
PASS test/idempotency.e2e-spec.ts (11.296 s)
|
||||
Идемпотентность отправки и X-Instance-Id (e2e)
|
||||
✓ требует Idempotency-Key правильного формата (315 ms)
|
||||
✓ повтор с тем же ключом и телом возвращает тот же 201 и то же сообщение (780 ms)
|
||||
✓ тот же ключ с другим телом — 409, сообщение не создаётся (315 ms)
|
||||
✓ 20 параллельных запросов с одним ключом через два экземпляра создают ровно одно сообщение (311 ms)
|
||||
✓ область ключа — пользователь и чат: одинаковый ключ у разных пользователей и чатов независим (154 ms)
|
||||
✓ повтор заново проверяет сессию (84 ms)
|
||||
✓ после IDEMPOTENCY_TTL_SECONDS ключ можно использовать заново (1613 ms)
|
||||
✓ X-Instance-Id есть в успешных ответах, ошибках и health и стабилен в процессе (12 ms)
|
||||
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:53:46 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mDELETE /api/v1/auth/sessions/current -> 503: session cache unavailable[39m
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:53:46 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mDELETE /api/v1/auth/sessions/current -> 503: session cache unavailable[39m
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:53:46 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mGET /health/ready -> 503: database unavailable[39m
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:53:46 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mGET /api/v1/chats -> 503: database unavailable[39m
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:53:46 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mGET /api/v1/chats -> 503: database unavailable[39m
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:53:46 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mPOST /api/v1/users -> 503: database unavailable[39m
|
||||
[31m[Nest] 175 - [39m11/01/2026, 2:53:46 PM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mGET /api/v1/chats -> 500: Internal server error[39m
|
||||
PASS test/failures.e2e-spec.ts (12.601 s)
|
||||
Уровень 4: expiry, отказы зависимостей, rollback (e2e)
|
||||
✓ сессия истекает при коротком SESSION_TTL_SECONDS, в том числе из кэша (3576 ms)
|
||||
✓ без Redis вход и проверка сессии работают через PostgreSQL, logout — 503 без отзыва (210 ms)
|
||||
✓ logout через реплику без связи с Redis не создаёт расхождения с репликой, у которой сессия в кэше (412 ms)
|
||||
✓ без PostgreSQL отвечает ограниченным 503 и не пускает анонима (232 ms)
|
||||
✓ неожиданное исключение — 500 internal_error без деталей, с X-Request-Id и X-Instance-Id (107 ms)
|
||||
✓ откатывает создание чата целиком, если один из участников не существует (103 ms)
|
||||
|
||||
PASS test/api.e2e-spec.ts (12.801 s)
|
||||
API мессенджера (e2e) — граничные случаи сверх публичного smoke
|
||||
POST /api/v1/users
|
||||
✓ отклоняет некорректный JSON с кодом 400 (84 ms)
|
||||
✓ отклоняет тело с лишними полями (32 ms)
|
||||
✓ отклоняет username с заглавными буквами (8 ms)
|
||||
✓ отклоняет display_name из одних пробелов (7 ms)
|
||||
✓ отклоняет дубликат username с кодом 409 (809 ms)
|
||||
✓ никогда не возвращает поле пароля или его хэша (60 ms)
|
||||
✓ отклоняет username короче 3 символов (6 ms)
|
||||
✓ отклоняет username длиннее 32 символов (6 ms)
|
||||
✓ отклоняет username с недопустимыми символами (дефис) (9 ms)
|
||||
✓ принимает username ровно на границах длины 3 и 32 символа (81 ms)
|
||||
✓ отклоняет display_name длиннее 100 Unicode code points (5 ms)
|
||||
✓ принимает display_name ровно из 100 code points, считая эмодзи вне BMP за один символ (41 ms)
|
||||
✓ отклоняет display_name из 101 code point, состоящий из эмодзи вне BMP (6 ms)
|
||||
контроль доступа
|
||||
✓ возвращает 401 раньше 404, если и актор, и ресурс невалидны (11 ms)
|
||||
✓ возвращает 404 (не 403), когда чат запрашивает не его участник (633 ms)
|
||||
✓ отклоняет создание чата, если вызывающий не входит в member_ids (126 ms)
|
||||
✓ отклоняет создание чата с дублирующимися member_ids (66 ms)
|
||||
✓ считает один UUID в разном регистре дубликатом и узнаёт вызывающего в верхнем регистре (63 ms)
|
||||
✓ принимает ровно 100 участников и отклоняет 101 (75 ms)
|
||||
✓ отклоняет создание чата с неизвестным участником (65 ms)
|
||||
✓ отклоняет создание чата с пустым/пробельным title (60 ms)
|
||||
✓ возвращает 400 для синтаксически некорректного chat_id (не UUID) (59 ms)
|
||||
✓ возвращает 404 для корректного по формату, но несуществующего chat_id (56 ms)
|
||||
GET /api/v1/chats (пагинация)
|
||||
✓ использует limit=50 по умолчанию, если limit не передан (67 ms)
|
||||
✓ отклоняет нечисловой limit (59 ms)
|
||||
✓ отклоняет limit=0 (68 ms)
|
||||
✓ отклоняет повторённые limit и cursor (66 ms)
|
||||
✓ отклоняет cursor, не являющийся корректным base64url JSON (61 ms)
|
||||
✓ отклоняет корректно закодированный cursor с id чата, который никогда не существовал (58 ms)
|
||||
✓ обходит весь список чатов по страницам без пропусков и дублей (91 ms)
|
||||
сообщения
|
||||
✓ не принимает sender_id, переданный клиентом (113 ms)
|
||||
✓ считает attachment_ids: [] равным отсутствию поля, непустой список отклоняет (142 ms)
|
||||
✓ отклоняет пустое сообщение (120 ms)
|
||||
✓ отклоняет сообщение из одних пробелов (116 ms)
|
||||
✓ отклоняет отправку в чат, где вызывающий не участник (157 ms)
|
||||
✓ отклоняет limit=0 при чтении истории (123 ms)
|
||||
✓ отклоняет limit=101 при чтении истории (103 ms)
|
||||
✓ отклоняет нечисловой limit (125 ms)
|
||||
✓ отклоняет текст сообщения длиннее 4000 Unicode code points (177 ms)
|
||||
✓ принимает текст сообщения ровно из 4000 Unicode code points (196 ms)
|
||||
✓ отклоняет текст сообщения свыше 4000 code points, состоящий из эмодзи вне BMP (119 ms)
|
||||
✓ отклоняет cursor, не являющийся корректным base64url JSON (122 ms)
|
||||
✓ отклоняет корректно закодированный cursor с id сообщения, которое никогда не существовало в этом чате (139 ms)
|
||||
✓ возвращает 400 для синтаксически некорректного chat_id при отправке сообщения (63 ms)
|
||||
✓ возвращает 400 для синтаксически некорректного chat_id при чтении истории (68 ms)
|
||||
✓ отклоняет cursor, взятый из другого чата (157 ms)
|
||||
✓ обходит всю историю по страницам без пропусков и дублей (161 ms)
|
||||
X-Request-Id
|
||||
✓ присутствует и уникален для независимых запросов (3 ms)
|
||||
✓ совпадает с request_id внутри тела ошибки (1 ms)
|
||||
|
||||
A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.
|
||||
Test Suites: 6 passed, 6 total
|
||||
Tests: 80 passed, 80 total
|
||||
Snapshots: 0 total
|
||||
Time: 13.86 s
|
||||
Ran all test suites.
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
maxconn 2000
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
option dontlognull
|
||||
timeout connect 1s
|
||||
timeout client 30s
|
||||
timeout server 10s
|
||||
timeout http-request 10s
|
||||
timeout queue 5s
|
||||
timeout check 1s
|
||||
retries 2
|
||||
option redispatch 1
|
||||
retry-on conn-failure
|
||||
unique-id-format %[uuid()]
|
||||
http-error status 502 content-type application/json hdr X-Request-Id "%[unique-id]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"bad gateway\",\"request_id\":\"%[unique-id]\"}}"
|
||||
http-error status 503 content-type application/json hdr X-Request-Id "%[unique-id]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"no API replica available\",\"request_id\":\"%[unique-id]\"}}"
|
||||
http-error status 504 content-type application/json hdr X-Request-Id "%[unique-id]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"gateway timeout\",\"request_id\":\"%[unique-id]\"}}"
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 5s
|
||||
hold obsolete 5s
|
||||
accepted_payload_size 8192
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
default-server check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
|
||||
server-template api 1-4 api:8080
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
Generated
+10106
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"name": "mtusi-messenger-lab3",
|
||||
"version": "1.0.0",
|
||||
"description": "Lab 1: in-memory messenger API (NestJS + Fastify)",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"start": "node dist/main.js",
|
||||
"start:dev": "nest start --watch",
|
||||
"lint": "eslint \"{src,test}/**/*.ts\"",
|
||||
"test": "jest --config ./test/jest-e2e.json",
|
||||
"test:watch": "jest --config ./test/jest-e2e.json --watch"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/static": "7.0.4",
|
||||
"@nestjs/common": "^10.4.15",
|
||||
"@nestjs/core": "^10.4.15",
|
||||
"@nestjs/platform-fastify": "^10.4.15",
|
||||
"@nestjs/swagger": "7.4.2",
|
||||
"@prisma/client": "6.1.0",
|
||||
"argon2": "0.41.1",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"ioredis": "5.4.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^10.4.9",
|
||||
"@nestjs/schematics": "^10.2.3",
|
||||
"@nestjs/testing": "^10.4.15",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.17.9",
|
||||
"@types/supertest": "^6.0.2",
|
||||
"@typescript-eslint/eslint-plugin": "^8.18.1",
|
||||
"@typescript-eslint/parser": "^8.18.1",
|
||||
"ajv": "8.12.0",
|
||||
"eslint": "^8.57.1",
|
||||
"jest": "^29.7.0",
|
||||
"prisma": "6.1.0",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-loader": "^9.5.1",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.7.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
CREATE TABLE "users" (
|
||||
"id" UUID NOT NULL,
|
||||
"username" VARCHAR(32) NOT NULL,
|
||||
"display_name" VARCHAR(100) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "users_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "users_username_format" CHECK ("username" ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT "users_display_name_not_blank" CHECK (btrim("display_name") <> '')
|
||||
);
|
||||
|
||||
CREATE TABLE "chats" (
|
||||
"id" UUID NOT NULL,
|
||||
"title" VARCHAR(100) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "chats_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "chats_title_not_blank" CHECK (btrim("title") <> '')
|
||||
);
|
||||
|
||||
CREATE TABLE "chat_members" (
|
||||
"chat_id" UUID NOT NULL,
|
||||
"user_id" UUID NOT NULL,
|
||||
|
||||
CONSTRAINT "chat_members_pkey" PRIMARY KEY ("chat_id","user_id")
|
||||
);
|
||||
|
||||
CREATE TABLE "messages" (
|
||||
"id" UUID NOT NULL,
|
||||
"chat_id" UUID NOT NULL,
|
||||
"sender_id" UUID NOT NULL,
|
||||
"text" VARCHAR(4000) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "messages_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX "users_username_key" ON "users"("username");
|
||||
|
||||
CREATE INDEX "chat_members_user_id_idx" ON "chat_members"("user_id");
|
||||
|
||||
CREATE INDEX "messages_chat_id_created_at_id_idx" ON "messages"("chat_id", "created_at", "id");
|
||||
|
||||
ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "messages" ADD CONSTRAINT "messages_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "messages" ADD CONSTRAINT "messages_sender_id_fkey" FOREIGN KEY ("sender_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,14 @@
|
||||
ALTER TABLE "users" ADD COLUMN "password_hash" TEXT NOT NULL;
|
||||
|
||||
CREATE TABLE "sessions" (
|
||||
"token_hash" CHAR(64) NOT NULL,
|
||||
"user_id" UUID NOT NULL,
|
||||
"expires_at" TIMESTAMPTZ(3) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "sessions_pkey" PRIMARY KEY ("token_hash")
|
||||
);
|
||||
|
||||
CREATE INDEX "sessions_user_id_idx" ON "sessions"("user_id");
|
||||
|
||||
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE "idempotency_keys" (
|
||||
"user_id" UUID NOT NULL,
|
||||
"chat_id" UUID NOT NULL,
|
||||
"key" VARCHAR(128) NOT NULL,
|
||||
"request_hash" CHAR(64) NOT NULL,
|
||||
"message_id" UUID NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "idempotency_keys_pkey" PRIMARY KEY ("user_id","chat_id","key"),
|
||||
CONSTRAINT "idempotency_keys_key_format" CHECK ("key" ~ '^[A-Za-z0-9._:-]{1,128}$')
|
||||
);
|
||||
|
||||
ALTER TABLE "idempotency_keys" ADD CONSTRAINT "idempotency_keys_message_id_fkey" FOREIGN KEY ("message_id") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (i.e. Git)
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,80 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
username String @unique @db.VarChar(32)
|
||||
displayName String @map("display_name") @db.VarChar(100)
|
||||
passwordHash String @map("password_hash")
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
memberships ChatMember[]
|
||||
messages Message[]
|
||||
sessions Session[]
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model Session {
|
||||
tokenHash String @id @map("token_hash") @db.Char(64)
|
||||
userId String @map("user_id") @db.Uuid
|
||||
expiresAt DateTime @map("expires_at") @db.Timestamptz(3)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([userId])
|
||||
@@map("sessions")
|
||||
}
|
||||
|
||||
model Chat {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
title String @db.VarChar(100)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
members ChatMember[]
|
||||
messages Message[]
|
||||
|
||||
@@map("chats")
|
||||
}
|
||||
|
||||
model ChatMember {
|
||||
chatId String @map("chat_id") @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||
|
||||
@@id([chatId, userId])
|
||||
@@index([userId])
|
||||
@@map("chat_members")
|
||||
}
|
||||
|
||||
model Message {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
chatId String @map("chat_id") @db.Uuid
|
||||
senderId String @map("sender_id") @db.Uuid
|
||||
text String @db.VarChar(4000)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
|
||||
sender User @relation(fields: [senderId], references: [id], onDelete: Restrict)
|
||||
idempotencyKeys IdempotencyKey[]
|
||||
|
||||
@@index([chatId, createdAt, id])
|
||||
@@map("messages")
|
||||
}
|
||||
|
||||
model IdempotencyKey {
|
||||
userId String @map("user_id") @db.Uuid
|
||||
chatId String @map("chat_id") @db.Uuid
|
||||
key String @db.VarChar(128)
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
messageId String @map("message_id") @db.Uuid
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
message Message @relation(fields: [messageId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([userId, chatId, key])
|
||||
@@map("idempotency_keys")
|
||||
}
|
||||
Executable
+162
@@ -0,0 +1,162 @@
|
||||
#!/bin/sh
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
|
||||
COMMIT="$(git rev-parse --short HEAD)$(git diff --quiet HEAD -- src prisma test scripts infra compose.yaml Dockerfile || echo ' (dirty)')"
|
||||
|
||||
header() {
|
||||
printf '# %s\n# date: %s\n# commit: %s\n\n' "$1" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$COMMIT"
|
||||
}
|
||||
|
||||
run() {
|
||||
echo "\$ $*"
|
||||
"$@" 2>&1 || echo "EXIT CODE $?"
|
||||
echo
|
||||
}
|
||||
|
||||
started() {
|
||||
docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -aq postgres redis api lb)
|
||||
}
|
||||
|
||||
api_states() {
|
||||
docker inspect -f '{{.Name}} id={{slice .Id 0 12}} {{.State.Status}} exit={{.State.ExitCode}} finished={{.State.FinishedAt}}' $(docker compose ps -aq api)
|
||||
}
|
||||
|
||||
restore_api() {
|
||||
for id in $(docker compose ps -aq --status exited api); do
|
||||
docker start "$id" >/dev/null
|
||||
done
|
||||
python3 scripts/probe.py ready >/dev/null
|
||||
sleep 3
|
||||
}
|
||||
|
||||
echo 'container.txt'
|
||||
{
|
||||
header 'Стенд: сервисы, порты, лимиты, секреты, миграции'
|
||||
run docker compose ps -a --format 'table {{.Service}}\t{{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'
|
||||
echo '## CPU/RAM-лимиты (NanoCpus: 1e9 = 1 CPU; Memory в байтах)'
|
||||
run sh -c "docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}}' \$(docker compose ps -q)"
|
||||
echo '## container_name не задан (одно имя сервиса масштабируется)'
|
||||
run sh -c "docker compose config | grep -c container_name || true"
|
||||
echo '## Секреты: каждый сервис видит только свои файлы'
|
||||
for service in postgres redis api; do
|
||||
run docker compose exec -T "$service" ls /run/secrets
|
||||
done
|
||||
run docker compose exec -T lb sh -c 'ls /run/secrets 2>/dev/null || echo "no /run/secrets"'
|
||||
run docker compose exec -T lb haproxy -v
|
||||
run docker compose exec -T postgres postgres --version
|
||||
run docker compose exec -T redis redis-server --version
|
||||
echo '## Миграции: отдельный one-shot сервис, повторный запуск ничего не применяет'
|
||||
run docker compose run --rm migrate
|
||||
run docker compose run --rm --no-deps migrate sh -c 'export DATABASE_URL="$(cat "$DATABASE_URL_FILE")"; npx prisma migrate diff --from-url "$DATABASE_URL" --to-schema-datamodel prisma/schema.prisma --exit-code'
|
||||
run docker compose exec -T postgres psql -U messenger -d messenger -c 'SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY started_at'
|
||||
} > evidence/container.txt
|
||||
|
||||
echo 'tests.txt'
|
||||
{
|
||||
header 'Собственные e2e-тесты (PostgreSQL + Redis из compose.test.yaml)'
|
||||
docker compose -f compose.test.yaml build -q tests
|
||||
run docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose
|
||||
docker compose -f compose.test.yaml down >/dev/null 2>&1
|
||||
} > evidence/tests.txt
|
||||
|
||||
echo 'smoke.txt'
|
||||
{
|
||||
header 'Публичные проверки через LB; разные реплики обслуживают одну сессию'
|
||||
run make check
|
||||
run make test
|
||||
run sh -c "docker compose ps -q api | cut -c1-12"
|
||||
run python3 scripts/probe.py instances 6
|
||||
} > evidence/smoke.txt
|
||||
|
||||
echo 'persistence.txt'
|
||||
{
|
||||
header 'make test-persistence: restart.sh перезапускает postgres, redis, api, lb с сохранением volumes'
|
||||
echo '## до'
|
||||
started
|
||||
echo
|
||||
run make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
echo '## после'
|
||||
started
|
||||
} > evidence/persistence.txt
|
||||
|
||||
echo 'failover.txt'
|
||||
{
|
||||
header 'make test-failover: stop-one.sh останавливает реплику, обслужившую тест; затем вторую'
|
||||
for round in 1 2; do
|
||||
echo "## Прогон $round"
|
||||
echo '### до'
|
||||
api_states
|
||||
echo
|
||||
since=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
run make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
echo '### после: остановленная реплика Exited (0) — штатное завершение по SIGTERM'
|
||||
api_states
|
||||
echo
|
||||
echo '### журнал HAProxy'
|
||||
docker compose logs --no-log-prefix --since "$since" lb 2>&1 | grep -E 'is DOWN|is UP|maintenance|READY' | grep -v '^\[WARNING\]'
|
||||
echo
|
||||
restore_api
|
||||
python3 scripts/probe.py status GET /health/live >/dev/null
|
||||
done
|
||||
echo '## Проверка guard: stop-one.sh отказывается останавливать не api'
|
||||
run env TARGET_INSTANCE_ID="$(docker compose ps -q postgres | cut -c1-12)" sh scripts/stop-one.sh
|
||||
} > evidence/failover.txt
|
||||
|
||||
echo 'experiments: idempotency, failover, failover --kill, rolling'
|
||||
python3 scripts/experiment.py idempotency --output evidence/idempotency.json >/dev/null 2>&1
|
||||
python3 scripts/experiment.py failover --output evidence/failover-stop.json >/dev/null 2>&1
|
||||
python3 scripts/experiment.py failover --kill --output evidence/failover-kill.json >/dev/null 2>&1
|
||||
docker compose build -q api >/dev/null 2>&1
|
||||
python3 scripts/experiment.py rolling --output evidence/rolling.json >/dev/null 2>&1
|
||||
|
||||
echo 'failures.txt'
|
||||
{
|
||||
header 'Отказы зависимостей, ошибки LB, expiry'
|
||||
echo '## 1. Redis остановлен: вход и Bearer через PostgreSQL; logout — 503 без отзыва (токен остаётся действующим)'
|
||||
run docker compose stop redis
|
||||
run python3 scripts/probe.py logout
|
||||
run docker compose start redis
|
||||
sleep 3
|
||||
echo '## 2. Redis снова доступен: logout отзывает токен на всех репликах'
|
||||
run python3 scripts/probe.py logout
|
||||
echo '## 3. PostgreSQL остановлен: live 200, запрос с токеном — 503 без внутренних деталей, аноним — 401'
|
||||
run docker compose stop postgres
|
||||
run python3 scripts/probe.py status GET /health/live
|
||||
run python3 scripts/probe.py status GET /api/v1/chats 'Bearer unknown-token'
|
||||
run python3 scripts/probe.py status GET /api/v1/users/me
|
||||
run docker compose start postgres
|
||||
run python3 scripts/probe.py ready
|
||||
echo '## 4. Все реплики API остановлены: LB отвечает 503 в формате ошибки контракта'
|
||||
run docker compose stop api
|
||||
run python3 scripts/probe.py status GET /api/v1/users/me
|
||||
run docker compose start api
|
||||
run python3 scripts/probe.py ready
|
||||
echo '## 5. Живая, но неготовая реплика: PostgreSQL отклоняет подключения только от одной API (pg_hba reject)'
|
||||
target=$(docker compose ps -q api | head -1 | cut -c1-12)
|
||||
ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$target")
|
||||
hba=/var/lib/postgresql/data/pg_hba.conf
|
||||
echo "target=$target ip=$ip"
|
||||
since=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
docker compose exec -T postgres sh -c "cp $hba /tmp/pg_hba.bak && { echo 'host all all $ip/32 reject'; cat /tmp/pg_hba.bak; } > $hba && chown postgres:postgres $hba && chmod 600 $hba"
|
||||
docker compose exec -T postgres psql -U messenger -d messenger -tAc "SELECT pg_reload_conf(); SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE client_addr = '$ip'" >/dev/null
|
||||
sleep 4
|
||||
run docker exec "$target" node -e "let n=0;const g=p=>require('http').get('http://127.0.0.1:8080'+p,r=>{console.log(p,r.statusCode);r.resume();if(++n===2)process.exit(0)});g('/health/live');g('/health/ready')"
|
||||
run python3 scripts/probe.py instances 10
|
||||
docker compose logs --no-log-prefix --since "$since" lb 2>&1 | grep -E 'is DOWN|is UP' | grep -v '^\[WARNING\]'
|
||||
echo
|
||||
docker compose exec -T postgres sh -c "cp /tmp/pg_hba.bak $hba && chown postgres:postgres $hba && chmod 600 $hba"
|
||||
docker compose exec -T postgres psql -U messenger -d messenger -tAc "SELECT pg_reload_conf()" >/dev/null
|
||||
sleep 4
|
||||
echo '### доступ возвращён: реплика снова готова и получает запросы'
|
||||
run python3 scripts/probe.py instances 6
|
||||
echo '## 6. Expiry: реплики пересозданы с SESSION_TTL_SECONDS=2'
|
||||
SESSION_TTL_SECONDS=2 docker compose up -d --no-deps --wait api >/dev/null 2>&1
|
||||
run sh -c "docker exec \$(docker compose ps -q api | head -1) printenv SESSION_TTL_SECONDS"
|
||||
run python3 scripts/probe.py expiry 2
|
||||
docker compose up -d --no-deps --wait api >/dev/null 2>&1
|
||||
run python3 scripts/probe.py ready
|
||||
} > evidence/failures.txt
|
||||
|
||||
echo 'done'
|
||||
Executable
+255
@@ -0,0 +1,255 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure
|
||||
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://lb:8080')
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.run(['docker', *args], check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def api_containers():
|
||||
return [cid[:12] for cid in docker('compose', 'ps', '-q', 'api').split()]
|
||||
|
||||
|
||||
def describe(cid):
|
||||
return docker('inspect', '-f', '{{.Name}} {{.State.Status}} image={{slice .Image 7 19}}', cid)
|
||||
|
||||
|
||||
def wait_healthy(cid, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if docker('inspect', '-f', '{{.State.Health.Status}}', cid) == 'healthy':
|
||||
return
|
||||
time.sleep(0.2)
|
||||
raise SystemExit(cid + ' did not become healthy')
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, client, actor, chat, workers):
|
||||
self.client, self.actor, self.chat = client, actor, chat
|
||||
self.workers = workers
|
||||
self.lock = threading.Lock()
|
||||
self.events = []
|
||||
self.confirmed = []
|
||||
self.stop_flag = threading.Event()
|
||||
self.threads = [threading.Thread(target=self.worker, args=(i,)) for i in range(workers)]
|
||||
self.started = None
|
||||
|
||||
def worker(self, index):
|
||||
local = Client(BASE_URL, timeout=2)
|
||||
key = uuid.uuid4().hex
|
||||
while not self.stop_flag.is_set():
|
||||
try:
|
||||
response = local.message(self.actor, self.chat, 'load ' + key, key=key)
|
||||
with self.lock:
|
||||
self.events.append((time.monotonic(), True, response['headers']['X-Instance-Id'], response['elapsed']))
|
||||
self.confirmed.append(response['json'])
|
||||
key = uuid.uuid4().hex
|
||||
except Failure:
|
||||
with self.lock:
|
||||
self.events.append((time.monotonic(), False, None, None))
|
||||
time.sleep(0.05)
|
||||
|
||||
def __enter__(self):
|
||||
self.started = time.monotonic()
|
||||
for thread in self.threads:
|
||||
thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.stop_flag.set()
|
||||
for thread in self.threads:
|
||||
thread.join()
|
||||
|
||||
def window(self, start, end):
|
||||
with self.lock:
|
||||
events = [e for e in self.events if start <= e[0] < end]
|
||||
ok = sorted(e[0] for e in events if e[1])
|
||||
latencies = sorted(e[3] for e in events if e[1])
|
||||
points = [start, *ok, end]
|
||||
|
||||
def percentile(p):
|
||||
return round(1000 * latencies[max(0, math.ceil(p * len(latencies)) - 1)], 1) if latencies else None
|
||||
|
||||
return {
|
||||
'seconds': round(end - start, 3),
|
||||
'successful_writes': len(ok),
|
||||
'failed_attempts': len(events) - len(ok),
|
||||
'error_ratio': round((len(events) - len(ok)) / len(events), 4) if events else None,
|
||||
'successful_rps': round(len(ok) / (end - start), 1),
|
||||
'latency_ms_successful': {'p50': percentile(0.5), 'p95': percentile(0.95), 'p99': percentile(0.99)},
|
||||
'max_write_gap_seconds': round(max(b - a for a, b in zip(points, points[1:])), 3),
|
||||
'instances': sorted({e[2] for e in events if e[1]}),
|
||||
}
|
||||
|
||||
def last_seen(self, instance, start, end):
|
||||
with self.lock:
|
||||
times = [e[0] for e in self.events if e[1] and e[2] == instance and start <= e[0] < end]
|
||||
return max(times) if times else None
|
||||
|
||||
def first_seen_after(self, instance, after):
|
||||
with self.lock:
|
||||
times = [e[0] for e in self.events if e[1] and e[2] == instance and e[0] >= after]
|
||||
return min(times) if times else None
|
||||
|
||||
|
||||
def verify_history(client, actor, chat, confirmed):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100'
|
||||
items = []
|
||||
while True:
|
||||
page = client.call('GET', path, actor=actor, schema='MessagePage')['json']
|
||||
items.extend(page['items'])
|
||||
if page['next_cursor'] is None:
|
||||
break
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100&cursor=' + quote(page['next_cursor'], safe='')
|
||||
texts = [m['text'] for m in items]
|
||||
stored = {m['id']: m for m in items}
|
||||
return {
|
||||
'confirmed': len(confirmed),
|
||||
'stored': len(items),
|
||||
'lost_confirmed': sum(1 for m in confirmed if stored.get(m['id']) != m),
|
||||
'duplicates': len(texts) - len(set(texts)),
|
||||
}
|
||||
|
||||
|
||||
def resources():
|
||||
ids = docker('compose', 'ps', '-q').split()
|
||||
return docker('stats', '--no-stream', '--format', '{{.Name}} cpu={{.CPUPerc}} mem={{.MemUsage}}', *ids).splitlines()
|
||||
|
||||
|
||||
def messages_in_db():
|
||||
return int(docker('compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc', 'SELECT count(*) FROM messages'))
|
||||
|
||||
|
||||
def failover(load, args):
|
||||
results = []
|
||||
with load:
|
||||
time.sleep(args.warmup)
|
||||
usage = resources()
|
||||
for cid in api_containers():
|
||||
t0 = time.monotonic()
|
||||
docker('kill' if args.kill else 'stop', cid)
|
||||
stopped = time.monotonic()
|
||||
time.sleep(args.outage)
|
||||
outage = load.window(t0, time.monotonic())
|
||||
restore = time.monotonic()
|
||||
docker('start', cid)
|
||||
wait_healthy(cid)
|
||||
healthy = time.monotonic()
|
||||
time.sleep(args.warmup)
|
||||
rejoined = load.first_seen_after(cid, restore)
|
||||
last = load.last_seen(cid, t0, restore)
|
||||
results.append({
|
||||
'container': describe(cid),
|
||||
'action': 'docker kill (SIGKILL)' if args.kill else 'docker stop (SIGTERM, graceful)',
|
||||
'before': load.window(t0 - args.warmup, t0),
|
||||
'stop_command_seconds': round(stopped - t0, 3),
|
||||
'target_last_success_after_stop_seconds': round(last - t0, 3) if last else None,
|
||||
'outage_window': outage,
|
||||
'restore_until_healthy_seconds': round(healthy - restore, 3),
|
||||
'restore_until_serving_seconds': round(rejoined - restore, 3) if rejoined else None,
|
||||
'after_restore': load.window(healthy, time.monotonic()),
|
||||
})
|
||||
return {'scenario': 'sequential failover of each api replica', 'resources_under_load': usage, 'replicas': results}
|
||||
|
||||
|
||||
def rolling(load, args):
|
||||
old = api_containers()
|
||||
before = [describe(cid) for cid in old]
|
||||
steps = []
|
||||
with load:
|
||||
time.sleep(args.warmup)
|
||||
usage = resources()
|
||||
t_start = time.monotonic()
|
||||
docker('compose', 'run', '--rm', '--no-deps', 'migrate')
|
||||
for cid in old:
|
||||
t0 = time.monotonic()
|
||||
docker('compose', 'up', '-d', '--no-deps', '--no-recreate', '--scale', 'api=' + str(len(old) + 1), '--wait', 'api')
|
||||
added = time.monotonic()
|
||||
docker('stop', cid)
|
||||
docker('rm', cid)
|
||||
steps.append({'replaced': cid, 'new_replica_ready_seconds': round(added - t0, 3), 'step_seconds': round(time.monotonic() - t0, 3)})
|
||||
time.sleep(args.warmup)
|
||||
total = load.window(t_start, time.monotonic())
|
||||
return {
|
||||
'scenario': 'rolling replacement: migrate once, then add new replica, wait healthy, stop old one',
|
||||
'resources_under_load': usage,
|
||||
'before': before,
|
||||
'after': [describe(cid) for cid in api_containers()],
|
||||
'steps': steps,
|
||||
'during_update': total,
|
||||
}
|
||||
|
||||
|
||||
def idempotency(client, actor, chat, args):
|
||||
key = uuid.uuid4().hex
|
||||
text = 'parallel ' + key
|
||||
|
||||
def send(_):
|
||||
local = Client(BASE_URL, timeout=10)
|
||||
response = local.message(actor, chat, text, key=key)
|
||||
return response['json']['id'], response['headers']['X-Instance-Id']
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.parallel) as pool:
|
||||
results = list(pool.map(send, range(args.parallel)))
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100'
|
||||
stored = [m for m in client.call('GET', path, actor=actor, schema='MessagePage')['json']['items'] if m['text'] == text]
|
||||
return {
|
||||
'scenario': 'parallel POST with one Idempotency-Key through LB',
|
||||
'requests': args.parallel,
|
||||
'all_201': True,
|
||||
'distinct_message_ids': len({r[0] for r in results}),
|
||||
'instances': sorted({r[1] for r in results}),
|
||||
'messages_in_history': len(stored),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Lab3 level-4 experiments under load through LB')
|
||||
parser.add_argument('scenario', choices=['failover', 'rolling', 'idempotency'])
|
||||
parser.add_argument('--workers', type=int, default=4)
|
||||
parser.add_argument('--warmup', type=float, default=5)
|
||||
parser.add_argument('--outage', type=float, default=10)
|
||||
parser.add_argument('--parallel', type=int, default=20)
|
||||
parser.add_argument('--kill', action='store_true')
|
||||
parser.add_argument('--output')
|
||||
args = parser.parse_args()
|
||||
|
||||
client = Client(BASE_URL)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
scenarios = {'failover': failover, 'rolling': rolling}
|
||||
if args.scenario in scenarios:
|
||||
load = Load(client, alice, chat, args.workers)
|
||||
dataset = messages_in_db()
|
||||
report = scenarios[args.scenario](load, args)
|
||||
report['dataset'] = {'messages_in_db_before': dataset, 'messages_in_db_after': messages_in_db()}
|
||||
report['history'] = verify_history(client, bob, chat, load.confirmed)
|
||||
report['load'] = {'workers': args.workers, 'model': 'closed loop, POST message', 'warmup_seconds': args.warmup, 'client_timeout_seconds': 2, 'retry': 'same Idempotency-Key until success'}
|
||||
else:
|
||||
report = idempotency(client, alice, chat, args)
|
||||
report['date'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.output).write_text(text + '\n')
|
||||
print(text)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
BASE = os.environ.get('BASE_URL', 'http://localhost:8080')
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None, with_headers=False):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
content_type = {'Content-Type': 'application/json'} if data else {}
|
||||
request = urllib.request.Request(BASE + path, data=data, method=method, headers={**content_type, **(headers or {})})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
result = response.status, json.loads(response.read() or b'null'), response.headers
|
||||
except urllib.error.HTTPError as error:
|
||||
result = error.code, json.loads(error.read() or b'null'), error.headers
|
||||
except OSError as error:
|
||||
result = 0, str(error), {}
|
||||
return result if with_headers else result[:2]
|
||||
|
||||
|
||||
def login():
|
||||
username = 'probe_' + uuid.uuid4().hex[:8]
|
||||
password = 'Probe-check-' + uuid.uuid4().hex
|
||||
print('register ->', call('POST', '/api/v1/users', {'username': username, 'display_name': 'Probe', 'password': password})[0])
|
||||
credential = base64.b64encode((username + ':' + password).encode()).decode()
|
||||
code, session = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential})
|
||||
if code != 201:
|
||||
sys.exit('login failed: %s %s' % (code, session))
|
||||
print('login ->', code, 'expires_at:', session['expires_at'])
|
||||
return {'Authorization': 'Bearer ' + session['token']}
|
||||
|
||||
|
||||
def instances(count):
|
||||
auth = login()
|
||||
for _ in range(count):
|
||||
code, _, headers = call('GET', '/api/v1/users/me', headers=auth, with_headers=True)
|
||||
print('GET /api/v1/users/me ->', code, 'X-Instance-Id:', headers.get('X-Instance-Id'))
|
||||
|
||||
|
||||
def logout():
|
||||
auth = login()
|
||||
print('GET /api/v1/users/me ->', call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
code, body = call('DELETE', '/api/v1/auth/sessions/current', headers=auth)
|
||||
print('DELETE /api/v1/auth/sessions/current ->', code, json.dumps(body, ensure_ascii=False) if body else '')
|
||||
print('GET /api/v1/users/me ->', call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
|
||||
|
||||
def ready(timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if call('GET', '/health/ready')[0] == 200:
|
||||
print('ready')
|
||||
return
|
||||
time.sleep(0.5)
|
||||
sys.exit('not ready within %ds' % timeout)
|
||||
|
||||
|
||||
def status(method, path, authorization=None):
|
||||
code, body = call(method, path, headers={'Authorization': authorization} if authorization else None)
|
||||
print(method, path, '(%s)' % (authorization or 'anonymous'), '->', code, json.dumps(body, ensure_ascii=False))
|
||||
|
||||
|
||||
def expiry(ttl):
|
||||
auth = login()
|
||||
print('GET /api/v1/users/me (fresh) ->', call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
time.sleep(ttl + 1)
|
||||
print('GET /api/v1/users/me (after %ds) ->' % (ttl + 1), call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
command = sys.argv[1]
|
||||
if command == 'ready':
|
||||
ready()
|
||||
elif command == 'status':
|
||||
status(*sys.argv[2:5])
|
||||
elif command == 'expiry':
|
||||
expiry(int(sys.argv[2]))
|
||||
elif command == 'instances':
|
||||
instances(int(sys.argv[2]))
|
||||
elif command == 'logout':
|
||||
logout()
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
started() {
|
||||
docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -aq postgres redis api lb)
|
||||
}
|
||||
started
|
||||
docker compose restart postgres redis api lb
|
||||
started
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
project="${COMPOSE_PROJECT_NAME:-messenger-lab3}"
|
||||
labels=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}/{{index .Config.Labels "com.docker.compose.service"}}' "$TARGET_INSTANCE_ID")
|
||||
if [ "$labels" != "$project/api" ]; then
|
||||
echo "refusing to stop $TARGET_INSTANCE_ID: not an api replica of $project ($labels)" >&2
|
||||
exit 1
|
||||
fi
|
||||
docker stop -t 8 "$TARGET_INSTANCE_ID" >/dev/null
|
||||
docker inspect -f '{{.Name}} {{.State.Status}} finished={{.State.FinishedAt}}' "$TARGET_INSTANCE_ID"
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { CacheModule } from './cache/cache.module';
|
||||
import { ChatsModule } from './chats/chats.module';
|
||||
import { DbModule } from './db/db.module';
|
||||
import { HealthModule } from './health/health.module';
|
||||
import { MessagesModule } from './messages/messages.module';
|
||||
import { UsersModule } from './users/users.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
DbModule,
|
||||
CacheModule,
|
||||
AuthModule,
|
||||
HealthModule,
|
||||
UsersModule,
|
||||
ChatsModule,
|
||||
MessagesModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
Controller,
|
||||
Delete,
|
||||
Headers,
|
||||
HttpCode,
|
||||
Post,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { toUserResponse, UserResponse } from '../users/dto/user.response';
|
||||
import { AuthGuard } from './auth.guard';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
interface SessionResponse {
|
||||
token: string;
|
||||
token_type: 'Bearer';
|
||||
expires_at: string;
|
||||
user: UserResponse;
|
||||
}
|
||||
|
||||
@Controller('api/v1/auth/sessions')
|
||||
export class AuthController {
|
||||
constructor(private readonly auth: AuthService) {}
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
async create(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Req() request: FastifyRequest,
|
||||
): Promise<SessionResponse> {
|
||||
if (request.body !== undefined) {
|
||||
throw new ApiError('invalid_request', 'request body is not allowed');
|
||||
}
|
||||
const session = await this.auth.login(authorization);
|
||||
return {
|
||||
token: session.token,
|
||||
token_type: 'Bearer',
|
||||
expires_at: session.expiresAt.toISOString(),
|
||||
user: toUserResponse(session.user),
|
||||
};
|
||||
}
|
||||
|
||||
@Delete('current')
|
||||
@HttpCode(204)
|
||||
@UseGuards(AuthGuard)
|
||||
async revoke(@Req() request: FastifyRequest): Promise<void> {
|
||||
await this.auth.revoke(request.sessionTokenHash!);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
const BEARER_CHALLENGE = 'Bearer realm="messenger"';
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(private readonly auth: AuthService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<FastifyRequest>();
|
||||
const match = /^Bearer (\S+)$/i.exec(request.headers.authorization ?? '');
|
||||
const session = match ? await this.auth.resolve(match[1]) : null;
|
||||
if (!session) {
|
||||
throw new ApiError('unauthorized', 'missing or invalid session', {
|
||||
'WWW-Authenticate': BEARER_CHALLENGE,
|
||||
});
|
||||
}
|
||||
request.currentUser = session.user;
|
||||
request.sessionTokenHash = session.tokenHash;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthGuard } from './auth.guard';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, AuthGuard],
|
||||
exports: [AuthService, AuthGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { createHash, randomBytes } from 'crypto';
|
||||
import { CacheService } from '../cache/cache.service';
|
||||
import { codePointLength } from '../common/dto/code-point-length.validator';
|
||||
import { User } from '../common/domain';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { PrismaService } from '../db/prisma.service';
|
||||
import { toUser } from '../users/users.service';
|
||||
import { verifyPassword } from './password';
|
||||
|
||||
const BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"';
|
||||
const USERNAME_PATTERN = /^[a-z0-9_]{3,32}$/;
|
||||
const CACHE_TTL_MS = 60_000;
|
||||
const REVOKED = 'revoked';
|
||||
|
||||
interface CachedSession {
|
||||
user: User;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export interface CreatedSession {
|
||||
token: string;
|
||||
expiresAt: Date;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface ResolvedSession {
|
||||
tokenHash: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private readonly ttlSeconds = readSessionTtl();
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly cache: CacheService,
|
||||
) {}
|
||||
|
||||
async login(authorization: string | undefined): Promise<CreatedSession> {
|
||||
const credentials = parseBasic(authorization);
|
||||
if (!credentials) {
|
||||
throw invalidCredentials();
|
||||
}
|
||||
const row = await this.prisma.user.findUnique({
|
||||
where: { username: credentials.username },
|
||||
});
|
||||
const valid = await verifyPassword(
|
||||
row?.passwordHash ?? null,
|
||||
credentials.password,
|
||||
);
|
||||
if (!row || !valid) {
|
||||
throw invalidCredentials();
|
||||
}
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const expiresAt = new Date(Date.now() + this.ttlSeconds * 1000);
|
||||
await this.prisma.session.create({
|
||||
data: { tokenHash: hashToken(token), userId: row.id, expiresAt },
|
||||
});
|
||||
return { token, expiresAt, user: toUser(row) };
|
||||
}
|
||||
|
||||
async resolve(token: string): Promise<ResolvedSession | null> {
|
||||
const tokenHash = hashToken(token);
|
||||
const key = cacheKey(tokenHash);
|
||||
const cached = await this.cache.get(key);
|
||||
if (cached === REVOKED) {
|
||||
return null;
|
||||
}
|
||||
if (cached) {
|
||||
const entry = JSON.parse(cached) as CachedSession;
|
||||
if (entry.expiresAt > Date.now()) {
|
||||
return { tokenHash, user: entry.user };
|
||||
}
|
||||
}
|
||||
const session = await this.prisma.session.findUnique({
|
||||
where: { tokenHash },
|
||||
include: { user: true },
|
||||
});
|
||||
const remainingMs = session
|
||||
? session.expiresAt.getTime() - Date.now()
|
||||
: 0;
|
||||
if (!session || remainingMs <= 0) {
|
||||
return null;
|
||||
}
|
||||
const user = toUser(session.user);
|
||||
const entry: CachedSession = {
|
||||
user,
|
||||
expiresAt: session.expiresAt.getTime(),
|
||||
};
|
||||
await this.cache.set(
|
||||
key,
|
||||
JSON.stringify(entry),
|
||||
Math.min(remainingMs, CACHE_TTL_MS),
|
||||
true,
|
||||
);
|
||||
return { tokenHash, user };
|
||||
}
|
||||
|
||||
async revoke(tokenHash: string): Promise<void> {
|
||||
const marked = await this.cache.setStrict(
|
||||
cacheKey(tokenHash),
|
||||
REVOKED,
|
||||
CACHE_TTL_MS,
|
||||
);
|
||||
if (!marked) {
|
||||
throw new ApiError('unavailable', 'session cache unavailable');
|
||||
}
|
||||
await this.prisma.session.deleteMany({ where: { tokenHash } });
|
||||
}
|
||||
}
|
||||
|
||||
function cacheKey(tokenHash: string): string {
|
||||
return `session:v1:${tokenHash}`;
|
||||
}
|
||||
|
||||
function parseBasic(
|
||||
header: string | undefined,
|
||||
): { username: string; password: string } | null {
|
||||
const match = /^Basic ([A-Za-z0-9+/]+={0,2})$/i.exec(header ?? '');
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
const decoded = Buffer.from(match[1], 'base64').toString('utf8');
|
||||
const separator = decoded.indexOf(':');
|
||||
if (separator < 0) {
|
||||
return null;
|
||||
}
|
||||
const username = decoded.slice(0, separator);
|
||||
const password = decoded.slice(separator + 1);
|
||||
const length = codePointLength(password);
|
||||
if (!USERNAME_PATTERN.test(username) || length < 12 || length > 128) {
|
||||
return null;
|
||||
}
|
||||
return { username, password };
|
||||
}
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
function invalidCredentials(): ApiError {
|
||||
return new ApiError('unauthorized', 'invalid credentials', {
|
||||
'WWW-Authenticate': BASIC_CHALLENGE,
|
||||
});
|
||||
}
|
||||
|
||||
function readSessionTtl(): number {
|
||||
const ttl = Number(process.env.SESSION_TTL_SECONDS ?? 3600);
|
||||
if (!Number.isInteger(ttl) || ttl <= 0) {
|
||||
throw new Error('SESSION_TTL_SECONDS must be a positive integer');
|
||||
}
|
||||
return ttl;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { User } from '../common/domain';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
currentUser?: User;
|
||||
sessionTokenHash?: string;
|
||||
}
|
||||
}
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): User => {
|
||||
const request = ctx.switchToHttp().getRequest<FastifyRequest>();
|
||||
if (!request.currentUser) {
|
||||
throw new Error('CurrentUser used without AuthGuard');
|
||||
}
|
||||
return request.currentUser;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
import { argon2id, hash, verify } from 'argon2';
|
||||
|
||||
const OPTIONS = { type: argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 };
|
||||
|
||||
const dummyHash = hash('timing-equalizer-password', OPTIONS);
|
||||
|
||||
export function hashPassword(password: string): Promise<string> {
|
||||
return hash(password, OPTIONS);
|
||||
}
|
||||
|
||||
export async function verifyPassword(
|
||||
passwordHash: string | null,
|
||||
password: string,
|
||||
): Promise<boolean> {
|
||||
const valid = await verify(passwordHash ?? (await dummyHash), password);
|
||||
return passwordHash !== null && valid;
|
||||
}
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { CacheService } from './cache.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [CacheService],
|
||||
exports: [CacheService],
|
||||
})
|
||||
export class CacheModule {}
|
||||
Vendored
+98
@@ -0,0 +1,98 @@
|
||||
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
|
||||
import { readFileSync } from 'fs';
|
||||
import Redis from 'ioredis';
|
||||
|
||||
@Injectable()
|
||||
export class CacheService implements OnModuleDestroy {
|
||||
private readonly logger = new Logger('CacheService');
|
||||
private readonly client: Redis | null;
|
||||
private trusted = false;
|
||||
|
||||
constructor() {
|
||||
const url = readCacheUrl();
|
||||
this.client = url
|
||||
? new Redis(url, {
|
||||
enableOfflineQueue: false,
|
||||
maxRetriesPerRequest: 0,
|
||||
connectTimeout: 1000,
|
||||
commandTimeout: 200,
|
||||
})
|
||||
: null;
|
||||
this.client?.on('error', (error) =>
|
||||
this.logger.warn(`redis unavailable: ${error.message}`),
|
||||
);
|
||||
this.client?.on('close', () => {
|
||||
this.trusted = false;
|
||||
});
|
||||
this.client?.on('ready', () => {
|
||||
this.client!.flushdb().then(
|
||||
() => {
|
||||
this.trusted = true;
|
||||
},
|
||||
() => this.distrust(),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async get(key: string): Promise<string | null> {
|
||||
if (!this.client || !this.trusted) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return await this.client.get(key);
|
||||
} catch {
|
||||
this.distrust();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async set(
|
||||
key: string,
|
||||
value: string,
|
||||
ttlMs: number,
|
||||
onlyIfAbsent = false,
|
||||
): Promise<void> {
|
||||
if (!this.client || !this.trusted) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (onlyIfAbsent) {
|
||||
await this.client.set(key, value, 'PX', ttlMs, 'NX');
|
||||
} else {
|
||||
await this.client.set(key, value, 'PX', ttlMs);
|
||||
}
|
||||
} catch {
|
||||
this.distrust();
|
||||
}
|
||||
}
|
||||
|
||||
async setStrict(key: string, value: string, ttlMs: number): Promise<boolean> {
|
||||
if (!this.client) {
|
||||
return true;
|
||||
}
|
||||
if (!this.trusted) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await this.client.set(key, value, 'PX', ttlMs);
|
||||
return true;
|
||||
} catch {
|
||||
this.distrust();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
onModuleDestroy(): void {
|
||||
this.client?.disconnect();
|
||||
}
|
||||
|
||||
private distrust(): void {
|
||||
this.trusted = false;
|
||||
this.client?.disconnect(true);
|
||||
}
|
||||
}
|
||||
|
||||
function readCacheUrl(): string | undefined {
|
||||
const file = process.env.CACHE_URL_FILE;
|
||||
return file ? readFileSync(file, 'utf8').trim() : process.env.CACHE_URL;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '../auth/auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
|
||||
import { User } from '../common/domain';
|
||||
import { ChatsService } from './chats.service';
|
||||
import {
|
||||
ChatPageResponse,
|
||||
ChatResponse,
|
||||
toChatResponse,
|
||||
} from './dto/chat.response';
|
||||
import { CreateChatDto } from './dto/create-chat.dto';
|
||||
|
||||
@Controller('api/v1/chats')
|
||||
@UseGuards(AuthGuard)
|
||||
export class ChatsController {
|
||||
constructor(private readonly chats: ChatsService) {}
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
async create(
|
||||
@Body() dto: CreateChatDto,
|
||||
@CurrentUser() user: User,
|
||||
): Promise<ChatResponse> {
|
||||
const chat = await this.chats.create(dto.title, dto.member_ids, user.id);
|
||||
return toChatResponse(chat);
|
||||
}
|
||||
|
||||
@Get()
|
||||
async list(
|
||||
@CurrentUser() user: User,
|
||||
@Query('limit') limitRaw: unknown,
|
||||
@Query('cursor') cursorRaw: unknown,
|
||||
): Promise<ChatPageResponse> {
|
||||
const limit = parseLimit(limitRaw);
|
||||
const cursor = rawCursorParam(cursorRaw);
|
||||
return this.chats.listForMember(user.id, limit, cursor);
|
||||
}
|
||||
|
||||
@Get(':chatId')
|
||||
async getOne(
|
||||
@Param('chatId') chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
): Promise<ChatResponse> {
|
||||
const chat = await this.chats.getForMember(chatId, user.id);
|
||||
return toChatResponse(chat);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ChatsController } from './chats.controller';
|
||||
import { ChatsService } from './chats.service';
|
||||
|
||||
@Module({
|
||||
controllers: [ChatsController],
|
||||
providers: [ChatsService],
|
||||
exports: [ChatsService],
|
||||
})
|
||||
export class ChatsModule {}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { decodeChatCursor, encodeChatCursor } from '../common/cursor';
|
||||
import { Chat } from '../common/domain';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { validate as isUuid } from '../common/uuid';
|
||||
import { PrismaService, isForeignKeyViolation } from '../db/prisma.service';
|
||||
import { ChatPageResponse, toChatResponse } from './dto/chat.response';
|
||||
|
||||
interface ChatRow {
|
||||
id: string;
|
||||
title: string;
|
||||
createdAt: Date;
|
||||
memberIds: string[];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ChatsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async create(
|
||||
title: string,
|
||||
rawMemberIds: string[],
|
||||
callerId: string,
|
||||
): Promise<Chat> {
|
||||
const invalid = rawMemberIds.find((id) => !isUuid(id));
|
||||
if (invalid) {
|
||||
throw new ApiError('invalid_request', `unknown member_id: ${invalid}`);
|
||||
}
|
||||
const memberIds = rawMemberIds.map((id) => id.toLowerCase());
|
||||
if (new Set(memberIds).size !== memberIds.length) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
"All member_ids's elements must be unique",
|
||||
);
|
||||
}
|
||||
if (!memberIds.includes(callerId)) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'member_ids must include the caller',
|
||||
);
|
||||
}
|
||||
try {
|
||||
const chat = await this.prisma.$transaction(async (tx) => {
|
||||
const created = await tx.chat.create({
|
||||
data: { title: title.trim() },
|
||||
});
|
||||
await tx.chatMember.createMany({
|
||||
data: memberIds.map((userId) => ({
|
||||
chatId: created.id,
|
||||
userId,
|
||||
})),
|
||||
});
|
||||
return created;
|
||||
});
|
||||
return toChat({ ...chat, memberIds });
|
||||
} catch (error) {
|
||||
if (isForeignKeyViolation(error)) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'member_ids contain an unknown user',
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getForMember(chatId: string, callerId: string): Promise<Chat> {
|
||||
if (!isUuid(chatId)) {
|
||||
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
||||
}
|
||||
const chat = await this.prisma.chat.findFirst({
|
||||
where: { id: chatId, members: { some: { userId: callerId } } },
|
||||
include: { members: { select: { userId: true } } },
|
||||
});
|
||||
if (!chat) {
|
||||
throw new ApiError('not_found', 'chat not found');
|
||||
}
|
||||
return toChat({
|
||||
...chat,
|
||||
memberIds: chat.members.map((m) => m.userId),
|
||||
});
|
||||
}
|
||||
|
||||
async listForMember(
|
||||
callerId: string,
|
||||
limit: number,
|
||||
rawCursor: string | null,
|
||||
): Promise<ChatPageResponse> {
|
||||
let after = Prisma.empty;
|
||||
if (rawCursor !== null) {
|
||||
const cursor = decodeChatCursor(rawCursor);
|
||||
const member = cursor
|
||||
? await this.prisma.chatMember.findUnique({
|
||||
where: {
|
||||
chatId_userId: { chatId: cursor.id, userId: callerId },
|
||||
},
|
||||
include: { chat: { select: { createdAt: true } } },
|
||||
})
|
||||
: null;
|
||||
if (!member) {
|
||||
throw new ApiError('invalid_request', 'invalid cursor');
|
||||
}
|
||||
after = Prisma.sql`AND (c.created_at, c.id) > (${member.chat.createdAt}::timestamptz, ${member.chatId}::uuid)`;
|
||||
}
|
||||
const rows = await this.prisma.$queryRaw<ChatRow[]>`
|
||||
SELECT c.id, c.title, c.created_at AS "createdAt",
|
||||
ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id = c.id) AS "memberIds"
|
||||
FROM chat_members cm
|
||||
JOIN chats c ON c.id = cm.chat_id
|
||||
WHERE cm.user_id = ${callerId}::uuid ${after}
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT ${limit + 1}`;
|
||||
const items = rows.slice(0, limit).map(toChat);
|
||||
const last = items[items.length - 1];
|
||||
return {
|
||||
items: items.map(toChatResponse),
|
||||
next_cursor:
|
||||
rows.length > limit ? encodeChatCursor({ id: last.id }) : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function toChat(row: ChatRow): Chat {
|
||||
return {
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
memberIds: row.memberIds,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Chat } from '../../common/domain';
|
||||
|
||||
export interface ChatResponse {
|
||||
id: string;
|
||||
title: string;
|
||||
member_ids: string[];
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ChatPageResponse {
|
||||
items: ChatResponse[];
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
export function toChatResponse(chat: Chat): ChatResponse {
|
||||
return {
|
||||
id: chat.id,
|
||||
title: chat.title,
|
||||
member_ids: chat.memberIds,
|
||||
created_at: chat.createdAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
ArrayMinSize,
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsString,
|
||||
} from 'class-validator';
|
||||
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||
import { NotBlank } from '../../common/dto/not-blank.validator';
|
||||
|
||||
export class CreateChatDto {
|
||||
@NotBlank()
|
||||
@CodePointLength(1, 100)
|
||||
title!: string;
|
||||
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ArrayMaxSize(100)
|
||||
@ArrayUnique()
|
||||
@IsString({ each: true })
|
||||
member_ids!: string[];
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { validate as isUuid } from './uuid';
|
||||
|
||||
export interface ChatCursor {
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface MessageCursor {
|
||||
chatId: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export function encodeChatCursor(cursor: ChatCursor): string {
|
||||
return encode(cursor);
|
||||
}
|
||||
|
||||
export function decodeChatCursor(raw: string): ChatCursor | null {
|
||||
const decoded = decode(raw);
|
||||
return decoded && isUuidField(decoded.id) ? { id: decoded.id } : null;
|
||||
}
|
||||
|
||||
export function encodeMessageCursor(cursor: MessageCursor): string {
|
||||
return encode(cursor);
|
||||
}
|
||||
|
||||
export function decodeMessageCursor(raw: string): MessageCursor | null {
|
||||
const decoded = decode(raw);
|
||||
return decoded && isUuidField(decoded.chatId) && isUuidField(decoded.id)
|
||||
? { chatId: decoded.chatId, id: decoded.id }
|
||||
: null;
|
||||
}
|
||||
|
||||
function isUuidField(value: unknown): value is string {
|
||||
return typeof value === 'string' && isUuid(value);
|
||||
}
|
||||
|
||||
function encode(value: object): string {
|
||||
return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url');
|
||||
}
|
||||
|
||||
function decode(raw: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const parsed = JSON.parse(
|
||||
Buffer.from(raw, 'base64url').toString('utf8'),
|
||||
);
|
||||
return typeof parsed === 'object' && parsed !== null ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
displayName: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface Chat {
|
||||
id: string;
|
||||
title: string;
|
||||
memberIds: string[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id: string;
|
||||
chatId: string;
|
||||
senderId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { registerDecorator, ValidationOptions } from 'class-validator';
|
||||
|
||||
export function codePointLength(value: string): number {
|
||||
return [...value].length;
|
||||
}
|
||||
|
||||
export function CodePointLength(
|
||||
min: number,
|
||||
max: number,
|
||||
options?: ValidationOptions,
|
||||
) {
|
||||
return function (object: object, propertyName: string) {
|
||||
registerDecorator({
|
||||
name: 'codePointLength',
|
||||
target: object.constructor,
|
||||
propertyName,
|
||||
constraints: [min, max],
|
||||
options,
|
||||
validator: {
|
||||
validate(value: unknown): boolean {
|
||||
if (typeof value !== 'string') {
|
||||
return false;
|
||||
}
|
||||
const length = codePointLength(value);
|
||||
return length >= min && length <= max;
|
||||
},
|
||||
defaultMessage(): string {
|
||||
return `${propertyName} must be between ${min} and ${max} Unicode code points`;
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { registerDecorator, ValidationOptions } from 'class-validator';
|
||||
|
||||
export function NotBlank(options?: ValidationOptions) {
|
||||
return function (object: object, propertyName: string) {
|
||||
registerDecorator({
|
||||
name: 'notBlank',
|
||||
target: object.constructor,
|
||||
propertyName,
|
||||
options,
|
||||
validator: {
|
||||
validate(value: unknown): boolean {
|
||||
return typeof value === 'string' && value.trim().length > 0;
|
||||
},
|
||||
defaultMessage(): string {
|
||||
return `${propertyName} must not be empty or whitespace-only`;
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { ApiError } from '../filters/api-error';
|
||||
|
||||
const DEFAULT_LIMIT = 50;
|
||||
const MIN_LIMIT = 1;
|
||||
const MAX_LIMIT = 100;
|
||||
|
||||
export function parseLimit(raw: unknown): number {
|
||||
if (raw === undefined) {
|
||||
return DEFAULT_LIMIT;
|
||||
}
|
||||
if (typeof raw !== 'string' || !/^\d+$/.test(raw)) {
|
||||
throw new ApiError('invalid_request', 'limit must be an integer');
|
||||
}
|
||||
const limit = Number(raw);
|
||||
if (limit < MIN_LIMIT || limit > MAX_LIMIT) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
`limit must be between ${MIN_LIMIT} and ${MAX_LIMIT}`,
|
||||
);
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
|
||||
export function rawCursorParam(raw: unknown): string | null {
|
||||
if (raw === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (typeof raw !== 'string' || raw.length === 0) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'cursor must be a non-empty string',
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
|
||||
export type ErrorCode =
|
||||
| 'invalid_request'
|
||||
| 'unauthorized'
|
||||
| 'not_found'
|
||||
| 'conflict'
|
||||
| 'payload_too_large'
|
||||
| 'unsupported_media_type'
|
||||
| 'rate_limited'
|
||||
| 'unavailable'
|
||||
| 'internal_error';
|
||||
|
||||
const STATUS_BY_CODE: Record<ErrorCode, number> = {
|
||||
invalid_request: HttpStatus.BAD_REQUEST,
|
||||
unauthorized: HttpStatus.UNAUTHORIZED,
|
||||
not_found: HttpStatus.NOT_FOUND,
|
||||
conflict: HttpStatus.CONFLICT,
|
||||
payload_too_large: HttpStatus.PAYLOAD_TOO_LARGE,
|
||||
unsupported_media_type: HttpStatus.UNSUPPORTED_MEDIA_TYPE,
|
||||
rate_limited: HttpStatus.TOO_MANY_REQUESTS,
|
||||
unavailable: HttpStatus.SERVICE_UNAVAILABLE,
|
||||
internal_error: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
|
||||
export class ApiError extends HttpException {
|
||||
constructor(
|
||||
public readonly code: ErrorCode,
|
||||
message: string,
|
||||
public readonly headers: Record<string, string> = {},
|
||||
) {
|
||||
super(message, STATUS_BY_CODE[code]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { isDatabaseUnavailable } from '../../db/prisma.service';
|
||||
import { ApiError, ErrorCode } from './api-error';
|
||||
|
||||
const CODE_BY_STATUS: Partial<Record<number, ErrorCode>> = {
|
||||
[HttpStatus.BAD_REQUEST]: 'invalid_request',
|
||||
[HttpStatus.UNAUTHORIZED]: 'unauthorized',
|
||||
[HttpStatus.NOT_FOUND]: 'not_found',
|
||||
[HttpStatus.CONFLICT]: 'conflict',
|
||||
[HttpStatus.PAYLOAD_TOO_LARGE]: 'payload_too_large',
|
||||
[HttpStatus.UNSUPPORTED_MEDIA_TYPE]: 'unsupported_media_type',
|
||||
[HttpStatus.TOO_MANY_REQUESTS]: 'rate_limited',
|
||||
[HttpStatus.SERVICE_UNAVAILABLE]: 'unavailable',
|
||||
};
|
||||
|
||||
interface Resolved {
|
||||
status: number;
|
||||
code: ErrorCode;
|
||||
message: string;
|
||||
}
|
||||
|
||||
@Catch()
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger('HttpExceptionFilter');
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost): void {
|
||||
const ctx = host.switchToHttp();
|
||||
const reply = ctx.getResponse<FastifyReply>();
|
||||
const request = ctx.getRequest<FastifyRequest>();
|
||||
const requestId = request.requestId;
|
||||
|
||||
const { status, code, message } = this.resolve(exception);
|
||||
if (status >= 500) {
|
||||
this.logger.error(
|
||||
`${request.method} ${request.url} -> ${status}: ${message}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (exception instanceof ApiError) {
|
||||
reply.headers(exception.headers);
|
||||
}
|
||||
reply
|
||||
.code(status)
|
||||
.header('x-request-id', requestId)
|
||||
.send({ error: { code, message, request_id: requestId } });
|
||||
}
|
||||
|
||||
private resolve(exception: unknown): Resolved {
|
||||
if (exception instanceof ApiError) {
|
||||
return {
|
||||
status: exception.getStatus(),
|
||||
code: exception.code,
|
||||
message: exception.message,
|
||||
};
|
||||
}
|
||||
if (exception instanceof HttpException) {
|
||||
const status = exception.getStatus();
|
||||
const code = CODE_BY_STATUS[status] ?? 'internal_error';
|
||||
const message =
|
||||
extractMessage(exception.getResponse()) ?? exception.message;
|
||||
return { status, code, message };
|
||||
}
|
||||
const fastifyStatus = (exception as { statusCode?: unknown })
|
||||
?.statusCode;
|
||||
if (typeof fastifyStatus === 'number' && CODE_BY_STATUS[fastifyStatus]) {
|
||||
const message =
|
||||
exception instanceof Error ? exception.message : 'Invalid request';
|
||||
return {
|
||||
status: fastifyStatus,
|
||||
code: CODE_BY_STATUS[fastifyStatus]!,
|
||||
message,
|
||||
};
|
||||
}
|
||||
if (isDatabaseUnavailable(exception)) {
|
||||
return {
|
||||
status: 503,
|
||||
code: 'unavailable',
|
||||
message: 'database unavailable',
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: 500,
|
||||
code: 'internal_error',
|
||||
message: 'Internal server error',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function extractMessage(response: unknown): string | null {
|
||||
if (typeof response === 'string') {
|
||||
return response;
|
||||
}
|
||||
if (
|
||||
typeof response === 'object' &&
|
||||
response !== null &&
|
||||
'message' in response
|
||||
) {
|
||||
const value = (response as { message: unknown }).message;
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
if (Array.isArray(value) && value.every((v) => typeof v === 'string')) {
|
||||
return value.join('; ');
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import { hostname } from 'os';
|
||||
|
||||
const REQUEST_ID_HEADER = 'x-request-id';
|
||||
const INSTANCE_ID_HEADER = 'x-instance-id';
|
||||
|
||||
export const INSTANCE_ID = process.env.INSTANCE_ID ?? hostname();
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
requestId: string;
|
||||
}
|
||||
}
|
||||
|
||||
export function registerRequestId(instance: FastifyInstance): void {
|
||||
instance.addHook('onRequest', (request: FastifyRequest, reply, done) => {
|
||||
request.requestId = randomUUID();
|
||||
reply.header(REQUEST_ID_HEADER, request.requestId);
|
||||
reply.header(INSTANCE_ID_HEADER, INSTANCE_ID);
|
||||
done();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
const UUID_PATTERN =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
export function validate(value: string): boolean {
|
||||
return UUID_PATTERN.test(value);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
|
||||
import { registerRequestId } from './common/interceptors/request-id';
|
||||
|
||||
export function configureApp(app: NestFastifyApplication): void {
|
||||
registerRequestId(app.getHttpAdapter().getInstance());
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
forbidUnknownValues: true,
|
||||
}),
|
||||
);
|
||||
app.useGlobalFilters(new HttpExceptionFilter());
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class DbModule {}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Injectable, OnModuleDestroy } from '@nestjs/common';
|
||||
import { Prisma, PrismaClient } from '@prisma/client';
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
const UNAVAILABLE_CODES = new Set(['P1001', 'P1002', 'P1008', 'P1017', 'P2024']);
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleDestroy {
|
||||
constructor() {
|
||||
super({ datasourceUrl: readDatabaseUrl() });
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
function readDatabaseUrl(): string {
|
||||
const file = process.env.DATABASE_URL_FILE;
|
||||
const url = file ? readFileSync(file, 'utf8').trim() : process.env.DATABASE_URL;
|
||||
if (!url) {
|
||||
throw new Error('DATABASE_URL_FILE or DATABASE_URL must be set');
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export function isUniqueViolation(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
error.code === 'P2002'
|
||||
);
|
||||
}
|
||||
|
||||
export function isForeignKeyViolation(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
error.code === 'P2003'
|
||||
);
|
||||
}
|
||||
|
||||
export function isDatabaseUnavailable(error: unknown): boolean {
|
||||
if (error instanceof Prisma.PrismaClientInitializationError) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
UNAVAILABLE_CODES.has(error.code)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
const ALICE_ID = '11111111-1111-4111-8111-111111111111';
|
||||
const BOB_ID = '22222222-2222-4222-8222-222222222222';
|
||||
const CHAT_ID = '33333333-3333-4333-8333-333333333333';
|
||||
const MESSAGE_ID = '44444444-4444-4444-8444-444444444444';
|
||||
const CURSOR =
|
||||
'eyJjaGF0SWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJpZCI6IjQ0NDQ0NDQ0LTQ0NDQtNDQ0NC04NDQ0LTQ0NDQ0NDQ0NDQ0NCJ9';
|
||||
|
||||
const ALICE = {
|
||||
id: ALICE_ID,
|
||||
username: 'alice',
|
||||
display_name: 'Алиса',
|
||||
created_at: '2026-09-01T12:00:00.000Z',
|
||||
};
|
||||
|
||||
const CHAT = {
|
||||
id: CHAT_ID,
|
||||
title: 'Проект по ВНП',
|
||||
member_ids: [ALICE_ID, BOB_ID],
|
||||
created_at: '2026-09-01T12:01:00.000Z',
|
||||
};
|
||||
|
||||
const MESSAGE = {
|
||||
id: MESSAGE_ID,
|
||||
chat_id: CHAT_ID,
|
||||
sender_id: ALICE_ID,
|
||||
text: 'Привет, Боб! 👋',
|
||||
created_at: '2026-09-01T12:02:00.000Z',
|
||||
};
|
||||
|
||||
export interface Example {
|
||||
summary: string;
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
export interface OperationExamples {
|
||||
request?: Record<string, Example>;
|
||||
responses: Record<string, Record<string, Example>>;
|
||||
}
|
||||
|
||||
function example(summary: string, value: unknown): Example {
|
||||
return { summary, value };
|
||||
}
|
||||
|
||||
function error(code: string, message: string): unknown {
|
||||
return {
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
request_id: '9b2c6f1e-5d4a-4c3b-8a2f-1e0d9c8b7a6f',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const UNAUTHORIZED = {
|
||||
missing: example(
|
||||
'Нет/неверный/истёкший/отозванный Bearer-токен',
|
||||
error('unauthorized', 'missing or invalid session'),
|
||||
),
|
||||
};
|
||||
|
||||
const UNAVAILABLE = {
|
||||
database: example(
|
||||
'PostgreSQL недоступен',
|
||||
error('unavailable', 'database unavailable'),
|
||||
),
|
||||
};
|
||||
|
||||
const CHAT_NOT_FOUND = {
|
||||
notFound: example(
|
||||
'Чата нет или вызывающий не участник (не 403)',
|
||||
error('not_found', 'chat not found'),
|
||||
),
|
||||
};
|
||||
|
||||
const INVALID_CHAT_ID = example(
|
||||
'chat_id не UUID',
|
||||
error('invalid_request', 'chatId must be a valid UUID'),
|
||||
);
|
||||
|
||||
export const GUIDE = `
|
||||
Учебный мессенджер, лабораторная 3: PostgreSQL, сессии, Redis-кэш сессий.
|
||||
Документ — обязательный контракт \`contracts/openapi.json\`, дополненный примерами запросов и ответов.
|
||||
|
||||
**Как пройти сценарий в Swagger UI**
|
||||
|
||||
1. \`POST /api/v1/users\` — зарегистрируйте пользователей (примеры alice, bob, eve в списке Examples). Повторная регистрация того же username — 409, меняйте username.
|
||||
2. **Authorize → basicAuth**: username и password из шага 1 → \`POST /api/v1/auth/sessions\` → скопируйте \`token\`.
|
||||
3. **Authorize → bearerAuth**: вставьте token (без слова Bearer). Basic отправляется только на вход, остальные запросы идут с Bearer.
|
||||
4. \`GET /api/v1/users/me\` — свой id; id второго участника — из ответа его регистрации.
|
||||
5. \`POST /api/v1/chats\` с \`member_ids\` = [свой id, id собеседника] → \`chat_id\`.
|
||||
6. \`POST /api/v1/chats/{chat_id}/messages\` с заголовком \`Idempotency-Key\` (любая строка из \`A-Za-z0-9._:-\`, до 128 символов). Повтор с тем же ключом и телом вернёт то же сообщение, с другим телом — 409. Затем \`GET …/messages?limit=1\` и следующая страница с \`cursor\` = \`next_cursor\`.
|
||||
7. Чтобы действовать от другого пользователя: Logout в Authorize, вход им и новый token.
|
||||
8. \`DELETE /api/v1/auth/sessions/current\` — logout; тот же token дальше даёт 401.
|
||||
|
||||
Сессия живёт \`SESSION_TTL_SECONDS\` (по умолчанию 3600 с). Пароль — 12–128 символов Unicode, двоеточие допустимо.
|
||||
`;
|
||||
|
||||
export const OPERATION_EXAMPLES: Record<string, OperationExamples> = {
|
||||
'GET /health/live': {
|
||||
responses: {
|
||||
'200': { ok: example('Процесс жив', { status: 'ok' }) },
|
||||
},
|
||||
},
|
||||
'GET /health/ready': {
|
||||
responses: {
|
||||
'200': {
|
||||
ok: example('PostgreSQL доступен (Redis не критичен)', {
|
||||
status: 'ok',
|
||||
}),
|
||||
},
|
||||
'503': UNAVAILABLE,
|
||||
},
|
||||
},
|
||||
'POST /api/v1/users': {
|
||||
request: {
|
||||
alice: example('Алиса', {
|
||||
username: 'alice',
|
||||
display_name: 'Алиса',
|
||||
password: 'Alice-password-123',
|
||||
}),
|
||||
bob: example('Боб', {
|
||||
username: 'bob',
|
||||
display_name: 'Боб',
|
||||
password: 'Bob-password-123',
|
||||
}),
|
||||
eve: example('Ева (посторонняя)', {
|
||||
username: 'eve',
|
||||
display_name: 'Ева',
|
||||
password: 'Eve-password-123',
|
||||
}),
|
||||
colon: example('Пароль с двоеточием и эмодзи', {
|
||||
username: 'carol',
|
||||
display_name: 'Кэрол 🌸',
|
||||
password: 'пароль:с:двоеточием🔑',
|
||||
}),
|
||||
},
|
||||
responses: {
|
||||
'201': { created: example('Пользователь создан', ALICE) },
|
||||
'400': {
|
||||
username: example(
|
||||
'username не соответствует [a-z0-9_]{3,32}',
|
||||
error('invalid_request', 'username must match [a-z0-9_]{3,32}'),
|
||||
),
|
||||
password: example(
|
||||
'password короче 12 символов',
|
||||
error(
|
||||
'invalid_request',
|
||||
'password must be between 12 and 128 Unicode code points',
|
||||
),
|
||||
),
|
||||
extra: example(
|
||||
'Лишнее поле в JSON',
|
||||
error('invalid_request', 'property extra should not exist'),
|
||||
),
|
||||
},
|
||||
'409': {
|
||||
taken: example(
|
||||
'username уже занят',
|
||||
error('conflict', 'username is already taken'),
|
||||
),
|
||||
},
|
||||
'503': UNAVAILABLE,
|
||||
},
|
||||
},
|
||||
'POST /api/v1/auth/sessions': {
|
||||
responses: {
|
||||
'201': {
|
||||
created: example('Сессия создана', {
|
||||
token: 'q8Hn3vXl0ZbJ7mWcY2sRkT5uPaE9dFgVhN1oLxI4w6A',
|
||||
token_type: 'Bearer',
|
||||
expires_at: '2026-09-01T13:00:00.000Z',
|
||||
user: ALICE,
|
||||
}),
|
||||
},
|
||||
'401': {
|
||||
invalid: example(
|
||||
'Неверный пароль, неизвестный пользователь или нет Basic — ответ одинаковый',
|
||||
error('unauthorized', 'invalid credentials'),
|
||||
),
|
||||
},
|
||||
'503': UNAVAILABLE,
|
||||
},
|
||||
},
|
||||
'DELETE /api/v1/auth/sessions/current': {
|
||||
responses: {
|
||||
'401': UNAUTHORIZED,
|
||||
'503': {
|
||||
...UNAVAILABLE,
|
||||
cache: example(
|
||||
'Redis недоступен — отзыв не выполнен, повторите позже',
|
||||
error('unavailable', 'session cache unavailable'),
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
'GET /api/v1/users/me': {
|
||||
responses: {
|
||||
'200': { me: example('Текущий пользователь из сессии', ALICE) },
|
||||
'401': UNAUTHORIZED,
|
||||
'503': UNAVAILABLE,
|
||||
},
|
||||
},
|
||||
'POST /api/v1/chats': {
|
||||
request: {
|
||||
pair: example('Чат Алисы и Боба', {
|
||||
title: CHAT.title,
|
||||
member_ids: CHAT.member_ids,
|
||||
}),
|
||||
solo: example('Чат только с собой', {
|
||||
title: 'Заметки',
|
||||
member_ids: [ALICE_ID],
|
||||
}),
|
||||
},
|
||||
responses: {
|
||||
'201': { created: example('Чат создан атомарно', CHAT) },
|
||||
'400': {
|
||||
noCaller: example(
|
||||
'Вызывающий не в member_ids',
|
||||
error('invalid_request', 'member_ids must include the caller'),
|
||||
),
|
||||
unknown: example(
|
||||
'Неизвестный участник — транзакция откатывается',
|
||||
error('invalid_request', 'member_ids contain an unknown user'),
|
||||
),
|
||||
duplicate: example(
|
||||
'Дубликаты в member_ids',
|
||||
error(
|
||||
'invalid_request',
|
||||
"All member_ids's elements must be unique",
|
||||
),
|
||||
),
|
||||
},
|
||||
'401': UNAUTHORIZED,
|
||||
'503': UNAVAILABLE,
|
||||
},
|
||||
},
|
||||
'GET /api/v1/chats': {
|
||||
responses: {
|
||||
'200': {
|
||||
page: example('Страница чатов с продолжением', {
|
||||
items: [CHAT],
|
||||
next_cursor: 'eyJpZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyJ9',
|
||||
}),
|
||||
last: example('Последняя страница', {
|
||||
items: [CHAT],
|
||||
next_cursor: null,
|
||||
}),
|
||||
},
|
||||
'400': {
|
||||
limit: example(
|
||||
'limit вне 1–100',
|
||||
error('invalid_request', 'limit must be between 1 and 100'),
|
||||
),
|
||||
cursor: example(
|
||||
'Испорченный или чужой cursor',
|
||||
error('invalid_request', 'invalid cursor'),
|
||||
),
|
||||
},
|
||||
'401': UNAUTHORIZED,
|
||||
'503': UNAVAILABLE,
|
||||
},
|
||||
},
|
||||
'GET /api/v1/chats/{chat_id}': {
|
||||
responses: {
|
||||
'200': { chat: example('Чат, где вызывающий — участник', CHAT) },
|
||||
'400': { chatId: INVALID_CHAT_ID },
|
||||
'401': UNAUTHORIZED,
|
||||
'404': CHAT_NOT_FOUND,
|
||||
'503': UNAVAILABLE,
|
||||
},
|
||||
},
|
||||
'POST /api/v1/chats/{chat_id}/messages': {
|
||||
request: {
|
||||
text: example('Обычное сообщение', { text: MESSAGE.text }),
|
||||
long: example('Максимум — 4000 символов Unicode', {
|
||||
text: 'Длинный текст…',
|
||||
}),
|
||||
},
|
||||
responses: {
|
||||
'201': {
|
||||
created: example('Отправитель берётся из сессии', MESSAGE),
|
||||
},
|
||||
'400': {
|
||||
blank: example(
|
||||
'Пустой или пробельный текст',
|
||||
error(
|
||||
'invalid_request',
|
||||
'text must not be empty or whitespace-only',
|
||||
),
|
||||
),
|
||||
sender: example(
|
||||
'sender_id в теле не принимается',
|
||||
error('invalid_request', 'property sender_id should not exist'),
|
||||
),
|
||||
chatId: INVALID_CHAT_ID,
|
||||
key: example(
|
||||
'Нет Idempotency-Key или неверный формат',
|
||||
error(
|
||||
'invalid_request',
|
||||
'Idempotency-Key header must match [A-Za-z0-9._:-]{1,128}',
|
||||
),
|
||||
),
|
||||
},
|
||||
'401': UNAUTHORIZED,
|
||||
'404': CHAT_NOT_FOUND,
|
||||
'409': {
|
||||
keyReused: example(
|
||||
'Тот же Idempotency-Key с другим телом',
|
||||
error(
|
||||
'conflict',
|
||||
'Idempotency-Key was already used with a different request',
|
||||
),
|
||||
),
|
||||
},
|
||||
'503': UNAVAILABLE,
|
||||
},
|
||||
},
|
||||
'GET /api/v1/chats/{chat_id}/messages': {
|
||||
responses: {
|
||||
'200': {
|
||||
page: example('Страница истории (limit=1) с cursor', {
|
||||
items: [MESSAGE],
|
||||
next_cursor: CURSOR,
|
||||
}),
|
||||
last: example('Последняя страница', {
|
||||
items: [MESSAGE],
|
||||
next_cursor: null,
|
||||
}),
|
||||
},
|
||||
'400': {
|
||||
otherChat: example(
|
||||
'cursor от другого чата',
|
||||
error('invalid_request', 'cursor belongs to a different chat'),
|
||||
),
|
||||
cursor: example(
|
||||
'Испорченный cursor или cursor несуществующего сообщения',
|
||||
error('invalid_request', 'invalid cursor'),
|
||||
),
|
||||
limit: example(
|
||||
'limit вне 1–100',
|
||||
error('invalid_request', 'limit must be between 1 and 100'),
|
||||
),
|
||||
},
|
||||
'401': UNAUTHORIZED,
|
||||
'404': CHAT_NOT_FOUND,
|
||||
'503': UNAVAILABLE,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
import { NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||
import { OpenAPIObject, SwaggerModule } from '@nestjs/swagger';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { GUIDE, OPERATION_EXAMPLES } from './examples';
|
||||
|
||||
const CONTRACT_PATH = join(process.cwd(), 'contracts', 'openapi.json');
|
||||
|
||||
export function setupSwagger(app: NestFastifyApplication): void {
|
||||
SwaggerModule.setup('docs', app, loadDocument(), {
|
||||
customSiteTitle: 'Messenger lab3 API',
|
||||
swaggerOptions: {
|
||||
persistAuthorization: true,
|
||||
displayRequestDuration: true,
|
||||
tryItOutEnabled: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function loadDocument(): OpenAPIObject {
|
||||
const document = JSON.parse(readFileSync(CONTRACT_PATH, 'utf8'));
|
||||
document.info.description = GUIDE;
|
||||
document.servers = [{ url: '/', description: 'Этот экземпляр API' }];
|
||||
for (const [key, examples] of Object.entries(OPERATION_EXAMPLES)) {
|
||||
const [method, path] = key.split(' ');
|
||||
const operation = document.paths[path]?.[method.toLowerCase()];
|
||||
if (!operation) {
|
||||
throw new Error(`examples for unknown operation ${key}`);
|
||||
}
|
||||
if (examples.request) {
|
||||
operation.requestBody.content['application/json'].examples =
|
||||
examples.request;
|
||||
}
|
||||
for (const [status, named] of Object.entries(examples.responses)) {
|
||||
const content = operation.responses[status]?.content;
|
||||
if (!content) {
|
||||
throw new Error(`examples for unknown response ${key} ${status}`);
|
||||
}
|
||||
content['application/json'].examples = named;
|
||||
}
|
||||
}
|
||||
return document;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { PrismaService } from '../db/prisma.service';
|
||||
import { isDraining } from './shutdown';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get('live')
|
||||
live(): { status: 'ok' } {
|
||||
return { status: 'ok' };
|
||||
}
|
||||
|
||||
@Get('ready')
|
||||
async ready(): Promise<{ status: 'ok' }> {
|
||||
if (isDraining()) {
|
||||
throw new ApiError('unavailable', 'shutting down');
|
||||
}
|
||||
try {
|
||||
await this.prisma.$queryRaw`SELECT 1`;
|
||||
} catch {
|
||||
throw new ApiError('unavailable', 'database unavailable');
|
||||
}
|
||||
return { status: 'ok' };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { INestApplication, Logger } from '@nestjs/common';
|
||||
|
||||
let draining = false;
|
||||
|
||||
export function isDraining(): boolean {
|
||||
return draining;
|
||||
}
|
||||
|
||||
export function enableGracefulShutdown(app: INestApplication): void {
|
||||
const delayMs = Number(process.env.SHUTDOWN_DELAY_MS ?? 3000);
|
||||
const shutdown = (signal: string): void => {
|
||||
if (draining) {
|
||||
return;
|
||||
}
|
||||
draining = true;
|
||||
Logger.log(`${signal}: readiness → 503, closing in ${delayMs} ms`, 'Shutdown');
|
||||
setTimeout(() => {
|
||||
app.close().then(
|
||||
() => process.exit(0),
|
||||
() => process.exit(1),
|
||||
);
|
||||
}, delayMs);
|
||||
};
|
||||
process.once('SIGTERM', () => shutdown('SIGTERM'));
|
||||
process.once('SIGINT', () => shutdown('SIGINT'));
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
} from '@nestjs/platform-fastify';
|
||||
import { AppModule } from './app.module';
|
||||
import { configureApp } from './configure-app';
|
||||
import { setupSwagger } from './docs/swagger';
|
||||
import { enableGracefulShutdown } from './health/shutdown';
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.create<NestFastifyApplication>(
|
||||
AppModule,
|
||||
new FastifyAdapter(),
|
||||
{
|
||||
bufferLogs: true,
|
||||
},
|
||||
);
|
||||
|
||||
configureApp(app);
|
||||
setupSwagger(app);
|
||||
enableGracefulShutdown(app);
|
||||
|
||||
const host = process.env.APP_HOST ?? '0.0.0.0';
|
||||
const port = Number(process.env.APP_PORT ?? 8080);
|
||||
await app.listen(port, host);
|
||||
Logger.log(`Listening on http://${host}:${port}`, 'Bootstrap');
|
||||
}
|
||||
|
||||
bootstrap().catch((error) => {
|
||||
Logger.error('Fatal error during bootstrap', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ArrayMaxSize, IsArray, IsString, ValidateIf } from 'class-validator';
|
||||
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||
|
||||
export class CreateMessageDto {
|
||||
@IsString()
|
||||
@CodePointLength(0, 4000)
|
||||
text!: string;
|
||||
|
||||
@ValidateIf((dto: CreateMessageDto) => dto.attachment_ids !== undefined)
|
||||
@IsArray()
|
||||
@ArrayMaxSize(0, { message: 'attachment_ids must be empty: attachments are not supported' })
|
||||
attachment_ids?: unknown[];
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Message } from '../../common/domain';
|
||||
|
||||
export interface MessageResponse {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface MessagePageResponse {
|
||||
items: MessageResponse[];
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
export function toMessageResponse(message: Message): MessageResponse {
|
||||
return {
|
||||
id: message.id,
|
||||
chat_id: message.chatId,
|
||||
sender_id: message.senderId,
|
||||
text: message.text,
|
||||
created_at: message.createdAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Headers,
|
||||
HttpCode,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '../auth/auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
|
||||
import { User } from '../common/domain';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { CreateMessageDto } from './dto/create-message.dto';
|
||||
import {
|
||||
MessagePageResponse,
|
||||
MessageResponse,
|
||||
toMessageResponse,
|
||||
} from './dto/message.response';
|
||||
import { MessagesService } from './messages.service';
|
||||
|
||||
@Controller('api/v1/chats/:chatId/messages')
|
||||
@UseGuards(AuthGuard)
|
||||
export class MessagesController {
|
||||
constructor(private readonly messages: MessagesService) {}
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
async create(
|
||||
@Param('chatId') chatId: string,
|
||||
@Body() dto: CreateMessageDto,
|
||||
@Headers('idempotency-key') keyRaw: unknown,
|
||||
@CurrentUser() user: User,
|
||||
): Promise<MessageResponse> {
|
||||
const key = parseIdempotencyKey(keyRaw);
|
||||
const message = await this.messages.create(chatId, user.id, dto.text, key);
|
||||
return toMessageResponse(message);
|
||||
}
|
||||
|
||||
@Get()
|
||||
async list(
|
||||
@Param('chatId') chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
@Query('limit') limitRaw: unknown,
|
||||
@Query('cursor') cursorRaw: unknown,
|
||||
): Promise<MessagePageResponse> {
|
||||
const limit = parseLimit(limitRaw);
|
||||
const cursor = rawCursorParam(cursorRaw);
|
||||
return this.messages.list(chatId, user.id, limit, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
function parseIdempotencyKey(raw: unknown): string {
|
||||
if (typeof raw !== 'string' || !/^[A-Za-z0-9._:-]{1,128}$/.test(raw)) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'Idempotency-Key header must match [A-Za-z0-9._:-]{1,128}',
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MessagesController } from './messages.controller';
|
||||
import { MessagesService } from './messages.service';
|
||||
|
||||
@Module({
|
||||
controllers: [MessagesController],
|
||||
providers: [MessagesService],
|
||||
})
|
||||
export class MessagesModule {}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { createHash } from 'crypto';
|
||||
import { codePointLength } from '../common/dto/code-point-length.validator';
|
||||
import { decodeMessageCursor, encodeMessageCursor } from '../common/cursor';
|
||||
import { Message } from '../common/domain';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { validate as isUuid } from '../common/uuid';
|
||||
import { PrismaService } from '../db/prisma.service';
|
||||
import { MessagePageResponse, toMessageResponse } from './dto/message.response';
|
||||
|
||||
interface MessageRow {
|
||||
id: string;
|
||||
chatId: string;
|
||||
senderId: string;
|
||||
text: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
class KeyAlreadyUsed extends Error {}
|
||||
|
||||
@Injectable()
|
||||
export class MessagesService {
|
||||
private readonly keyTtlMs =
|
||||
Number(process.env.IDEMPOTENCY_TTL_SECONDS ?? 86400) * 1000;
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async create(
|
||||
chatId: string,
|
||||
callerId: string,
|
||||
text: string,
|
||||
key: string,
|
||||
): Promise<Message> {
|
||||
await this.assertMember(chatId, callerId);
|
||||
if (codePointLength(text.trim()) === 0) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'text must not be empty or whitespace-only',
|
||||
);
|
||||
}
|
||||
const scope = { userId: callerId, chatId, key };
|
||||
const requestHash = createHash('sha256')
|
||||
.update(JSON.stringify({ text }))
|
||||
.digest('hex');
|
||||
try {
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
await tx.idempotencyKey.deleteMany({
|
||||
where: {
|
||||
...scope,
|
||||
createdAt: { lt: new Date(Date.now() - this.keyTtlMs) },
|
||||
},
|
||||
});
|
||||
const row = await tx.message.create({
|
||||
data: { chatId, senderId: callerId, text },
|
||||
});
|
||||
const { count } = await tx.idempotencyKey.createMany({
|
||||
data: [{ ...scope, requestHash, messageId: row.id }],
|
||||
skipDuplicates: true,
|
||||
});
|
||||
if (count === 0) {
|
||||
throw new KeyAlreadyUsed();
|
||||
}
|
||||
return toMessage(row);
|
||||
});
|
||||
} catch (error) {
|
||||
if (!(error instanceof KeyAlreadyUsed)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const stored = await this.prisma.idempotencyKey.findUnique({
|
||||
where: { userId_chatId_key: scope },
|
||||
include: { message: true },
|
||||
});
|
||||
if (!stored || stored.requestHash !== requestHash) {
|
||||
throw new ApiError(
|
||||
'conflict',
|
||||
'Idempotency-Key was already used with a different request',
|
||||
);
|
||||
}
|
||||
return toMessage(stored.message);
|
||||
}
|
||||
|
||||
async list(
|
||||
chatId: string,
|
||||
callerId: string,
|
||||
limit: number,
|
||||
rawCursor: string | null,
|
||||
): Promise<MessagePageResponse> {
|
||||
await this.assertMember(chatId, callerId);
|
||||
let after = Prisma.empty;
|
||||
if (rawCursor !== null) {
|
||||
const cursor = decodeMessageCursor(rawCursor);
|
||||
if (cursor && cursor.chatId !== chatId) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'cursor belongs to a different chat',
|
||||
);
|
||||
}
|
||||
const anchor = cursor
|
||||
? await this.prisma.message.findFirst({
|
||||
where: { id: cursor.id, chatId },
|
||||
select: { id: true, createdAt: true },
|
||||
})
|
||||
: null;
|
||||
if (!anchor) {
|
||||
throw new ApiError('invalid_request', 'invalid cursor');
|
||||
}
|
||||
after = Prisma.sql`AND (created_at, id) > (${anchor.createdAt}::timestamptz, ${anchor.id}::uuid)`;
|
||||
}
|
||||
const rows = await this.prisma.$queryRaw<MessageRow[]>`
|
||||
SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt"
|
||||
FROM messages
|
||||
WHERE chat_id = ${chatId}::uuid ${after}
|
||||
ORDER BY created_at, id
|
||||
LIMIT ${limit + 1}`;
|
||||
const items = rows.slice(0, limit).map(toMessage);
|
||||
const last = items[items.length - 1];
|
||||
return {
|
||||
items: items.map(toMessageResponse),
|
||||
next_cursor:
|
||||
rows.length > limit
|
||||
? encodeMessageCursor({ chatId, id: last.id })
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
private async assertMember(chatId: string, callerId: string): Promise<void> {
|
||||
if (!isUuid(chatId)) {
|
||||
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
||||
}
|
||||
const member = await this.prisma.chatMember.findUnique({
|
||||
where: { chatId_userId: { chatId, userId: callerId } },
|
||||
});
|
||||
if (!member) {
|
||||
throw new ApiError('not_found', 'chat not found');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toMessage(row: MessageRow): Message {
|
||||
return {
|
||||
id: row.id,
|
||||
chatId: row.chatId,
|
||||
senderId: row.senderId,
|
||||
text: row.text,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Matches } from 'class-validator';
|
||||
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||
import { NotBlank } from '../../common/dto/not-blank.validator';
|
||||
|
||||
export class CreateUserDto {
|
||||
@Matches(/^[a-z0-9_]{3,32}$/, {
|
||||
message: 'username must match [a-z0-9_]{3,32}',
|
||||
})
|
||||
username!: string;
|
||||
|
||||
@NotBlank()
|
||||
@CodePointLength(1, 100)
|
||||
display_name!: string;
|
||||
|
||||
@NotBlank()
|
||||
@CodePointLength(12, 128)
|
||||
password!: string;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { User } from '../../common/domain';
|
||||
|
||||
export interface UserResponse {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export function toUserResponse(user: User): UserResponse {
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
display_name: user.displayName,
|
||||
created_at: user.createdAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '../auth/auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { User } from '../common/domain';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { toUserResponse, UserResponse } from './dto/user.response';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Controller('api/v1/users')
|
||||
export class UsersController {
|
||||
constructor(private readonly users: UsersService) {}
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
async create(@Body() dto: CreateUserDto): Promise<UserResponse> {
|
||||
const user = await this.users.register(
|
||||
dto.username,
|
||||
dto.display_name,
|
||||
dto.password,
|
||||
);
|
||||
return toUserResponse(user);
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@UseGuards(AuthGuard)
|
||||
me(@CurrentUser() user: User): UserResponse {
|
||||
return toUserResponse(user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UsersController } from './users.controller';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Module({
|
||||
controllers: [UsersController],
|
||||
providers: [UsersService],
|
||||
exports: [UsersService],
|
||||
})
|
||||
export class UsersModule {}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { hashPassword } from '../auth/password';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { User } from '../common/domain';
|
||||
import { PrismaService, isUniqueViolation } from '../db/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async register(
|
||||
username: string,
|
||||
displayName: string,
|
||||
password: string,
|
||||
): Promise<User> {
|
||||
const passwordHash = await hashPassword(password);
|
||||
try {
|
||||
const row = await this.prisma.user.create({
|
||||
data: { username, displayName: displayName.trim(), passwordHash },
|
||||
});
|
||||
return toUser(row);
|
||||
} catch (error) {
|
||||
if (isUniqueViolation(error)) {
|
||||
throw new ApiError('conflict', 'username is already taken');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<User | null> {
|
||||
const row = await this.prisma.user.findUnique({ where: { id } });
|
||||
return row ? toUser(row) : null;
|
||||
}
|
||||
}
|
||||
|
||||
export function toUser(row: {
|
||||
id: string;
|
||||
username: string;
|
||||
displayName: string;
|
||||
createdAt: Date;
|
||||
}): User {
|
||||
return {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
displayName: row.displayName,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,680 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import {
|
||||
bearer,
|
||||
createTestApp,
|
||||
PASSWORD,
|
||||
registerUser,
|
||||
TestUser,
|
||||
} from './helpers';
|
||||
|
||||
describe('API мессенджера (e2e) — граничные случаи сверх публичного smoke', () => {
|
||||
let app: INestApplication;
|
||||
let server: any;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ app, server } = await createTestApp());
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
function createUser(label: string): Promise<TestUser> {
|
||||
return registerUser(server, label);
|
||||
}
|
||||
|
||||
describe('POST /api/v1/users', () => {
|
||||
it('отклоняет некорректный JSON с кодом 400', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send('{not valid json')
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
expect(res.body.error.request_id).toBeTruthy();
|
||||
});
|
||||
|
||||
it('отклоняет тело с лишними полями', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'validname1',
|
||||
display_name: 'Valid',
|
||||
password: PASSWORD,
|
||||
extra: 'nope',
|
||||
})
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('отклоняет username с заглавными буквами', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'InvalidName', display_name: 'X', password: PASSWORD })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет display_name из одних пробелов', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'wsonlyname1', display_name: ' ', password: PASSWORD })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет дубликат username с кодом 409', async () => {
|
||||
const user = await createUser('dup');
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: user.username, display_name: 'Someone else', password: PASSWORD })
|
||||
.expect(409);
|
||||
expect(res.body.error.code).toBe('conflict');
|
||||
});
|
||||
|
||||
it('никогда не возвращает поле пароля или его хэша', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `nopass_${randomUUID().slice(0, 8)}`,
|
||||
display_name: 'X',
|
||||
password: PASSWORD,
|
||||
})
|
||||
.expect(201);
|
||||
expect(res.body).not.toHaveProperty('password');
|
||||
expect(res.body).not.toHaveProperty('password_hash');
|
||||
});
|
||||
|
||||
it('отклоняет username короче 3 символов', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'ab', display_name: 'X', password: PASSWORD })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет username длиннее 32 символов', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'a'.repeat(33), display_name: 'X', password: PASSWORD })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет username с недопустимыми символами (дефис)', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'has-hyphen', display_name: 'X', password: PASSWORD })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('принимает username ровно на границах длины 3 и 32 символа', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `a${randomUUID().slice(0, 2)}`,
|
||||
display_name: 'X',
|
||||
password: PASSWORD,
|
||||
})
|
||||
.expect(201);
|
||||
const longest = ('z' + randomUUID().replace(/-/g, '')).slice(0, 32);
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: longest, display_name: 'X', password: PASSWORD })
|
||||
.expect(201);
|
||||
});
|
||||
|
||||
it('отклоняет display_name длиннее 100 Unicode code points', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `toolongname_${randomUUID().slice(0, 6)}`,
|
||||
display_name: 'x'.repeat(101),
|
||||
password: PASSWORD,
|
||||
})
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('принимает display_name ровно из 100 code points, считая эмодзи вне BMP за один символ', async () => {
|
||||
const displayName = '👋'.repeat(100);
|
||||
expect([...displayName].length).toBe(100);
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `emojiname_${randomUUID().slice(0, 6)}`,
|
||||
display_name: displayName,
|
||||
password: PASSWORD,
|
||||
})
|
||||
.expect(201);
|
||||
});
|
||||
|
||||
it('отклоняет display_name из 101 code point, состоящий из эмодзи вне BMP', async () => {
|
||||
const displayName = '👋'.repeat(100) + 'x';
|
||||
expect([...displayName].length).toBe(101);
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `emojitoolong_${randomUUID().slice(0, 6)}`,
|
||||
display_name: displayName,
|
||||
password: PASSWORD,
|
||||
})
|
||||
.expect(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('контроль доступа', () => {
|
||||
it('возвращает 401 раньше 404, если и актор, и ресурс невалидны', async () => {
|
||||
const res = await request(server)
|
||||
.get(`/api/v1/chats/${randomUUID()}`)
|
||||
.set('Authorization', 'Bearer not-a-token')
|
||||
.expect(401);
|
||||
expect(res.body.error.code).toBe('unauthorized');
|
||||
});
|
||||
|
||||
it('возвращает 404 (не 403), когда чат запрашивает не его участник', async () => {
|
||||
const alice = await createUser('alice');
|
||||
const bob = await createUser('bob');
|
||||
const eve = await createUser('eve');
|
||||
const chat = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title: 'Private', member_ids: [alice.id, bob.id] })
|
||||
.expect(201);
|
||||
|
||||
const res = await request(server)
|
||||
.get(`/api/v1/chats/${chat.body.id}`)
|
||||
.set('Authorization', bearer(eve))
|
||||
.expect(404);
|
||||
expect(res.body.error.code).toBe('not_found');
|
||||
});
|
||||
|
||||
it('отклоняет создание чата, если вызывающий не входит в member_ids', async () => {
|
||||
const alice = await createUser('alice2');
|
||||
const bob = await createUser('bob2');
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title: 'Missing caller', member_ids: [bob.id] })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет создание чата с дублирующимися member_ids', async () => {
|
||||
const alice = await createUser('alice3');
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({
|
||||
title: 'Dup members',
|
||||
member_ids: [alice.id, alice.id],
|
||||
})
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('считает один UUID в разном регистре дубликатом и узнаёт вызывающего в верхнем регистре', async () => {
|
||||
const alice = await createUser('alicecase');
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title: 'Case', member_ids: [alice.id, alice.id.toUpperCase()] })
|
||||
.expect(400);
|
||||
const res = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title: 'Upper', member_ids: [alice.id.toUpperCase()] })
|
||||
.expect(201);
|
||||
expect(res.body.member_ids).toEqual([alice.id]);
|
||||
});
|
||||
|
||||
it('принимает ровно 100 участников и отклоняет 101', async () => {
|
||||
const alice = await createUser('max');
|
||||
const ids = Array.from({ length: 100 }, () => randomUUID());
|
||||
await app.get(PrismaService).user.createMany({
|
||||
data: ids.map((id) => ({
|
||||
id,
|
||||
username: `m_${id.replace(/-/g, '').slice(0, 30)}`,
|
||||
displayName: 'Member',
|
||||
passwordHash: 'not-a-real-hash',
|
||||
})),
|
||||
});
|
||||
const ok = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title: 'Max', member_ids: [alice.id, ...ids.slice(0, 99)] })
|
||||
.expect(201);
|
||||
expect(ok.body.member_ids).toHaveLength(100);
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title: 'Too many', member_ids: [alice.id, ...ids] })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет создание чата с неизвестным участником', async () => {
|
||||
const alice = await createUser('alice4');
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({
|
||||
title: 'Unknown member',
|
||||
member_ids: [alice.id, randomUUID()],
|
||||
})
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет создание чата с пустым/пробельным title', async () => {
|
||||
const alice = await createUser('alice4b');
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title: ' ', member_ids: [alice.id] })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('возвращает 400 для синтаксически некорректного chat_id (не UUID)', async () => {
|
||||
const alice = await createUser('alice4c');
|
||||
const res = await request(server)
|
||||
.get('/api/v1/chats/not-a-uuid')
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('возвращает 404 для корректного по формату, но несуществующего chat_id', async () => {
|
||||
const alice = await createUser('alice4d');
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${randomUUID()}`)
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/chats (пагинация)', () => {
|
||||
it('использует limit=50 по умолчанию, если limit не передан', async () => {
|
||||
const alice = await createUser('pgalice1');
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title: 'Only chat', member_ids: [alice.id] })
|
||||
.expect(201);
|
||||
const res = await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(200);
|
||||
expect(res.body.items.length).toBeGreaterThanOrEqual(1);
|
||||
expect(res.body.items.length).toBeLessThanOrEqual(50);
|
||||
});
|
||||
|
||||
it('отклоняет нечисловой limit', async () => {
|
||||
const alice = await createUser('pgalice2');
|
||||
await request(server)
|
||||
.get('/api/v1/chats?limit=abc')
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет limit=0', async () => {
|
||||
const alice = await createUser('pgalice3');
|
||||
await request(server)
|
||||
.get('/api/v1/chats?limit=0')
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет повторённые limit и cursor', async () => {
|
||||
const alice = await createUser('pgrepeat');
|
||||
for (const query of ['limit=1&limit=2', 'cursor=a&cursor=b']) {
|
||||
await request(server)
|
||||
.get(`/api/v1/chats?${query}`)
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
}
|
||||
});
|
||||
|
||||
it('отклоняет cursor, не являющийся корректным base64url JSON', async () => {
|
||||
const alice = await createUser('pgalice4');
|
||||
await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.query({ cursor: 'not-a-real-cursor!!!' })
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет корректно закодированный cursor с id чата, который никогда не существовал', async () => {
|
||||
const alice = await createUser('pgalice4b');
|
||||
const bogusCursor = Buffer.from(
|
||||
JSON.stringify({ id: randomUUID() }),
|
||||
'utf8',
|
||||
).toString('base64url');
|
||||
const res = await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.query({ cursor: bogusCursor })
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('обходит весь список чатов по страницам без пропусков и дублей', async () => {
|
||||
const alice = await createUser('pgalice5');
|
||||
const titles = ['c1', 'c2', 'c3', 'c4', 'c5'];
|
||||
for (const title of titles) {
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title, member_ids: [alice.id] })
|
||||
.expect(201);
|
||||
}
|
||||
|
||||
const seen: string[] = [];
|
||||
let cursor: string | null = null;
|
||||
do {
|
||||
const res: request.Response = await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.query({ limit: 2, ...(cursor ? { cursor } : {}) })
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(200);
|
||||
seen.push(
|
||||
...res.body.items.map((c: { title: string }) => c.title),
|
||||
);
|
||||
cursor = res.body.next_cursor;
|
||||
} while (cursor);
|
||||
|
||||
expect(seen).toEqual(titles);
|
||||
});
|
||||
});
|
||||
|
||||
describe('сообщения', () => {
|
||||
async function createChat(alice: TestUser, bob: TestUser) {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title: 'Chat', member_ids: [alice.id, bob.id] })
|
||||
.expect(201);
|
||||
return res.body as { id: string };
|
||||
}
|
||||
|
||||
it('не принимает sender_id, переданный клиентом', async () => {
|
||||
const alice = await createUser('alice5');
|
||||
const bob = await createUser('bob5');
|
||||
const chat = await createChat(alice, bob);
|
||||
|
||||
const res = await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'hi', sender_id: bob.id })
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('считает attachment_ids: [] равным отсутствию поля, непустой список отклоняет', async () => {
|
||||
const alice = await createUser('aliceatt');
|
||||
const bob = await createUser('bobatt');
|
||||
const chat = await createChat(alice, bob);
|
||||
const path = `/api/v1/chats/${chat.id}/messages`;
|
||||
const key = randomUUID();
|
||||
const first = await request(server)
|
||||
.post(path)
|
||||
.set('Idempotency-Key', key)
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'att' })
|
||||
.expect(201);
|
||||
const replay = await request(server)
|
||||
.post(path)
|
||||
.set('Idempotency-Key', key)
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ attachment_ids: [], text: 'att' })
|
||||
.expect(201);
|
||||
expect(replay.body).toEqual(first.body);
|
||||
for (const attachment_ids of [[randomUUID()], null, 'x']) {
|
||||
await request(server)
|
||||
.post(path)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'x', attachment_ids })
|
||||
.expect(400);
|
||||
}
|
||||
});
|
||||
|
||||
it('отклоняет пустое сообщение', async () => {
|
||||
const alice = await createUser('alice6');
|
||||
const bob = await createUser('bob6');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: '' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет сообщение из одних пробелов', async () => {
|
||||
const alice = await createUser('alice7');
|
||||
const bob = await createUser('bob7');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: ' \n\t ' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет отправку в чат, где вызывающий не участник', async () => {
|
||||
const alice = await createUser('alice8');
|
||||
const bob = await createUser('bob8');
|
||||
const eve = await createUser('eve8');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(eve))
|
||||
.send({ text: 'intrusion' })
|
||||
.expect(404);
|
||||
});
|
||||
|
||||
it('отклоняет limit=0 при чтении истории', async () => {
|
||||
const alice = await createUser('alice9');
|
||||
const bob = await createUser('bob9');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages?limit=0`)
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет limit=101 при чтении истории', async () => {
|
||||
const alice = await createUser('alice10');
|
||||
const bob = await createUser('bob10');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages?limit=101`)
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет нечисловой limit', async () => {
|
||||
const alice = await createUser('alice10b');
|
||||
const bob = await createUser('bob10b');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages?limit=abc`)
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет текст сообщения длиннее 4000 Unicode code points', async () => {
|
||||
const alice = await createUser('alice10c');
|
||||
const bob = await createUser('bob10c');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'x'.repeat(4001) })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('принимает текст сообщения ровно из 4000 Unicode code points', async () => {
|
||||
const alice = await createUser('alice10d');
|
||||
const bob = await createUser('bob10d');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'x'.repeat(4000) })
|
||||
.expect(201);
|
||||
});
|
||||
|
||||
it('отклоняет текст сообщения свыше 4000 code points, состоящий из эмодзи вне BMP', async () => {
|
||||
const alice = await createUser('alice10e');
|
||||
const bob = await createUser('bob10e');
|
||||
const chat = await createChat(alice, bob);
|
||||
const text = '👋'.repeat(4001);
|
||||
expect([...text].length).toBe(4001);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет cursor, не являющийся корректным base64url JSON', async () => {
|
||||
const alice = await createUser('alice10f');
|
||||
const bob = await createUser('bob10f');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages`)
|
||||
.query({ cursor: '!!!not-valid!!!' })
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет корректно закодированный cursor с id сообщения, которое никогда не существовало в этом чате', async () => {
|
||||
const alice = await createUser('alice10i');
|
||||
const bob = await createUser('bob10i');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'only message' })
|
||||
.expect(201);
|
||||
|
||||
const bogusCursor = Buffer.from(
|
||||
JSON.stringify({ chatId: chat.id, id: randomUUID() }),
|
||||
'utf8',
|
||||
).toString('base64url');
|
||||
const res = await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages`)
|
||||
.query({ cursor: bogusCursor })
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('возвращает 400 для синтаксически некорректного chat_id при отправке сообщения', async () => {
|
||||
const alice = await createUser('alice10g');
|
||||
const res = await request(server)
|
||||
.post('/api/v1/chats/not-a-uuid/messages')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'hi' })
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('возвращает 400 для синтаксически некорректного chat_id при чтении истории', async () => {
|
||||
const alice = await createUser('alice10h');
|
||||
const res = await request(server)
|
||||
.get('/api/v1/chats/not-a-uuid/messages')
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('отклоняет cursor, взятый из другого чата', async () => {
|
||||
const alice = await createUser('alice11');
|
||||
const bob = await createUser('bob11');
|
||||
const chatA = await createChat(alice, bob);
|
||||
const chatB = await createChat(alice, bob);
|
||||
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chatA.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'first' })
|
||||
.expect(201);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chatA.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text: 'second' })
|
||||
.expect(201);
|
||||
|
||||
const page1 = await request(server)
|
||||
.get(`/api/v1/chats/${chatA.id}/messages?limit=1`)
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(200);
|
||||
expect(page1.body.next_cursor).toBeTruthy();
|
||||
|
||||
const res = await request(server)
|
||||
.get(`/api/v1/chats/${chatB.id}/messages`)
|
||||
.query({ cursor: page1.body.next_cursor })
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('обходит всю историю по страницам без пропусков и дублей', async () => {
|
||||
const alice = await createUser('alice12');
|
||||
const bob = await createUser('bob12');
|
||||
const chat = await createChat(alice, bob);
|
||||
const sentTexts = ['m1', 'm2', 'm3', 'm4', 'm5'];
|
||||
for (const text of sentTexts) {
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ text })
|
||||
.expect(201);
|
||||
}
|
||||
|
||||
const seen: string[] = [];
|
||||
let cursor: string | null = null;
|
||||
do {
|
||||
const res: request.Response = await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages`)
|
||||
.query({ limit: 2, ...(cursor ? { cursor } : {}) })
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(200);
|
||||
seen.push(
|
||||
...res.body.items.map((m: { text: string }) => m.text),
|
||||
);
|
||||
cursor = res.body.next_cursor;
|
||||
} while (cursor);
|
||||
|
||||
expect(seen).toEqual(sentTexts);
|
||||
});
|
||||
});
|
||||
|
||||
describe('X-Request-Id', () => {
|
||||
it('присутствует и уникален для независимых запросов', async () => {
|
||||
const first = await request(server).get('/health/live').expect(200);
|
||||
const second = await request(server)
|
||||
.get('/health/live')
|
||||
.expect(200);
|
||||
expect(first.headers['x-request-id']).toBeTruthy();
|
||||
expect(second.headers['x-request-id']).toBeTruthy();
|
||||
expect(first.headers['x-request-id']).not.toBe(
|
||||
second.headers['x-request-id'],
|
||||
);
|
||||
});
|
||||
|
||||
it('совпадает с request_id внутри тела ошибки', async () => {
|
||||
const res = await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.expect(401);
|
||||
expect(res.body.error.request_id).toBe(res.headers['x-request-id']);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import {
|
||||
basic,
|
||||
bearer,
|
||||
createTestApp,
|
||||
login,
|
||||
PASSWORD,
|
||||
registerUser,
|
||||
} from './helpers';
|
||||
|
||||
describe('Аутентификация и сессии (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
let server: any;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ app, server } = await createTestApp());
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe('регистрация', () => {
|
||||
it('требует password', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: `nopw_${randomUUID().slice(0, 8)}`, display_name: 'X' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет password короче 12 code points', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `short_${randomUUID().slice(0, 8)}`,
|
||||
display_name: 'X',
|
||||
password: 'x'.repeat(11),
|
||||
})
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('хранит пароль как Argon2id-хеш, а не открытым текстом', async () => {
|
||||
const user = await registerUser(server, 'hash');
|
||||
const row = await app
|
||||
.get(PrismaService)
|
||||
.user.findUniqueOrThrow({ where: { id: user.id } });
|
||||
expect(row.passwordHash.startsWith('$argon2id$')).toBe(true);
|
||||
expect(row.passwordHash).not.toContain(PASSWORD);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/auth/sessions', () => {
|
||||
it('выдаёт непрозрачный Bearer-токен с expires_at и пользователем', async () => {
|
||||
const user = await registerUser(server, 'login');
|
||||
const res = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.set('Authorization', basic(user.username, PASSWORD))
|
||||
.expect(201);
|
||||
expect(res.body.token_type).toBe('Bearer');
|
||||
expect(res.body.token.length).toBeGreaterThanOrEqual(43);
|
||||
expect(res.body.token).not.toContain(user.id);
|
||||
expect(res.body.user.id).toBe(user.id);
|
||||
const expiresIn = Date.parse(res.body.expires_at) - Date.now();
|
||||
expect(expiresIn).toBeGreaterThan(3500 * 1000);
|
||||
expect(expiresIn).toBeLessThanOrEqual(3600 * 1000);
|
||||
});
|
||||
|
||||
it('принимает пароль с двоеточием и не-ASCII символами', async () => {
|
||||
const username = `colon_${randomUUID().slice(0, 8)}`;
|
||||
const password = 'пароль:с:двоеточием🔑';
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username, display_name: 'X', password })
|
||||
.expect(201);
|
||||
await login(server, username, password);
|
||||
});
|
||||
|
||||
it('отвечает одинаковым 401 на неверный пароль и неизвестного пользователя', async () => {
|
||||
const user = await registerUser(server, 'wrong');
|
||||
const wrong = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.set('Authorization', basic(user.username, 'wrong-password-123'))
|
||||
.expect(401);
|
||||
const unknown = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.set('Authorization', basic(`ghost_${randomUUID().slice(0, 8)}`, PASSWORD))
|
||||
.expect(401);
|
||||
for (const res of [wrong, unknown]) {
|
||||
expect(res.headers['www-authenticate']).toBe(
|
||||
'Basic realm="messenger", charset="UTF-8"',
|
||||
);
|
||||
expect(res.body.error.code).toBe('unauthorized');
|
||||
}
|
||||
expect(wrong.body.error.message).toBe(unknown.body.error.message);
|
||||
});
|
||||
|
||||
it('отклоняет JSON body при входе даже с верным Basic', async () => {
|
||||
const user = await registerUser(server, 'body');
|
||||
for (const body of [{ extra: 'forbidden' }, {}]) {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.set('Authorization', basic(user.username, PASSWORD))
|
||||
.send(body)
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
}
|
||||
});
|
||||
|
||||
it('отвечает 401 без заголовка Authorization', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.expect(401);
|
||||
expect(res.headers['www-authenticate']).toContain('Basic');
|
||||
});
|
||||
});
|
||||
|
||||
describe('защищённые endpoint', () => {
|
||||
it('не принимают Basic', async () => {
|
||||
const user = await registerUser(server, 'basic');
|
||||
const res = await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', basic(user.username, PASSWORD))
|
||||
.expect(401);
|
||||
expect(res.headers['www-authenticate']).toBe('Bearer realm="messenger"');
|
||||
});
|
||||
|
||||
it('не принимают X-User-Id сам по себе', async () => {
|
||||
const user = await registerUser(server, 'xuid');
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('X-User-Id', user.id)
|
||||
.expect(401);
|
||||
});
|
||||
|
||||
it('игнорируют X-User-Id рядом с Bearer', async () => {
|
||||
const alice = await registerUser(server, 'alice');
|
||||
const eve = await registerUser(server, 'eve');
|
||||
const res = await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', bearer(alice))
|
||||
.set('X-User-Id', eve.id)
|
||||
.expect(200);
|
||||
expect(res.body.id).toBe(alice.id);
|
||||
});
|
||||
|
||||
it('отвечают 401 на неизвестный токен', async () => {
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', 'Bearer unknown-token-value')
|
||||
.expect(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/auth/sessions/current', () => {
|
||||
it('отзывает только текущий токен: 204, затем 401 на повтор', async () => {
|
||||
const user = await registerUser(server, 'logout');
|
||||
const other = await login(server, user.username);
|
||||
await request(server)
|
||||
.delete('/api/v1/auth/sessions/current')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(204);
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(401);
|
||||
await request(server)
|
||||
.delete('/api/v1/auth/sessions/current')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(401);
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', `Bearer ${other}`)
|
||||
.expect(200);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { randomUUID } from 'crypto';
|
||||
import {
|
||||
bearer,
|
||||
createTestApp,
|
||||
login,
|
||||
PASSWORD,
|
||||
registerUser,
|
||||
} from './helpers';
|
||||
|
||||
describe('Безопасность при конкурентном доступе (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
let server: any;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ app, server } = await createTestApp());
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных', async () => {
|
||||
const CLIENTS = 10;
|
||||
const MESSAGES_PER_CLIENT = 10;
|
||||
|
||||
const owner = await registerUser(server, 'owner');
|
||||
const clients = await Promise.all(
|
||||
Array.from({ length: CLIENTS }, (_, i) =>
|
||||
registerUser(server, `racer${i}`),
|
||||
),
|
||||
);
|
||||
const memberIds = [owner.id, ...clients.map((c) => c.id)];
|
||||
|
||||
const chat = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(owner))
|
||||
.send({ title: 'Race', member_ids: memberIds })
|
||||
.expect(201);
|
||||
|
||||
const sendTasks: Promise<request.Response>[] = [];
|
||||
for (let c = 0; c < CLIENTS; c++) {
|
||||
for (let m = 0; m < MESSAGES_PER_CLIENT; m++) {
|
||||
sendTasks.push(
|
||||
request(server)
|
||||
.post(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.set('Idempotency-Key', randomUUID())
|
||||
.set('Authorization', bearer(clients[c]))
|
||||
.send({ text: `client-${c}-message-${m}` }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const responses = await Promise.all(sendTasks);
|
||||
for (const res of responses) {
|
||||
expect(res.status).toBe(201);
|
||||
}
|
||||
|
||||
const sentIds = new Set(responses.map((r) => r.body.id));
|
||||
expect(sentIds.size).toBe(CLIENTS * MESSAGES_PER_CLIENT);
|
||||
|
||||
const collected: { id: string; text: string }[] = [];
|
||||
let cursor: string | null = null;
|
||||
do {
|
||||
const res: request.Response = await request(server)
|
||||
.get(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.query({ limit: 25, ...(cursor ? { cursor } : {}) })
|
||||
.set('Authorization', bearer(owner))
|
||||
.expect(200);
|
||||
collected.push(...res.body.items);
|
||||
cursor = res.body.next_cursor;
|
||||
} while (cursor);
|
||||
|
||||
expect(collected.length).toBe(CLIENTS * MESSAGES_PER_CLIENT);
|
||||
const uniqueIds = new Set(collected.map((m) => m.id));
|
||||
expect(uniqueIds.size).toBe(CLIENTS * MESSAGES_PER_CLIENT);
|
||||
|
||||
const uniqueTexts = new Set(collected.map((m) => m.text));
|
||||
expect(uniqueTexts.size).toBe(CLIENTS * MESSAGES_PER_CLIENT);
|
||||
|
||||
const fullHistory: { id: string; created_at: string }[] =
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.query({ limit: 100 })
|
||||
.set('Authorization', bearer(owner))
|
||||
.expect(200)
|
||||
.then((res) => res.body.items);
|
||||
const sortKeys = fullHistory.map((m) => `${m.created_at}#${m.id}`);
|
||||
const sortedKeys = [...sortKeys].sort();
|
||||
expect(sortKeys).toEqual(sortedKeys);
|
||||
});
|
||||
|
||||
it('регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username', async () => {
|
||||
const username = `racer_username_${randomUUID().slice(0, 8)}`;
|
||||
const attempts = 10;
|
||||
|
||||
const responses = await Promise.all(
|
||||
Array.from({ length: attempts }, () =>
|
||||
request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username, display_name: 'Racer', password: PASSWORD }),
|
||||
),
|
||||
);
|
||||
|
||||
const succeeded = responses.filter((r) => r.status === 201);
|
||||
const conflicted = responses.filter((r) => r.status === 409);
|
||||
|
||||
expect(succeeded.length).toBe(1);
|
||||
expect(conflicted.length).toBe(attempts - 1);
|
||||
|
||||
const token = await login(server, username);
|
||||
const me = await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
expect(me.body.id).toBe(succeeded[0].body.id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import Ajv2020 from 'ajv/dist/2020';
|
||||
import request from 'supertest';
|
||||
import { OPERATION_EXAMPLES } from '../src/docs/examples';
|
||||
import { loadDocument, setupSwagger } from '../src/docs/swagger';
|
||||
import { createTestApp } from './helpers';
|
||||
|
||||
const CONTRACT_ID = 'https://contract.local/openapi.json';
|
||||
|
||||
describe('Swagger UI и примеры (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
let server: any;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ app, server } = await createTestApp({}, setupSwagger));
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('отдаёт Swagger UI и документ контракта со всеми путями', async () => {
|
||||
await request(server).get('/docs').expect(200);
|
||||
const res = await request(server).get('/docs-json').expect(200);
|
||||
expect(res.body.openapi).toBe('3.1.0');
|
||||
expect(Object.keys(res.body.paths)).toEqual(
|
||||
Object.keys(loadDocument().paths),
|
||||
);
|
||||
expect(res.body.components.securitySchemes).toHaveProperty('basicAuth');
|
||||
expect(res.body.components.securitySchemes).toHaveProperty('bearerAuth');
|
||||
});
|
||||
|
||||
it('каждый пример запроса и ответа проходит JSON Schema контракта', () => {
|
||||
const document: any = loadDocument();
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
ajv.addSchema(document, CONTRACT_ID);
|
||||
let checked = 0;
|
||||
for (const [key, examples] of Object.entries(OPERATION_EXAMPLES)) {
|
||||
const [method, path] = key.split(' ');
|
||||
const operation = document.paths[path][method.toLowerCase()];
|
||||
const targets: [string, any, Record<string, any>][] = [];
|
||||
if (examples.request) {
|
||||
targets.push([
|
||||
'request',
|
||||
operation.requestBody.content['application/json'].schema,
|
||||
examples.request,
|
||||
]);
|
||||
}
|
||||
for (const [status, named] of Object.entries(examples.responses)) {
|
||||
targets.push([
|
||||
status,
|
||||
operation.responses[status].content['application/json'].schema,
|
||||
named,
|
||||
]);
|
||||
}
|
||||
for (const [where, schema, named] of targets) {
|
||||
const validate = ajv.compile({ $ref: CONTRACT_ID + schema.$ref });
|
||||
for (const [name, example] of Object.entries(named)) {
|
||||
const valid = validate(example.value);
|
||||
expect({ key, where, name, valid, errors: validate.errors }).toEqual(
|
||||
{ key, where, name, valid: true, errors: null },
|
||||
);
|
||||
checked++;
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(checked).toBeGreaterThan(40);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { randomUUID } from 'crypto';
|
||||
import Redis from 'ioredis';
|
||||
import { CacheService } from '../src/cache/cache.service';
|
||||
import { ChatsService } from '../src/chats/chats.service';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import { bearer, createTestApp, registerUser } from './helpers';
|
||||
|
||||
const UNREACHABLE_REDIS = 'redis://127.0.0.1:1/0';
|
||||
const UNREACHABLE_DB = 'postgresql://test:test@127.0.0.1:1/none?connect_timeout=1';
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
describe('Уровень 4: expiry, отказы зависимостей, rollback (e2e)', () => {
|
||||
const apps: INestApplication[] = [];
|
||||
|
||||
async function start(env: Record<string, string> = {}) {
|
||||
const started = await createTestApp(env);
|
||||
apps.push(started.app);
|
||||
return started;
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
await Promise.all(apps.map((app) => app.close()));
|
||||
});
|
||||
|
||||
it('сессия истекает при коротком SESSION_TTL_SECONDS, в том числе из кэша', async () => {
|
||||
const { server } = await start({ SESSION_TTL_SECONDS: '2' });
|
||||
const user = await registerUser(server, 'ttl');
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(200);
|
||||
await sleep(2500);
|
||||
const res = await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(401);
|
||||
expect(res.headers['www-authenticate']).toBe('Bearer realm="messenger"');
|
||||
});
|
||||
|
||||
it('без Redis вход и проверка сессии работают через PostgreSQL, logout — 503 без отзыва', async () => {
|
||||
const { server } = await start({ CACHE_URL: UNREACHABLE_REDIS });
|
||||
const user = await registerUser(server, 'noredis');
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(200);
|
||||
const res = await request(server)
|
||||
.delete('/api/v1/auth/sessions/current')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(503);
|
||||
expect(res.body.error.code).toBe('unavailable');
|
||||
await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(200);
|
||||
await request(server).get('/api/v1/users/me').expect(401);
|
||||
});
|
||||
|
||||
it('logout через реплику без связи с Redis не создаёт расхождения с репликой, у которой сессия в кэше', async () => {
|
||||
const a = await start();
|
||||
const b = await start();
|
||||
const user = await registerUser(a.server, 'partition');
|
||||
const me = (server: any, status: number) =>
|
||||
request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(status);
|
||||
const logout = (status: number) =>
|
||||
request(a.server)
|
||||
.delete('/api/v1/auth/sessions/current')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(status);
|
||||
const cache = a.app.get(CacheService) as any;
|
||||
const redis = cache.client as Redis;
|
||||
|
||||
await me(b.server, 200);
|
||||
redis.disconnect();
|
||||
await logout(503);
|
||||
await me(b.server, 200);
|
||||
await me(a.server, 200);
|
||||
|
||||
await redis.connect();
|
||||
await sleep(200);
|
||||
expect(cache.trusted).toBe(true);
|
||||
await me(b.server, 200);
|
||||
expect((await redis.keys('session:v1:*')).length).toBeGreaterThan(0);
|
||||
await logout(204);
|
||||
await me(b.server, 401);
|
||||
await me(a.server, 401);
|
||||
});
|
||||
|
||||
it('без PostgreSQL отвечает ограниченным 503 и не пускает анонима', async () => {
|
||||
const healthy = await start();
|
||||
const user = await registerUser(healthy.server, 'nodb');
|
||||
await request(healthy.server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(200);
|
||||
|
||||
const { server } = await start({ DATABASE_URL: UNREACHABLE_DB });
|
||||
const ready = await request(server).get('/health/ready').expect(503);
|
||||
expect(ready.body.error.code).toBe('unavailable');
|
||||
expect(JSON.stringify(ready.body)).not.toMatch(/127\.0\.0\.1|postgresql:|prisma/i);
|
||||
|
||||
await request(server).get('/api/v1/chats').expect(401);
|
||||
await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.set('X-User-Id', user.id)
|
||||
.expect(401);
|
||||
await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.set('Authorization', 'Bearer unknown-token-value')
|
||||
.expect(503);
|
||||
const res = await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(503);
|
||||
expect(res.body.error.code).toBe('unavailable');
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `nodb_${randomUUID().slice(0, 8)}`,
|
||||
display_name: 'X',
|
||||
password: 'Long-enough-pass-1',
|
||||
})
|
||||
.expect(503);
|
||||
});
|
||||
|
||||
it('неожиданное исключение — 500 internal_error без деталей, с X-Request-Id и X-Instance-Id', async () => {
|
||||
const { app, server } = await start();
|
||||
const user = await registerUser(server, 'boom');
|
||||
jest
|
||||
.spyOn(app.get(ChatsService), 'listForMember')
|
||||
.mockRejectedValueOnce(new Error('secret internal details'));
|
||||
const res = await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(500);
|
||||
expect(res.body.error.code).toBe('internal_error');
|
||||
expect(JSON.stringify(res.body)).not.toMatch(/secret/);
|
||||
expect(res.body.error.request_id).toBe(res.headers['x-request-id']);
|
||||
expect(res.headers['x-instance-id']).toBeTruthy();
|
||||
});
|
||||
|
||||
it('откатывает создание чата целиком, если один из участников не существует', async () => {
|
||||
const { app, server } = await start();
|
||||
const alice = await registerUser(server, 'rollback');
|
||||
const title = `rollback ${randomUUID()}`;
|
||||
const res = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title, member_ids: [alice.id, randomUUID()] })
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
const prisma = app.get(PrismaService);
|
||||
expect(await prisma.chat.count({ where: { title } })).toBe(0);
|
||||
expect(
|
||||
await prisma.chatMember.count({ where: { userId: alice.id } }),
|
||||
).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
export default function globalSetup(): void {
|
||||
execSync('npx prisma migrate deploy', { stdio: 'inherit' });
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
} from '@nestjs/platform-fastify';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { randomUUID } from 'crypto';
|
||||
import request from 'supertest';
|
||||
import { AppModule } from '../src/app.module';
|
||||
import { configureApp } from '../src/configure-app';
|
||||
|
||||
export const PASSWORD = 'Correct-Horse-Battery-42';
|
||||
|
||||
export interface TestUser {
|
||||
id: string;
|
||||
username: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
export async function createTestApp(
|
||||
env: Record<string, string> = {},
|
||||
setup: (app: NestFastifyApplication) => void = () => undefined,
|
||||
): Promise<{
|
||||
app: INestApplication;
|
||||
server: any;
|
||||
}> {
|
||||
const saved = { ...process.env };
|
||||
Object.assign(process.env, env);
|
||||
let app: NestFastifyApplication;
|
||||
try {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
app = moduleRef.createNestApplication<NestFastifyApplication>(
|
||||
new FastifyAdapter(),
|
||||
);
|
||||
} finally {
|
||||
process.env = saved;
|
||||
}
|
||||
configureApp(app);
|
||||
setup(app);
|
||||
await app.listen(0, '127.0.0.1');
|
||||
return { app, server: app.getHttpServer() };
|
||||
}
|
||||
|
||||
export function basic(username: string, password: string): string {
|
||||
return `Basic ${Buffer.from(`${username}:${password}`, 'utf8').toString('base64')}`;
|
||||
}
|
||||
|
||||
export function bearer(user: TestUser): string {
|
||||
return `Bearer ${user.token}`;
|
||||
}
|
||||
|
||||
export async function login(
|
||||
server: any,
|
||||
username: string,
|
||||
password = PASSWORD,
|
||||
): Promise<string> {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/auth/sessions')
|
||||
.set('Authorization', basic(username, password))
|
||||
.expect(201);
|
||||
return res.body.token;
|
||||
}
|
||||
|
||||
export async function registerUser(
|
||||
server: any,
|
||||
label: string,
|
||||
): Promise<TestUser> {
|
||||
const username = `u_${label}_${randomUUID().slice(0, 8)}`;
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username, display_name: `User ${label}`, password: PASSWORD })
|
||||
.expect(201);
|
||||
return { id: res.body.id, username, token: await login(server, username) };
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { PrismaService } from '../src/db/prisma.service';
|
||||
import { bearer, createTestApp, registerUser, TestUser } from './helpers';
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
describe('Идемпотентность отправки и X-Instance-Id (e2e)', () => {
|
||||
const apps: INestApplication[] = [];
|
||||
let server: any;
|
||||
let replica: any;
|
||||
let prisma: PrismaService;
|
||||
|
||||
beforeAll(async () => {
|
||||
const first = await createTestApp();
|
||||
const second = await createTestApp();
|
||||
apps.push(first.app, second.app);
|
||||
server = first.server;
|
||||
replica = second.server;
|
||||
prisma = first.app.get(PrismaService);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await Promise.all(apps.map((app) => app.close()));
|
||||
});
|
||||
|
||||
async function setup(label: string) {
|
||||
const alice = await registerUser(server, label);
|
||||
const chat = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('Authorization', bearer(alice))
|
||||
.send({ title: 'Idem', member_ids: [alice.id] })
|
||||
.expect(201);
|
||||
return { alice, path: `/api/v1/chats/${chat.body.id}/messages` };
|
||||
}
|
||||
|
||||
function send(target: any, user: TestUser, path: string, key: string | null, body: object) {
|
||||
const req = request(target).post(path).set('Authorization', bearer(user));
|
||||
return (key === null ? req : req.set('Idempotency-Key', key)).send(body);
|
||||
}
|
||||
|
||||
async function countMessages(path: string, user: TestUser): Promise<number> {
|
||||
const res = await request(server)
|
||||
.get(`${path}?limit=100`)
|
||||
.set('Authorization', bearer(user))
|
||||
.expect(200);
|
||||
return res.body.items.length;
|
||||
}
|
||||
|
||||
it('требует Idempotency-Key правильного формата', async () => {
|
||||
const { alice, path } = await setup('keyfmt');
|
||||
for (const key of [null, '', 'has space', 'semi;colon', 'slash/key', 'x'.repeat(129)]) {
|
||||
const res = await send(server, alice, path, key, { text: 'x' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
}
|
||||
await send(server, alice, path, 'A-z_0.9:' + 'k'.repeat(120), { text: 'x' }).expect(201);
|
||||
});
|
||||
|
||||
it('повтор с тем же ключом и телом возвращает тот же 201 и то же сообщение', async () => {
|
||||
const { alice, path } = await setup('replay');
|
||||
const key = randomUUID();
|
||||
const first = await send(server, alice, path, key, { text: 'Привет 👋' }).expect(201);
|
||||
const again = await send(replica, alice, path, key, { text: 'Привет 👋' }).expect(201);
|
||||
expect(again.body).toEqual(first.body);
|
||||
expect(await countMessages(path, alice)).toBe(1);
|
||||
});
|
||||
|
||||
it('тот же ключ с другим телом — 409, сообщение не создаётся', async () => {
|
||||
const { alice, path } = await setup('conflict');
|
||||
const key = randomUUID();
|
||||
await send(server, alice, path, key, { text: 'первое' }).expect(201);
|
||||
const res = await send(server, alice, path, key, { text: 'другое' }).expect(409);
|
||||
expect(res.body.error.code).toBe('conflict');
|
||||
expect(await countMessages(path, alice)).toBe(1);
|
||||
});
|
||||
|
||||
it('20 параллельных запросов с одним ключом через два экземпляра создают ровно одно сообщение', async () => {
|
||||
const { alice, path } = await setup('parallel');
|
||||
const key = randomUUID();
|
||||
const responses = await Promise.all(
|
||||
Array.from({ length: 20 }, (_, i) =>
|
||||
send(i % 2 ? replica : server, alice, path, key, { text: 'одно' }),
|
||||
),
|
||||
);
|
||||
expect(responses.map((r) => r.status)).toEqual(Array(20).fill(201));
|
||||
expect(new Set(responses.map((r) => r.body.id)).size).toBe(1);
|
||||
expect(await countMessages(path, alice)).toBe(1);
|
||||
});
|
||||
|
||||
it('область ключа — пользователь и чат: одинаковый ключ у разных пользователей и чатов независим', async () => {
|
||||
const a = await setup('scopea');
|
||||
const b = await setup('scopeb');
|
||||
const key = randomUUID();
|
||||
const one = await send(server, a.alice, a.path, key, { text: 'x' }).expect(201);
|
||||
const two = await send(server, b.alice, b.path, key, { text: 'x' }).expect(201);
|
||||
expect(one.body.id).not.toBe(two.body.id);
|
||||
});
|
||||
|
||||
it('повтор заново проверяет сессию', async () => {
|
||||
const { alice, path } = await setup('recheck');
|
||||
const key = randomUUID();
|
||||
await send(server, alice, path, key, { text: 'x' }).expect(201);
|
||||
await request(server)
|
||||
.delete('/api/v1/auth/sessions/current')
|
||||
.set('Authorization', bearer(alice))
|
||||
.expect(204);
|
||||
await send(server, alice, path, key, { text: 'x' }).expect(401);
|
||||
});
|
||||
|
||||
it('после IDEMPOTENCY_TTL_SECONDS ключ можно использовать заново', async () => {
|
||||
const { app, server: short } = await createTestApp({ IDEMPOTENCY_TTL_SECONDS: '1' });
|
||||
apps.push(app);
|
||||
const { alice, path } = await setup('ttl');
|
||||
const key = randomUUID();
|
||||
const first = await send(short, alice, path, key, { text: 'x' }).expect(201);
|
||||
await sleep(1500);
|
||||
const second = await send(short, alice, path, key, { text: 'y' }).expect(201);
|
||||
expect(second.body.id).not.toBe(first.body.id);
|
||||
expect(await prisma.idempotencyKey.count({ where: { key } })).toBe(1);
|
||||
});
|
||||
|
||||
it('X-Instance-Id есть в успешных ответах, ошибках и health и стабилен в процессе', async () => {
|
||||
const ids = new Set<string>();
|
||||
for (const res of [
|
||||
await request(server).get('/health/live').expect(200),
|
||||
await request(server).get('/health/ready').expect(200),
|
||||
await request(server).get('/api/v1/users/me').expect(401),
|
||||
await request(server).post('/api/v1/users').send('{bad').set('Content-Type', 'application/json').expect(400),
|
||||
]) {
|
||||
expect(res.headers['x-instance-id']).toBeTruthy();
|
||||
ids.add(res.headers['x-instance-id']);
|
||||
}
|
||||
expect(ids.size).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"globalSetup": "<rootDir>/global-setup.ts",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "experiments", "**/*spec.ts"]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": false,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2021",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"strictNullChecks": true,
|
||||
"noImplicitAny": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"esModuleInterop": true,
|
||||
"types": ["node", "jest"]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user