forked from mtusi2026/mtusi2026lab2
feat: lab2 done
This commit is contained in:
+41
-7
@@ -1,11 +1,45 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_PUBLIC_PORT=8080
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
|
||||
# Credentials for the local synthetic stand. Never commit a real .env.
|
||||
# Rationale and tradeoffs: REPORT.md, section "Конфигурация и секреты".
|
||||
# POSTGRES_PASSWORD initializes the database volume; DATABASE_URL must use the
|
||||
# same password, otherwise the API cannot connect to an existing volume.
|
||||
POSTGRES_DB=messenger
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=change-me
|
||||
DATABASE_URL=postgresql://messenger:change-me@postgres:5432/messenger
|
||||
REDIS_URL=redis://redis:6379
|
||||
|
||||
# Application tuning
|
||||
DATABASE_POOL_MAX=10
|
||||
DATABASE_CONNECTION_TIMEOUT_MS=5000
|
||||
DATABASE_STATEMENT_TIMEOUT_MS=5000
|
||||
CACHE_TTL_SECONDS=30
|
||||
CACHE_MODE=protected
|
||||
CACHE_LOCK_TTL_MS=1000
|
||||
CACHE_MISS_DELAY_MS=0
|
||||
METRICS_TOKEN=change-me
|
||||
|
||||
# Clean clone (run once, then `docker compose --env-file .env up -d --build`):
|
||||
# cp .env.example .env
|
||||
# password=$(openssl rand -hex 32)
|
||||
# sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$password/" .env
|
||||
# sed -i "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://messenger:$password@postgres:5432/messenger|" .env
|
||||
# sed -i "s/^METRICS_TOKEN=.*/METRICS_TOKEN=$(openssl rand -hex 16)/" .env
|
||||
# unset password
|
||||
#
|
||||
# Existing postgres-data keeps its original password: changing POSTGRES_PASSWORD
|
||||
# alone does not rotate it. Update DATABASE_URL to the volume's password, or
|
||||
# rotate the password inside PostgreSQL explicitly.
|
||||
#
|
||||
# Alternative for docker-secrets or Swarm deployments: point DATABASE_URL_FILE /
|
||||
# REDIS_URL_FILE at mounted secret files instead of inline URLs. The application
|
||||
# reads the file, trims it, and validates it exactly like an inline value.
|
||||
|
||||
# Optional file-based secret override (uncomment to use):
|
||||
# DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# REDIS_URL_FILE=/run/secrets/redis_url
|
||||
|
||||
@@ -1,18 +1,78 @@
|
||||
## Лабораторная 2
|
||||
|
||||
Автор / группа: TODO
|
||||
Целевая оценка (3/4/5): TODO
|
||||
Трек 5, если заявлен: TODO
|
||||
Автор / группа: Тюнин Илья БВТ2303
|
||||
Целевая оценка (3/4/5): 5
|
||||
Трек 1, если заявлен: Трек 1 «Согласованность кэша» — при 32 конкурентных чтениях холодной страницы × 5 повторностей: **160 SQL-запросов истории в naive против 5 в protected (−96,9 %)**, read-after-write подтверждён, сессия и история переживают рестарт Redis
|
||||
|
||||
Что реализовано и что перенесено: TODO
|
||||
Команды запуска из чистого clone: TODO
|
||||
Результаты проверок и ссылка на REPORT.md: TODO
|
||||
Ограничения / известные ошибки: TODO
|
||||
Источники и использование ИИ: TODO
|
||||
### Что реализовано
|
||||
|
||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [ ] Контракт и публичные тесты не ослаблены.
|
||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
- **PostgreSQL 16.4 — источник истины**: `users`, `chats`, `chat_members`, `messages`; версионируемые миграции `001_initial.sql`, `002_timestamp_precision.sql`; raw `pg.Pool` с ограниченным пулом, connection/statement timeout и параметризованными запросами, без ORM.
|
||||
- **Транзакционные границы**: создание чата (валидация участников + chat + membership) и отправка сообщения (membership + insert + `message_version`) — в одной транзакции с rollback; проверено отсутствие частичных данных.
|
||||
- **Redis 7.4.2 с AOF — серверные Bearer-сессии** с TTL, expiry и logout; одновременно версионированный кэш истории с lock на конкретную страницу `(chat_id, message_version, cursor, limit)` и fallback в PostgreSQL при недоступности Redis.
|
||||
- **Аутентификация по контракту lab2**: Basic только на `POST /auth/sessions` (UTF-8, первый `:`), Bearer на бизнес-endpoint, `X-User-Id` не аутентифицирует и не подменяет владельца, Argon2id, opaque-токен 256 бит.
|
||||
- **Воспроизводимый стенд**: Compose с pinned-образами, именованными volumes, healthchecks, сервисом миграций перед API, конфигурацией через `.env`.
|
||||
- **Наблюдаемость**: token-gated `GET /internal/metrics` и `POST /internal/metrics/reset` — SQL-метки, операции Redis, cache hit/miss/lock wait, session get/set/del, request count, агрегаты латентности; деградации кэша и зависимостей пишутся счётчиками и `warn`-логами, а не проглатываются.
|
||||
- **Перенесено из lab1** с объявленным переходом: health, регистрация/пользователи, чаты и участники, сообщения, keyset-пагинация — переведены на новую аутентификацию.
|
||||
|
||||
Подробности решения — [`REPORT.md`](../REPORT.md) (архитектура, схема, транзакции, политика кэша, команды, ограничения).
|
||||
Проверки уровня 3/4 — [`evidence/level3-4-verification.md`](../evidence/level3-4-verification.md).
|
||||
Трек 1 — [`evidence/track1-cache-consistency.md`](../evidence/track1-cache-consistency.md) и [`evidence/track1-explain.md`](../evidence/track1-explain.md).
|
||||
Навигация по доказательствам — [`evidence/README.md`](../evidence/README.md).
|
||||
Ручной клиент для разбора API — [`bruno/README.md`](../bruno/README.md).
|
||||
|
||||
### Команды запуска из чистого clone
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
password=$(openssl rand -hex 32)
|
||||
sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$password/" .env
|
||||
sed -i "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://messenger:$password@postgres:5432/messenger|" .env
|
||||
sed -i "s/^METRICS_TOKEN=.*/METRICS_TOKEN=$(openssl rand -hex 16)/" .env
|
||||
unset password
|
||||
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build # postgres/redis healthy, migrate exit 0, api healthy
|
||||
curl -fsS http://localhost:8080/health/ready
|
||||
```
|
||||
|
||||
Пояснения по переменным и паролю существующего volume — [`.env.example`](../.env.example) и [REPORT.md § «Конфигурация и секреты»](../REPORT.md).
|
||||
|
||||
### Результаты проверок (фактический вывод)
|
||||
|
||||
```text
|
||||
make check PASS
|
||||
make validate PASS
|
||||
make test BASE_URL=http://localhost:8080 PASS: lab2 public API scenario
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh PASS: preserved confirmed data and existing session
|
||||
(cd app && npm run build) PASS
|
||||
(cd app && npm test) 5 files, 13 tests passed
|
||||
(cd app && npx tsc --noEmit) PASS
|
||||
integration suite (реальные PostgreSQL/Redis) 7 passed | 1 skipped
|
||||
то же с SESSION_TTL_SECONDS=2 8 passed (expiry → 401)
|
||||
коллекция Bruno (bru run -r --env local) 28 запросов, 56 проверок — все зелёные
|
||||
```
|
||||
|
||||
Трек 1 (32 конкурентных GET × 5 повторностей, `CACHE_MISS_DELAY_MS=75`):
|
||||
|
||||
| Режим | SQL `messages.history` | Cache hits | Ошибок | p50, мс |
|
||||
| --------- | ---------------------: | ---------: | -----: | ------: |
|
||||
| naive | 160 | 0 | 0 | ≈ 89 |
|
||||
| protected | 5 | 155 | 0 | ≈ 20 |
|
||||
|
||||
Отдельно проверены: гонка одинакового username (201 + 409, в таблице ровно 1 строка, unique-индекс), rollback при неизвестном участнике чата (`400`, строк не осталось), отказы Redis и PostgreSQL (`/health/ready` 503, анонимный доступ не выдаётся, процесс API жив, после старта — 200 с тем же токеном), `EXPLAIN (ANALYZE, BUFFERS)` на 10 002 сообщениях (Index Scan по `messages_chat_created_id_idx`, keyset-предикат в `Index Cond`).
|
||||
|
||||
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [x] Контракт и публичные тесты не ослаблены (`contracts/` и `tests/` не изменялись).
|
||||
- [x] `make check` и `make test` выполнены; приложен реальный вывод (выше и в evidence).
|
||||
- [x] Сценарии отказов/безопасности своего уровня воспроизведены (отказы Redis/PostgreSQL, expiry, logout/replay, spoofing, rollback — [журнал](../evidence/level3-4-verification.md)).
|
||||
- [x] Все секреты и приватные ключи находятся вне Git: `.env` и локальные секреты покрыты `.gitignore`, в отчёте и evidence нет токенов и паролей.
|
||||
- [x] README задания сохранён, `REPORT.md` содержит инструкцию именно этого решения.
|
||||
|
||||
### Ограничения / известные ошибки
|
||||
|
||||
- Метрики локальны процессу API и сбрасываются при его рестарте; при нескольких репликах их нельзя суммировать как распределённый снимок.
|
||||
- Измерения трека 1 — closed-loop на одном хосте (32 конкурентных читателя, 5 повторностей): это не production-пропускная способность.
|
||||
- `redis-data` хранит действующие сессии: удаление volume осознанно разлогинивает пользователей; AOF плюс сохранённый volume — проверенная граница durability.
|
||||
- `CACHE_MODE=naive` и `CACHE_MISS_DELAY_MS` предназначены только для эксперимента и задаются переменными окружения при пересоздании контейнера `api` (например, `CACHE_MODE=naive CACHE_MISS_DELAY_MS=75 docker compose --env-file .env up -d api`); задержка влияет только на naive-путь.
|
||||
- Порты PostgreSQL/Redis наружу не публикуются, поэтому интеграционный набор запускается с адресами контейнеров (команда в [REPORT.md](../REPORT.md) § «Команды проверок»).
|
||||
- Сырые прогоны бенчмарка не коммитятся (локальные идентификаторы); их хеши — в [`evidence/track1-cache-consistency.md`](../evidence/track1-cache-consistency.md) §8.
|
||||
|
||||
@@ -30,3 +30,6 @@ coverage/
|
||||
.vscode/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
secrets/
|
||||
.env
|
||||
evidence/track1-raw/
|
||||
|
||||
+6
-2
@@ -2,11 +2,15 @@ FROM node:25.7.0-slim AS build
|
||||
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends python3 make g++ \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY app/package.json app/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY app/ ./
|
||||
RUN npm run build
|
||||
RUN npm run build && npm prune --omit=dev
|
||||
|
||||
FROM node:25.7.0-slim AS runtime
|
||||
|
||||
@@ -16,7 +20,7 @@ ENV NODE_ENV=production
|
||||
ENV APP_PORT=8080
|
||||
ENV DRAIN_DELAY_MS=5000
|
||||
COPY --from=build /usr/src/app/package.json /usr/src/app/package-lock.json ./
|
||||
RUN npm ci --omit=dev && npm cache clean --force
|
||||
COPY --from=build /usr/src/app/node_modules ./node_modules
|
||||
COPY --from=build /usr/src/app/dist ./dist
|
||||
|
||||
USER node
|
||||
|
||||
@@ -1,37 +1,228 @@
|
||||
# Отчёт — лабораторная 2
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Тюнин Илья БВТ2303
|
||||
- Целевая оценка: 5, трек 1 («Согласованность кэша»)
|
||||
- Commit/PR: [вставьте после публикации]
|
||||
|
||||
## Запуск из чистого clone
|
||||
## Карта документации
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
| Документ | Что содержит |
|
||||
| -------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Этот отчёт | Архитектура, схема данных, транзакции, аутентификация, политика кэша, методика и результаты трека 1, наблюдаемые проверки, ограничения. |
|
||||
| [`evidence/README.md`](evidence/README.md) | Индекс доказательств: что какой файл подтверждает и как всё регенерировать. |
|
||||
| [`evidence/level3-4-verification.md`](evidence/level3-4-verification.md) | Журнал проверок уровня 3/4 с наблюдаемым выводом команд и таблицей найденных дефектов. |
|
||||
| [`evidence/track1-cache-consistency.md`](evidence/track1-cache-consistency.md) | Трек 1: окружение, методика, числа по повторностям, сравнение, read-after-write, рестарт Redis, хеши артефактов. |
|
||||
| [`evidence/track1-explain.md`](evidence/track1-explain.md) | Тексты анализируемых SQL-запросов и `EXPLAIN (ANALYZE, BUFFERS)`. |
|
||||
| [`.github/pull_request_template.md`](.github/pull_request_template.md) | Краткая сводка работы, команды запуска, результаты проверок, чек-лист сдачи. |
|
||||
| [`tests/README.md`](tests/README.md) | Публичные проверки репозитория (`make check`, `make test`, persistence, load, TLS). |
|
||||
| [`docs/architecture/`](docs/architecture/README.md) | Граф модулей и провайдеров NestJS (`npm run graph`). |
|
||||
| [`bruno/README.md`](bruno/README.md) | Коллекция Bruno: ручные запросы на все эндпоинты, негативные кейсы и автосохранение токенов/ID между запросами. |
|
||||
| [`scripts/track1_cache_benchmark.py`](scripts/track1_cache_benchmark.py), [`scripts/track1_verify.py`](scripts/track1_verify.py) | Инструменты измерения трека 1 и проверки рестарта Redis. |
|
||||
| [`scripts/restart.sh`](scripts/restart.sh) | Хук перезапуска для `make test-persistence`. |
|
||||
|
||||
## Архитектура и решения
|
||||
## Архитектура и роли компонентов
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```text
|
||||
Client
|
||||
-> Fastify/Nest API
|
||||
AuthController (Basic -> opaque Bearer session)
|
||||
CurrentUserGuard (Bearer -> Redis session -> PostgreSQL user)
|
||||
UsersController / ChatsController / MessagesController
|
||||
-> UsersRepository -> pg.Pool -> PostgreSQL
|
||||
-> ChatsRepository -> pg.Pool -> PostgreSQL (transaction)
|
||||
-> MessagesRepository-> pg.Pool -> PostgreSQL (transaction)
|
||||
-> MessagesCacheService -> Redis versioned message page
|
||||
-> SessionRepository -> Redis session:{token} (AOF)
|
||||
-> MetricsService -> token-gated /internal/metrics
|
||||
```
|
||||
|
||||
## Доказательства критериев
|
||||
Источник истины:
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
- PostgreSQL — пользователи, чаты, membership, сообщения.
|
||||
- Redis — действующие безопасные сессии (AOF persistence) и производный кэш истории.
|
||||
- Удаление Redis cache не теряет подтверждённые данные: они восстанавливаются из PostgreSQL.
|
||||
- Отказ Redis не даёт анонимного доступа: сессионный путь возвращает ограниченную 503.
|
||||
- Отказ PostgreSQL не убивает процесс API и даёт ограниченную 503.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
### Схема данных и миграции
|
||||
|
||||
## Эксперименты и отказы
|
||||
`001_initial.sql`:
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
- `users(id uuid pk, username unique, display_name, password_hash, created_at)`;
|
||||
- `chats(id uuid pk, title, created_at, message_version bigint)`;
|
||||
- `chat_members(chat_id, user_id)` — composite PK, cascade FK;
|
||||
- `messages(id, chat_id, sender_id, text, created_at)`, FK на chat и на member;
|
||||
- `messages_chat_created_id_idx (chat_id, created_at, id)`;
|
||||
- `chat_members_user_chat_idx (user_id, chat_id)`.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
`002_timestamp_precision.sql` приводит `created_at` к `timestamptz(3)`, чтобы значения совпадали с millisecond timestamps JavaScript. Без этого следующая страница keyset-пагинации повторяла последнее сообщение предыдущей.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
Migration runner сам находит `NNN_*.sql`, сортирует по имени и применяет каждую незаписанную миграцию в отдельной транзакции через `schema_migrations`. Повторный запуск — no-op; сиды не выполняются.
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
### Транзакционные границы
|
||||
|
||||
Создание чата: валидация `member_ids` через `ANY($1::uuid[])`, вставка `chats`, вставка всех `chat_members`, commit либо полный rollback. Создание сообщения: проверка membership, вставка `messages`, инкремент `chats.message_version`, commit либо rollback.
|
||||
|
||||
## Аутентификация и доступ
|
||||
|
||||
- `POST /api/v1/users` — регистрация с паролем 12–128 code points; Argon2id.
|
||||
- `POST /api/v1/auth/sessions` — только Basic, UTF-8, разделение по первому `:`; тело не принимается.
|
||||
- Токен — 32 случайных байта (Base64URL), серверная сессия в Redis с TTL.
|
||||
- Бизнес-endpoint — только Bearer; истёкший/отозванный/неизвестный токен → 401 + `WWW-Authenticate: Bearer realm="messenger"`.
|
||||
- `X-User-Id` не аутентифицирует и не подменяет владельца сессии.
|
||||
- `DELETE /api/v1/auth/sessions/current` → 204 без тела; повтор с тем же токеном → 401.
|
||||
- Ответы 401 содержат корректный challenge: Basic для создания сессии, Bearer для остальных.
|
||||
|
||||
## Политика кэша и трек 1
|
||||
|
||||
Ключ страницы: `messages:{chat_id}:v{message_version}:c{cursor|start}:l{limit}`.
|
||||
|
||||
Protected режим: exact-page lock `lock:{cache_key}` (`SET NX PX` + compare-owner Lua unlock), ограниченные повторы, повторная проверка кэша, запись результата владельцем, best-effort запись кэша и fallback в PostgreSQL при недоступности Redis. Любой commit сообщения увеличивает `message_version`, поэтому старые страницы становятся недостижимыми.
|
||||
|
||||
Naive режим — управляемый baseline без распределённой блокировки; `CACHE_MISS_DELAY_MS` расширяет окно гонки.
|
||||
|
||||
Гипотеза: при одном холодном ключе и `N` конкурентных читателях naive порождает около `N` SQL-запросов истории, protected — один запрос владельца, остальные ждут и попадают в кэш.
|
||||
|
||||
## Воспроизводимый запуск
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
password=$(openssl rand -hex 32)
|
||||
sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$password/" .env
|
||||
sed -i "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://messenger:$password@postgres:5432/messenger|" .env
|
||||
sed -i "s/^METRICS_TOKEN=.*/METRICS_TOKEN=$(openssl rand -hex 16)/" .env
|
||||
unset password
|
||||
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build
|
||||
curl -fsS http://localhost:8080/health/ready
|
||||
```
|
||||
|
||||
- `postgres:16.4-alpine` c named volume `postgres-data`;
|
||||
- `redis:7.4.2-alpine`, AOF (`appendonly yes`, `appendfsync everysec`), named volume `redis-data`;
|
||||
- одноразовый сервис `migrate`;
|
||||
- `api` с healthcheck `/health/ready`.
|
||||
|
||||
### Конфигурация и секреты
|
||||
|
||||
Все параметры, включая `POSTGRES_PASSWORD`, `DATABASE_URL` и `REDIS_URL`, задаются в `.env`
|
||||
(вне Git). Это сознательный выбор для локального синтетического стенда:
|
||||
|
||||
- `.env` уже игнорируется `.gitignore`; отдельных файлов секретов и лишнего маппинга не требуется;
|
||||
- значения видны через `docker inspect`/`/proc/<pid>/environ` — для учебного стенда с
|
||||
синтетическими данными это допустимо, для production нужен внешний secret store;
|
||||
- `postgres-data` хранит пароль, заданный при первой инициализации: смена `POSTGRES_PASSWORD`
|
||||
сама по себе его не меняет, поэтому `DATABASE_URL` должен указывать на пароль этого volume;
|
||||
- файловый вариант (`DATABASE_URL_FILE`, `REDIS_URL_FILE`, docker secrets/Swarm) поддержан в
|
||||
конфигурации как опциональная альтернатива и описан в `.env.example`.
|
||||
|
||||
`scripts/restart.sh` перезапускает `postgres redis api` и ждёт готовности, не удаляя volumes и не выполняя `FLUSHALL`.
|
||||
|
||||
## Track 1: методика и результаты
|
||||
|
||||
Методика: режим кэша и задержка промаха задаются переменными окружения при пересоздании контейнера (`CACHE_MODE`, `CACHE_MISS_DELAY_MS`; shell-значение перекрывает `.env`). Каждая повторность использует новый чат (холодный ключ), поэтому `FLUSHALL` не нужен. Барьер синхронизирует старт конкурентных GET, метрики сбрасываются через `POST /internal/metrics/reset`.
|
||||
|
||||
Важно: `CACHE_MISS_DELAY_MS` действует только в naive-пути (пауза между промахом и запросом в PostgreSQL) и намеренно расширяет окно гонки. Protected-путь задержку не использует, поэтому замеренная разница p50/p95 между режимами включает эти 75 мс и не является «честным» сравнением скорости; независимая от задержки метрика — число SQL-запросов истории.
|
||||
|
||||
Команды:
|
||||
|
||||
```sh
|
||||
printf '%s' "$METRICS_TOKEN" > /tmp/track1-metrics-token
|
||||
CACHE_MODE=naive CACHE_MISS_DELAY_MS=75 docker compose --env-file .env up -d api
|
||||
python3 scripts/track1_cache_benchmark.py --base-url http://localhost:8080 --mode naive \
|
||||
--concurrency 32 --repetitions 5 --metrics-token-file /tmp/track1-metrics-token \
|
||||
--runtime-version node=25.7.0 --runtime-version postgres=16.4 --runtime-version redis=7.4.2 \
|
||||
--output evidence/track1-raw/naive.json
|
||||
CACHE_MODE=protected docker compose --env-file .env up -d api
|
||||
python3 scripts/track1_cache_benchmark.py --base-url http://localhost:8080 --mode protected \
|
||||
--concurrency 32 --repetitions 5 --metrics-token-file /tmp/track1-metrics-token \
|
||||
--runtime-version node=25.7.0 --runtime-version postgres=16.4 --runtime-version redis=7.4.2 \
|
||||
--output evidence/track1-raw/protected.json
|
||||
python3 scripts/track1_verify.py --summary \
|
||||
--naive-raw evidence/track1-raw/naive.json --protected-raw evidence/track1-raw/protected.json \
|
||||
--output evidence/track1-cache-consistency.md
|
||||
```
|
||||
|
||||
Наблюдено (concurrency 32, 5 повторностей, 160 успешных GET в каждом режиме, ошибок 0):
|
||||
|
||||
| Режим | `messages.history` SQL | Cache misses | Cache hits | Lock waits |
|
||||
| --------- | ---------------------: | -----------: | ---------: | ---------: |
|
||||
| naive | 160 | 160 | 0 | 0 |
|
||||
| protected | 5 | 46 | 155 | 41 |
|
||||
|
||||
Снижение числа SQL-запросов истории: **160 → 5 (96.9 %)**. Латентность успешных запросов: naive p50 ≈ 82–117 ms, protected p50 ≈ 28–44 ms (сырые значения в `evidence/track1-raw/`). Эта разница не является чистым сравнением скорости: в naive-путь искусственно добавлена пауза `CACHE_MISS_DELAY_MS=75` (задержка применяется только в naive), тогда как protected её не использует. Независимая от задержки метрика — число SQL-запросов истории.
|
||||
|
||||
Read-after-write (protected, вторая действующая сессия): `asserted=true`, `stale_observed=false`.
|
||||
|
||||
Рестарт Redis с сохранением AOF-volume и последующим удалением только `messages:*`:
|
||||
|
||||
```json
|
||||
{
|
||||
"restart_redis": true,
|
||||
"same_token_users_me": true,
|
||||
"history_equal": true,
|
||||
"cache_eviction": { "requested": true, "message_keys_deleted": 9 }
|
||||
}
|
||||
```
|
||||
|
||||
## Уровень 3/4: наблюдаемые проверки
|
||||
|
||||
| Проверка | Команда/сценарий | Наблюдаемый результат |
|
||||
| ---------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
||||
| Публичный smoke | `make test` | `PASS: lab2 public API scenario` |
|
||||
| Сохранность через полный рестарт | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | `PASS: persistence preserved confirmed data and existing session` |
|
||||
| Интеграционный набор (реальные PG/Redis) | `npx vitest run --config vitest.config.e2e.ts` | 7 passed, 1 gated |
|
||||
| То же с `SESSION_TTL_SECONDS=2` | тот же набор с TTL=2 | 8 passed (включая expiry → 401) |
|
||||
| Гонка одинакового username | набор: два одновременных POST + `select count(*)` | 201 и 409; в `users` ровно 1 строка (гарантия — unique index `users_username_key`, ошибка `23505` → 409) |
|
||||
| Rollback чата с неизвестным участником | HTTP 400 + `select count(*)` | 400; строк в `chats` — 0 |
|
||||
| Индекс истории | `EXPLAIN (ANALYZE, BUFFERS)` на 10 002 строках | `Index Scan using messages_chat_created_id_idx` для первой страницы (0.040 мс) и для keyset-продолжения (0.048 мс) |
|
||||
| Отказ Redis | stop redis | `/health/ready` 503, `/users/me` 503 (анонимного доступа нет), после старта — 200 |
|
||||
| Отказ PostgreSQL | stop postgres | `/health/ready` 503, `/users/me` 503; процесс API жив; после старта — 200 с тем же токеном |
|
||||
| Логин/логаут/подмена | набор + `X-User-Id` | Basic на бизнес-endpoint 401, `X-User-Id` не меняет владельца, replay после logout 401 |
|
||||
| Ручной клиент (Bruno) | `bru run -r --env local ...` из `bruno/` | 28 запросов, 56 проверок — все зелёные (включая негативные и метрики) |
|
||||
|
||||
Отдельно исправлен реальный дефект: при падении PostgreSQL процесс API завершался из-за необработанного события `error` у idle-клиента пула. Добавлен обработчик `pool.on('error')`, а ошибки доступности БД в фильтре отображаются в ограниченную 503 вместо 500.
|
||||
|
||||
Полный журнал проверок с наблюдаемым выводом команд — [`evidence/level3-4-verification.md`](evidence/level3-4-verification.md); методика и по-повторностные числа трека — [`evidence/track1-cache-consistency.md`](evidence/track1-cache-consistency.md).
|
||||
|
||||
`EXPLAIN` (фрагмент): `Index Scan using messages_chat_created_id_idx on messages`, первая страница `actual time=0.020..0.028 ms` / `Execution Time: 0.040 ms`, keyset-продолжение `Index Cond: ((chat_id = ...) AND (ROW(created_at, id) > ROW(...)))` / `Execution Time: 0.048 ms` — полного скана истории нет, предикат продолжения уходит в индекс. Тексты проанализированных запросов и подготовка данных — [`evidence/track1-explain.md`](evidence/track1-explain.md).
|
||||
|
||||
## Команды проверок
|
||||
|
||||
```sh
|
||||
make check
|
||||
make validate
|
||||
(cd app && npm run build && npm test && npx tsc --noEmit)
|
||||
make test BASE_URL=http://localhost:8080
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
(cd app && API_BASE_URL=http://localhost:8080 \
|
||||
DATABASE_URL=postgresql://messenger:<password>@<pg-host>:5432/messenger \
|
||||
REDIS_URL=redis://<redis-host>:6379 npx vitest run --config ./vitest.config.e2e.ts)
|
||||
```
|
||||
|
||||
Примечание: набор для интеграционных тестов читает `API_BASE_URL`, потому что Vitest сам устанавливает `process.env.BASE_URL`.
|
||||
|
||||
## Наблюдаемость отказов
|
||||
|
||||
`GET /internal/metrics` и `POST /internal/metrics/reset` открыты только с `Authorization: Bearer <METRICS_TOKEN>` и возвращают `{counters, latency_ms}` без секретов и SQL-текста. Счётчики, по которым видно деградацию (а не «тихое» проглатывание ошибок):
|
||||
|
||||
| Счётчик | Когда растёт |
|
||||
| ------------------------------------------------- | --------------------------------------------------------------------------------- |
|
||||
| `cache_hit` / `cache_miss` | попадание/промах страницы |
|
||||
| `cache_lock_wait` / `cache_lock_timeout` | ожидание владельца lock; владелец не успел за отведённые повторы |
|
||||
| `cache_fallback` | Redis недоступен на чтении/lock/повторном чтении, ответ отдан из PostgreSQL |
|
||||
| `cache_write_error` / `cache_unlock_error` | не удалось записать страницу или снять lock (ответ не ломается) |
|
||||
| `cache_corrupt_entry` | повреждённая запись кэша трактуется как промах и перезаписывается |
|
||||
| `database.pool_error` / `database.rollback_error` | обрыв idle-клиента пула; ошибка `ROLLBACK` (исходная ошибка операции сохраняется) |
|
||||
| `redis.error` | ошибка соединения/reconnect Redis |
|
||||
|
||||
Те же события дополнительно пишутся в лог уровнем `warn` с контекстом, поэтому один сбойный запрос уже видно без разбора дампов.
|
||||
|
||||
## Ограничения и границы
|
||||
|
||||
- Метрики локальны процессу API и сбрасываются при его рестарте; PostgreSQL и Redis не затрагиваются.
|
||||
- Измерения выполнены на одном локальном хосте (closed-loop, конкуренция 32, 5 повторностей); это не production-пропускная способность и не распределённая телеметрия.
|
||||
- `redis-data` — источник истины сессий: удаление volume осознанно разлогинивает пользователей; сохранённый AOF — проверенная граница durability.
|
||||
- `CACHE_MODE=naive` предназначен только для эксперимента и не должен включаться в штатном профиле.
|
||||
- Файлы `evidence/track1-raw/*.json` игнорируются git (содержат локальные идентификаторы); в репозитории хранится санитизированная сводка.
|
||||
- Публичные `contracts/` и `tests/` не изменялись.
|
||||
|
||||
+145
-87
@@ -1,114 +1,172 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
# app — API мессенджера (лабораторная 2)
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
NestJS 12 + Fastify, ESM TypeScript. PostgreSQL — источник истины бизнес-данных,
|
||||
Redis — серверные Bearer-сессии и производный кэш истории сообщений.
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
Общая документация (в корне репозитория):
|
||||
|
||||
## Description
|
||||
| Документ | Что содержит |
|
||||
|---|---|
|
||||
| [`../REPORT.md`](../REPORT.md) | архитектура, схема данных, транзакции, политика кэша, команды, результаты проверок и трека 1 |
|
||||
| [`../evidence/README.md`](../evidence/README.md) | индекс доказательств: что подтверждено и как это воспроизвести |
|
||||
| [`../bruno/README.md`](../bruno/README.md) | коллекция ручных запросов ко всем эндпоинтам |
|
||||
| [`../contracts/openapi.json`](../contracts/openapi.json) | нормативный контракт API |
|
||||
| [`../tests/README.md`](../tests/README.md) | публичные проверки репозитория (`make check`, `make test`, persistence) |
|
||||
| [`../docs/architecture/README.md`](../docs/architecture/README.md) | граф модулей NestJS (`npm run graph`) |
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
## Что внутри
|
||||
|
||||
## Project setup
|
||||
|
||||
```bash
|
||||
$ npm install
|
||||
```text
|
||||
src/
|
||||
main.ts bootstrap: Fastify, ValidationPipe, shutdown hooks
|
||||
app.module.ts сборка модулей приложения
|
||||
config/ Zod-схема env + глобальный ConfigModule
|
||||
database/ pg.Pool, транзакции, миграции (001, 002)
|
||||
redis/ клиент Redis (AOF-совместимый, без offline queue)
|
||||
auth/ Basic-вход, Redis-сессии, logout
|
||||
users/ регистрация (Argon2id), профиль
|
||||
chats/ создание чата в транзакции, список и чтение
|
||||
messages/ отправка сообщения, keyset-история
|
||||
cache/ версионированный кэш истории + lock на страницу
|
||||
metrics/ /internal/metrics и /internal/metrics/reset
|
||||
health/ liveness/readiness с проверкой зависимостей
|
||||
common/ guard, exception filter, request-id, cursor, errors
|
||||
test/
|
||||
app.e2e-spec.ts black-box набор против запущенного API (PG + Redis)
|
||||
scripts/
|
||||
graph-modules.ts генератор графа зависимостей (nestjs-spelunker)
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
Принципы: raw `pg.Pool` без ORM, параметризованные запросы, никаких in-memory
|
||||
хранилищ в боевых путях; кэш — производное состояние и всегда допускает
|
||||
восстановление из PostgreSQL; отказ зависимости даёт ограниченную ошибку
|
||||
(`503`), а не аварийное завершение процесса.
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ npm run start
|
||||
## Быстрый старт
|
||||
|
||||
# watch mode
|
||||
$ npm run start:dev
|
||||
Рекомендуемый путь — весь стенд из корня репозитория (PostgreSQL, Redis, миграции, API):
|
||||
|
||||
# production mode
|
||||
$ npm run start:prod
|
||||
```sh
|
||||
cd ..
|
||||
cp .env.example .env
|
||||
password=$(openssl rand -hex 32)
|
||||
sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$password/" .env
|
||||
sed -i "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://messenger:$password@postgres:5432/messenger|" .env
|
||||
docker compose --env-file .env up -d --build
|
||||
curl -fsS http://localhost:8080/health/ready
|
||||
```
|
||||
|
||||
## Run tests
|
||||
Локальный запуск без Docker (нужны доступные PostgreSQL и Redis):
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ npm run test
|
||||
```sh
|
||||
cd app
|
||||
npm ci
|
||||
npm run build
|
||||
|
||||
# e2e tests
|
||||
$ npm run test:e2e
|
||||
export DATABASE_URL=postgresql://messenger:<password>@127.0.0.1:5432/messenger
|
||||
export REDIS_URL=redis://127.0.0.1:6379
|
||||
export APP_PORT=8080
|
||||
node dist/database/migration.runner.js # применяет миграции из dist/database/migrations
|
||||
|
||||
# test coverage
|
||||
$ npm run test:cov
|
||||
npm run start:dev # или npm run start:prod после build
|
||||
```
|
||||
|
||||
## Deployment
|
||||
## Переменные окружения
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
Читаются только через конфигурационный слой (`src/config`), типы и диапазоны
|
||||
проверяет Zod-схема на старте — при некорректном значении приложение падает
|
||||
с понятной ошибкой.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
| Переменная | По умолчанию | Назначение |
|
||||
|---|---|---|
|
||||
| `APP_HOST` / `APP_PORT` | `0.0.0.0` / `8080` | адрес прослушивания |
|
||||
| `APP_ENV` | `lab` | метка окружения |
|
||||
| `DATABASE_URL` | — (обязательна) | строка подключения PostgreSQL |
|
||||
| `REDIS_URL` | — (обязательна) | строка подключения Redis |
|
||||
| `DATABASE_POOL_MAX` | `10` | размер пула соединений |
|
||||
| `DATABASE_CONNECTION_TIMEOUT_MS` | `5000` | таймаут установки соединения |
|
||||
| `DATABASE_STATEMENT_TIMEOUT_MS` | `5000` | таймаут SQL-запроса |
|
||||
| `SESSION_TTL_SECONDS` | `3600` | TTL сессии (минимум 2) |
|
||||
| `CACHE_TTL_SECONDS` | `30` | TTL страницы истории в Redis |
|
||||
| `CACHE_MODE` | `protected` | `protected` (lock на страницу) или `naive` (только для эксперимента) |
|
||||
| `CACHE_LOCK_TTL_MS` | `1000` | TTL lock-а страницы |
|
||||
| `CACHE_MISS_DELAY_MS` | `0` | искусственная пауза на промахе; влияет только на `naive` |
|
||||
| `METRICS_TOKEN` | — (необязательна) | токен доступа к `/internal/metrics*`; без него endpoint закрыт |
|
||||
| `DRAIN_DELAY_MS` | `5000` | окно дрейна при получении сигнала завершения |
|
||||
|
||||
```bash
|
||||
$ npm install -g @nestjs/mau
|
||||
$ mau deploy
|
||||
Поддерживаются также `DATABASE_URL_FILE` / `REDIS_URL_FILE`: если заданы, значение
|
||||
читается из файла (docker secrets / Swarm). Подробности и компромиссы —
|
||||
[`../REPORT.md`](../REPORT.md), раздел «Конфигурация и секреты».
|
||||
|
||||
## Эндпоинты
|
||||
|
||||
Публичный контракт — [`../contracts/openapi.json`](../contracts/openapi.json).
|
||||
|
||||
| Метод и путь | Аутентификация | Назначение |
|
||||
|---|---|---|
|
||||
| `GET /health/live` | нет | процесс жив |
|
||||
| `GET /health/ready` | нет | готовность: PostgreSQL и Redis доступны, иначе `503` |
|
||||
| `POST /api/v1/users` | нет | регистрация с паролем (Argon2id) |
|
||||
| `POST /api/v1/auth/sessions` | `Basic` | вход, выдаёт opaque Bearer-токен |
|
||||
| `DELETE /api/v1/auth/sessions/current` | `Bearer` | отзыв текущей сессии, `204` |
|
||||
| `GET /api/v1/users/me` | `Bearer` | текущий пользователь |
|
||||
| `POST /api/v1/chats` | `Bearer` | создание чата (транзакция) |
|
||||
| `GET /api/v1/chats` | `Bearer` | список доступных чатов |
|
||||
| `GET /api/v1/chats/:chatId` | `Bearer` | чат по id (чужой — `404`) |
|
||||
| `POST /api/v1/chats/:chatId/messages` | `Bearer` | отправка сообщения |
|
||||
| `GET /api/v1/chats/:chatId/messages` | `Bearer` | история, keyset-пагинация `(created_at, id)` |
|
||||
| `GET /internal/metrics` | `Bearer METRICS_TOKEN` | счётчики и агрегаты латентности |
|
||||
| `POST /internal/metrics/reset` | `Bearer METRICS_TOKEN` | сброс счётчиков (`200`) |
|
||||
|
||||
Правила: `Basic` принимается только на создании сессии, бизнес-запросы — только
|
||||
`Bearer`; заголовок `X-User-Id` не аутентифицирует и не подменяет владельца
|
||||
сессии; истёкший, отозванный или неизвестный токен — `401` с соответствующим
|
||||
`WWW-Authenticate`.
|
||||
|
||||
## npm-скрипты
|
||||
|
||||
| Команда | Что делает |
|
||||
|---|---|
|
||||
| `npm run build` | сборка в `dist/` |
|
||||
| `npm run start:dev` | watch-режим |
|
||||
| `npm run start:prod` | запуск собранного приложения (`node dist/main`) |
|
||||
| `npm test` / `npm run test:unit` | unit-тесты (vitest) |
|
||||
| `npm run test:e2e` | black-box набор против запущенного API (см. ниже) |
|
||||
| `npm run lint` | oxlint по `src/` и `test/` |
|
||||
| `npm run format` | prettier |
|
||||
| `npm run graph` | граф модулей и провайдеров через nestjs-spelunker (пишет `../docs/architecture/`) |
|
||||
|
||||
## Тесты
|
||||
|
||||
Unit-тесты не требуют инфраструктуры:
|
||||
|
||||
```sh
|
||||
npm test
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
Интеграционный набор работает по HTTP против запущенного стенда и дополнительно
|
||||
подключается к PostgreSQL (очистка тестовых данных) и Redis:
|
||||
|
||||
## Observability
|
||||
```sh
|
||||
export API_BASE_URL=http://localhost:8080
|
||||
export DATABASE_URL=postgresql://messenger:<password>@<pg-host>:5432/messenger
|
||||
export REDIS_URL=redis://<redis-host>:6379
|
||||
npm run test:e2e
|
||||
```
|
||||
|
||||
In production applications, observability is essential for understanding how your system behaves, detecting issues early, and maintaining reliable performance.
|
||||
Название `API_BASE_URL` (а не `BASE_URL`) выбрано потому, что Vitest сам
|
||||
устанавливает `process.env.BASE_URL` в значение Vite base. Кейс истечения сессии
|
||||
включается переменной `SESSION_TTL_SECONDS=2` и у запущенного API, и у набора.
|
||||
|
||||
[NestJS Observe](https://observe.nestjs.com) automatically instruments your NestJS application, giving you deep visibility into your system with minimal setup:
|
||||
## Метрики
|
||||
|
||||
- **Distributed tracing:** Follow requests across services and understand how they flow through your system.
|
||||
- **Waterfall analysis:** Visualize request execution and identify slow operations, bottlenecks, and unexpected delays.
|
||||
- **Performance analysis:** Analyze application performance in real time and quickly pinpoint areas that need optimization.
|
||||
- **Metrics:** Track key application and infrastructure metrics to understand system health and performance trends.
|
||||
- **Logging:** Centralize and correlate logs with traces and other telemetry to make debugging easier.
|
||||
- **Error tracking:** Detect errors quickly and investigate their root causes with the surrounding context.
|
||||
- **SLA monitoring:** Track service-level objectives and identify when your application is approaching or exceeding defined thresholds.
|
||||
- **Alarms and alerts:** Set up alerts for critical errors, performance degradation, SLA violations, and other anomalies so your team can react quickly.
|
||||
`GET /internal/metrics` возвращает `{counters, latency_ms}`: именованные SQL-метки,
|
||||
операции Redis, `cache_hit`/`cache_miss`/`cache_lock_wait`, `session_get/set/del`,
|
||||
`request_count` и процентили латентности (буфер ограничен). Деградации
|
||||
наблюдаемы отдельными счётчиками: `cache_fallback`, `cache_write_error`,
|
||||
`cache_unlock_error`, `cache_lock_timeout`, `cache_corrupt_entry`,
|
||||
`database.pool_error`, `database.rollback_error`, `redis.error`.
|
||||
|
||||
## Resources
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Auto-instrument your application with [NestJS Observer](https://observer.nestjs.com). Distributed tracing, metrics, and logging made easy. Error tracking and performance monitoring for your NestJS applications.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
|
||||
## Support
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||
Счётчики локальны процессу: при нескольких репликах их нельзя суммировать как
|
||||
распределённый снимок, а рестарт API обнуляет их (данные PostgreSQL и Redis при
|
||||
этом не затрагиваются).
|
||||
|
||||
+8
-1
@@ -3,6 +3,13 @@
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
"deleteOutDir": true,
|
||||
"assets": [
|
||||
{
|
||||
"include": "database/migrations/*.sql",
|
||||
"outDir": "dist"
|
||||
}
|
||||
],
|
||||
"watchAssets": true
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+948
-4
File diff suppressed because it is too large
Load Diff
+10
-1
@@ -20,6 +20,7 @@
|
||||
"test:watch": "vitest",
|
||||
"test:cov": "vitest run --coverage",
|
||||
"test:debug": "vitest --inspect-brk --no-file-parallelism",
|
||||
"graph": "npm run build && DATABASE_URL=postgresql://graph-only.invalid/messenger REDIS_URL=redis://graph-only.invalid:6379 tsx scripts/graph-modules.ts",
|
||||
"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -28,11 +29,15 @@
|
||||
"@nestjs/core": "^12.0.1",
|
||||
"@nestjs/platform-express": "^12.0.1",
|
||||
"@nestjs/platform-fastify": "^12.0.3",
|
||||
"argon2": "^0.45.1",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"fastify": "^5.12.5",
|
||||
"pg": "^8.23.1",
|
||||
"redis": "^6.3.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1"
|
||||
"rxjs": "^7.8.1",
|
||||
"zod": "^4.6.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^12.0.0",
|
||||
@@ -41,12 +46,16 @@
|
||||
"@nestjs/testing": "^12.0.1",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/pg": "^8.23.1",
|
||||
"@types/supertest": "^7.0.0",
|
||||
"@vitest/coverage-v8": "^4.1.2",
|
||||
"dotenv": "^18.0.5",
|
||||
"nestjs-spelunker": "^1.3.2",
|
||||
"oxlint": "^1.58.0",
|
||||
"prettier": "^3.4.2",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.2.2",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^6.0.3",
|
||||
"vite-tsconfig-paths": "^5.1.4",
|
||||
"vitest": "^4.1.2"
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import 'reflect-metadata';
|
||||
import { SpelunkerModule, type DebuggedTree } from 'nestjs-spelunker';
|
||||
import { AppModule } from '../dist/app.module.js';
|
||||
|
||||
function mermaidId(name: string): string {
|
||||
return name.replace(/[^a-zA-Z0-9_]/gu, '_');
|
||||
}
|
||||
|
||||
function findDependencyModule(
|
||||
tree: DebuggedTree[],
|
||||
dependency: string,
|
||||
): DebuggedTree | undefined {
|
||||
return tree.find(
|
||||
(candidate) =>
|
||||
candidate.providers.some((item) => item.name === dependency) ||
|
||||
candidate.controllers.some((item) => item.name === dependency),
|
||||
);
|
||||
}
|
||||
|
||||
function renderMermaid(tree: DebuggedTree[]): string {
|
||||
const lines = [
|
||||
'flowchart LR',
|
||||
' %% Generated by scripts/graph-modules.ts',
|
||||
' %% Solid arrows: module imports; dotted arrows: constructor dependencies',
|
||||
];
|
||||
const moduleNames = tree.map((module) => module.name);
|
||||
|
||||
for (const module of tree) {
|
||||
const moduleId = mermaidId(module.name);
|
||||
lines.push(` subgraph ${moduleId}["${module.name}"]`);
|
||||
for (const provider of module.providers) {
|
||||
lines.push(
|
||||
` ${moduleId}_${mermaidId(provider.name)}["provider: ${provider.name}"]`,
|
||||
);
|
||||
}
|
||||
for (const controller of module.controllers) {
|
||||
lines.push(
|
||||
` ${moduleId}_${mermaidId(controller.name)}["controller: ${controller.name}"]`,
|
||||
);
|
||||
}
|
||||
lines.push(' end');
|
||||
}
|
||||
|
||||
for (const module of tree) {
|
||||
for (const imported of module.imports) {
|
||||
if (moduleNames.includes(imported)) {
|
||||
lines.push(
|
||||
` ${mermaidId(module.name)} -->|imports| ${mermaidId(imported)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const item of [...module.providers, ...module.controllers]) {
|
||||
for (const dependency of item.dependencies) {
|
||||
const targetModule = findDependencyModule(tree, dependency);
|
||||
if (targetModule) {
|
||||
const source = `${mermaidId(module.name)}_${mermaidId(item.name)}`;
|
||||
const target = `${mermaidId(targetModule.name)}_${mermaidId(dependency)}`;
|
||||
lines.push(` ${source} -.->|injects| ${target}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
function renderMarkdown(tree: DebuggedTree[], mermaid: string): string {
|
||||
const lines = [
|
||||
'# NestJS dependency graph',
|
||||
'',
|
||||
'Generated from `AppModule` with `nestjs-spelunker` static module debugging.',
|
||||
'',
|
||||
'- Solid arrows: module imports.',
|
||||
'- Dotted arrows: constructor dependencies.',
|
||||
'- The generator does not boot PostgreSQL or Redis.',
|
||||
'',
|
||||
'```mermaid',
|
||||
mermaid.trim(),
|
||||
'```',
|
||||
'',
|
||||
'## Module details',
|
||||
'',
|
||||
];
|
||||
|
||||
for (const module of tree) {
|
||||
lines.push(
|
||||
`### ${module.name}`,
|
||||
'',
|
||||
`- Imports: ${module.imports.join(', ') || 'none'}`,
|
||||
);
|
||||
lines.push(
|
||||
`- Exports: ${module.exports.map((item) => `${item.name} (${item.type})`).join(', ') || 'none'}`,
|
||||
);
|
||||
lines.push('', '| Kind | Name | Dependencies |', '| --- | --- | --- |');
|
||||
for (const provider of module.providers) {
|
||||
lines.push(
|
||||
`| provider | ${provider.name} | ${provider.dependencies.join(', ') || 'none'} |`,
|
||||
);
|
||||
}
|
||||
for (const controller of module.controllers) {
|
||||
lines.push(
|
||||
`| controller | ${controller.name} | ${controller.dependencies.join(', ') || 'none'} |`,
|
||||
);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
const tree = await SpelunkerModule.debug(AppModule);
|
||||
const mermaid = renderMermaid(tree);
|
||||
await mkdir('../docs/architecture', { recursive: true });
|
||||
await writeFile(
|
||||
'../docs/architecture/nest-module-details.json',
|
||||
JSON.stringify(tree, null, 2),
|
||||
);
|
||||
await writeFile('../docs/architecture/nest-module-graph.mmd', mermaid);
|
||||
await writeFile(
|
||||
'../docs/architecture/nest-dependency-graph.md',
|
||||
renderMarkdown(tree, mermaid),
|
||||
);
|
||||
+24
-1
@@ -1,10 +1,33 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AppConfigModule } from './config/app-config.module.js';
|
||||
import { DatabaseModule } from './database/database.module.js';
|
||||
import { RedisModule } from './redis/redis.module.js';
|
||||
import { AuthModule } from './auth/auth.module.js';
|
||||
import { ChatsModule } from './chats/chats.module.js';
|
||||
import { HealthModule } from './health/health.module.js';
|
||||
import { MessagesModule } from './messages/messages.module.js';
|
||||
import { MetricsModule } from './metrics/metrics.module.js';
|
||||
import { UsersModule } from './users/users.module.js';
|
||||
import { APP_FILTER } from '@nestjs/core';
|
||||
import { ApiExceptionFilter } from './common/errors/api-exception.filter.js';
|
||||
|
||||
@Module({
|
||||
imports: [HealthModule, UsersModule, ChatsModule, MessagesModule],
|
||||
imports: [
|
||||
AppConfigModule,
|
||||
DatabaseModule,
|
||||
RedisModule,
|
||||
UsersModule,
|
||||
AuthModule,
|
||||
HealthModule,
|
||||
ChatsModule,
|
||||
MessagesModule,
|
||||
MetricsModule,
|
||||
],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_FILTER,
|
||||
useClass: ApiExceptionFilter,
|
||||
},
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Headers,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Post,
|
||||
UnauthorizedException,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { TextDecoder } from 'node:util';
|
||||
import { AuthService } from './auth.service.js';
|
||||
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
|
||||
|
||||
const BASE64 =
|
||||
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
|
||||
const BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"';
|
||||
|
||||
function basicUnauthorized(): UnauthorizedException {
|
||||
return new UnauthorizedException({
|
||||
message: 'Unauthorized',
|
||||
challenge: BASIC_CHALLENGE,
|
||||
});
|
||||
}
|
||||
|
||||
function bearerUnauthorized(): UnauthorizedException {
|
||||
return new UnauthorizedException({
|
||||
message: 'Unauthorized',
|
||||
challenge: 'Bearer realm="messenger"',
|
||||
});
|
||||
}
|
||||
|
||||
function parseBasic(value: string | undefined): [string, string] {
|
||||
if (typeof value !== 'string') throw basicUnauthorized();
|
||||
const match = /^Basic[ \t]+([^ \t]+)$/iu.exec(value);
|
||||
if (!match || !BASE64.test(match[1])) throw basicUnauthorized();
|
||||
const bytes = Buffer.from(match[1], 'base64');
|
||||
if (bytes.toString('base64') !== match[1]) throw basicUnauthorized();
|
||||
let decoded: string;
|
||||
try {
|
||||
decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
||||
} catch {
|
||||
throw basicUnauthorized();
|
||||
}
|
||||
const separator = decoded.indexOf(':');
|
||||
if (separator < 1) throw basicUnauthorized();
|
||||
return [decoded.slice(0, separator), decoded.slice(separator + 1)];
|
||||
}
|
||||
|
||||
@Controller('api/v1/auth/sessions')
|
||||
export class AuthController {
|
||||
constructor(private readonly auth: AuthService) {}
|
||||
|
||||
@Post()
|
||||
create(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Body() body: unknown,
|
||||
) {
|
||||
const [username, password] = parseBasic(authorization);
|
||||
if (body !== undefined)
|
||||
throw new BadRequestException(
|
||||
'Session creation does not accept a body',
|
||||
);
|
||||
return this.auth.createSession(username, password);
|
||||
}
|
||||
|
||||
@Delete('current')
|
||||
@UseGuards(CurrentUserGuard)
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
async delete(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
): Promise<void> {
|
||||
if (!authorization || !/^Bearer\s+[^\s]+$/iu.test(authorization))
|
||||
throw bearerUnauthorized();
|
||||
await this.auth.deleteSession(authorization.slice(7).trim());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { DatabaseModule } from '../database/database.module.js';
|
||||
import { RedisModule } from '../redis/redis.module.js';
|
||||
import { UsersModule } from '../users/users.module.js';
|
||||
import { AuthController } from './auth.controller.js';
|
||||
import { AuthService } from './auth.service.js';
|
||||
import { SessionRepository } from './session.repository.js';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [UsersModule, DatabaseModule, RedisModule, MetricsModule],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, SessionRepository],
|
||||
exports: [AuthService, SessionRepository],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,63 @@
|
||||
import {
|
||||
Injectable,
|
||||
ServiceUnavailableException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import argon2 from 'argon2';
|
||||
import type { User } from '../users/user.js';
|
||||
import { UsersService } from '../users/users.service.js';
|
||||
import { SessionRepository } from './session.repository.js';
|
||||
|
||||
export type SessionResponse = {
|
||||
token: string;
|
||||
token_type: 'Bearer';
|
||||
expires_at: string;
|
||||
user: User;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly users: UsersService,
|
||||
private readonly sessions: SessionRepository,
|
||||
) {}
|
||||
|
||||
async createSession(
|
||||
username: string,
|
||||
password: string,
|
||||
): Promise<SessionResponse> {
|
||||
const storedUser = await this.users.findByUsername(username);
|
||||
if (
|
||||
!storedUser ||
|
||||
!(await argon2.verify(storedUser.password_hash, password))
|
||||
) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
const user: User = {
|
||||
id: storedUser.id,
|
||||
username: storedUser.username,
|
||||
display_name: storedUser.display_name,
|
||||
created_at: storedUser.created_at,
|
||||
};
|
||||
let session: { token: string; expiresAt: string };
|
||||
try {
|
||||
session = await this.sessions.create(user.id);
|
||||
} catch {
|
||||
throw new ServiceUnavailableException('Session store unavailable');
|
||||
}
|
||||
return {
|
||||
token: session.token,
|
||||
token_type: 'Bearer',
|
||||
expires_at: session.expiresAt,
|
||||
user,
|
||||
};
|
||||
}
|
||||
|
||||
async deleteSession(token: string): Promise<void> {
|
||||
try {
|
||||
await this.sessions.delete(token);
|
||||
} catch {
|
||||
throw new ServiceUnavailableException('Session store unavailable');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { RedisClient } from '../redis/redis.client.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
|
||||
@Injectable()
|
||||
export class SessionRepository {
|
||||
constructor(
|
||||
private readonly redis: RedisClient,
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {}
|
||||
|
||||
async create(
|
||||
userId: string,
|
||||
): Promise<{ token: string; expiresAt: string }> {
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const ttl = this.config.getOrThrow('SESSION_TTL_SECONDS');
|
||||
const expiresAt = new Date(Date.now() + ttl * 1000).toISOString();
|
||||
this.metrics.increment('session_set');
|
||||
await this.redis.set(
|
||||
`session:${token}`,
|
||||
JSON.stringify({ user_id: userId, expires_at: expiresAt }),
|
||||
{ EX: ttl },
|
||||
);
|
||||
return { token, expiresAt };
|
||||
}
|
||||
|
||||
delete(token: string): Promise<number> {
|
||||
this.metrics.increment('session_del');
|
||||
return this.redis.del(`session:${token}`);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +1,49 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
DefaultValuePipe,
|
||||
Get,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
DefaultValuePipe,
|
||||
Get,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { CurrentUser } from '../common/auth/current-user.decorator.js';
|
||||
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import { ChatsService } from './chats.service.js';
|
||||
import { CreateChatDto } from './dto/create-chat.dto.js';
|
||||
import type { User } from '../users/user.js';
|
||||
|
||||
@Controller('api/v1/chats')
|
||||
@UseGuards(CurrentUserGuard)
|
||||
export class ChatsController {
|
||||
constructor(private readonly chatsService: ChatsService) {}
|
||||
constructor(private readonly chatsService: ChatsService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() body: CreateChatDto, @Req() request: FastifyRequest) {
|
||||
return this.chatsService.create(body, request.currentUser!);
|
||||
}
|
||||
@Post()
|
||||
create(@Body() body: CreateChatDto, @CurrentUser() currentUser: User) {
|
||||
return this.chatsService.create(body, currentUser);
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(
|
||||
@Req() request: FastifyRequest,
|
||||
@Query('limit', new DefaultValuePipe(50), new ParseIntPipe()) limit: number,
|
||||
@Query('cursor') cursor?: string,
|
||||
) {
|
||||
if (limit < 1 || limit > 100) {
|
||||
throw new BadRequestException('limit must be between 1 and 100');
|
||||
}
|
||||
@Get()
|
||||
list(
|
||||
@CurrentUser() currentUser: User,
|
||||
@Query('limit', new DefaultValuePipe(50), new ParseIntPipe())
|
||||
limit: number,
|
||||
@Query('cursor') cursor?: string,
|
||||
) {
|
||||
if (limit < 1 || limit > 100)
|
||||
throw new BadRequestException('limit must be between 1 and 100');
|
||||
return this.chatsService.listForUser(currentUser, limit, cursor);
|
||||
}
|
||||
|
||||
return this.chatsService.listForUser(
|
||||
request.currentUser!,
|
||||
limit,
|
||||
cursor,
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':chatId')
|
||||
get(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@Req() request: FastifyRequest,
|
||||
) {
|
||||
return this.chatsService.getForUser(chatId, request.currentUser!);
|
||||
}
|
||||
@Get(':chatId')
|
||||
get(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@CurrentUser() currentUser: User,
|
||||
) {
|
||||
return this.chatsService.getForUser(chatId, currentUser);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ChatsController } from './chats.controller.js';
|
||||
import { DatabaseModule } from '../database/database.module.js';
|
||||
import { RedisModule } from '../redis/redis.module.js';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
import { UsersModule } from '../users/users.module.js';
|
||||
import { ChatsController } from './chats.controller.js';
|
||||
import { ChatsRepository } from './chats.repository.js';
|
||||
import { ChatsService } from './chats.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [UsersModule],
|
||||
controllers: [ChatsController],
|
||||
providers: [ChatsRepository, ChatsService],
|
||||
exports: [ChatsService],
|
||||
imports: [UsersModule, DatabaseModule, RedisModule, MetricsModule],
|
||||
controllers: [ChatsController],
|
||||
providers: [ChatsRepository, ChatsService],
|
||||
exports: [ChatsService],
|
||||
})
|
||||
export class ChatsModule {}
|
||||
|
||||
@@ -1,19 +1,113 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Chat } from './chat.js';
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import type { Cursor } from '../common/http/cursor.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import type { Chat } from './chat.js';
|
||||
|
||||
type ChatRow = {
|
||||
id: string;
|
||||
title: string;
|
||||
created_at: Date | string;
|
||||
member_ids: string[];
|
||||
};
|
||||
|
||||
function toChat(row: ChatRow): Chat {
|
||||
return {
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
created_at: new Date(row.created_at).toISOString(),
|
||||
member_ids: row.member_ids,
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ChatsRepository {
|
||||
private readonly chatsById = new Map<string, Chat>();
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
save(chat: Chat): void {
|
||||
this.chatsById.set(chat.id, chat);
|
||||
async create(title: string, memberIds: string[]): Promise<Chat> {
|
||||
const id = randomUUID();
|
||||
return this.database.withTransaction(async (client) => {
|
||||
const users = await client.query<{ id: string }>({
|
||||
name: 'chats.validateMembers',
|
||||
text: 'SELECT id FROM users WHERE id = ANY($1::uuid[])',
|
||||
values: [memberIds],
|
||||
});
|
||||
if (users.rowCount !== memberIds.length)
|
||||
throw new BadRequestException('Chat member does not exist');
|
||||
const inserted = await client.query<ChatRow>({
|
||||
name: 'chats.insert',
|
||||
text: 'INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING id, title, created_at',
|
||||
values: [id, title],
|
||||
});
|
||||
for (const memberId of memberIds) {
|
||||
await client.query({
|
||||
name: 'chats.insertMember',
|
||||
text: 'INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)',
|
||||
values: [id, memberId],
|
||||
});
|
||||
}
|
||||
return {
|
||||
...toChat({ ...inserted.rows[0], member_ids: memberIds }),
|
||||
member_ids: memberIds,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
findById(id: string): Chat | undefined {
|
||||
return this.chatsById.get(id);
|
||||
async findForUser(id: string, user: User): Promise<Chat | undefined> {
|
||||
const result = await this.database.query<ChatRow>(
|
||||
'chats.findForUser',
|
||||
`SELECT c.id, c.title, c.created_at,
|
||||
COALESCE(array_agg(cm.user_id ORDER BY cm.user_id)
|
||||
FILTER (WHERE cm.user_id IS NOT NULL), '{}') AS member_ids
|
||||
FROM chats c
|
||||
LEFT JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM chat_members own
|
||||
WHERE own.chat_id = c.id AND own.user_id = $2
|
||||
)
|
||||
GROUP BY c.id`,
|
||||
[id, user.id],
|
||||
);
|
||||
return result.rows[0] ? toChat(result.rows[0]) : undefined;
|
||||
}
|
||||
|
||||
findAll(): Chat[] {
|
||||
return Array.from(this.chatsById.values());
|
||||
async findPageForUser(
|
||||
user: User,
|
||||
limit: number,
|
||||
cursor?: Cursor,
|
||||
): Promise<{ items: Chat[]; hasMore: boolean }> {
|
||||
const values: unknown[] = [user.id];
|
||||
let predicate = '';
|
||||
if (cursor) {
|
||||
values.push(cursor.created_at, cursor.id);
|
||||
predicate =
|
||||
'AND (c.created_at, c.id) > ($2::timestamptz, $3::uuid)';
|
||||
}
|
||||
values.push(limit + 1);
|
||||
const result = await this.database.query<ChatRow>(
|
||||
'chats.listForUser',
|
||||
`SELECT c.id, c.title, c.created_at,
|
||||
COALESCE(array_agg(cm.user_id ORDER BY cm.user_id)
|
||||
FILTER (WHERE cm.user_id IS NOT NULL), '{}') AS member_ids
|
||||
FROM chats c
|
||||
LEFT JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members own
|
||||
WHERE own.chat_id = c.id AND own.user_id = $1
|
||||
)
|
||||
${predicate}
|
||||
GROUP BY c.id ORDER BY c.created_at, c.id LIMIT $${values.length}`,
|
||||
values,
|
||||
);
|
||||
return {
|
||||
items: result.rows.slice(0, limit).map(toChat),
|
||||
hasMore: result.rows.length > limit,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,95 +1,60 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import {
|
||||
decodeCursor,
|
||||
encodeCursor,
|
||||
isAfter,
|
||||
} from '../common/http/cursor.js';
|
||||
import { encodeCursor, decodeCursor } from '../common/http/cursor.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import { UsersService } from '../users/users.service.js';
|
||||
import type { Chat } from './chat.js';
|
||||
import type { CreateChatDto } from './dto/create-chat.dto.js';
|
||||
import type { Chat } from './chat.js';
|
||||
import { ChatsRepository } from './chats.repository.js';
|
||||
|
||||
@Injectable()
|
||||
export class ChatsService {
|
||||
constructor(
|
||||
private readonly chatsRepository: ChatsRepository,
|
||||
private readonly usersService: UsersService,
|
||||
) {}
|
||||
constructor(private readonly chatsRepository: ChatsRepository) {}
|
||||
|
||||
create(input: CreateChatDto, currentUser: User): Chat {
|
||||
if (!input.member_ids.includes(currentUser.id)) {
|
||||
throw new BadRequestException('Current user must be a chat member');
|
||||
}
|
||||
create(input: CreateChatDto, currentUser: User): Promise<Chat> {
|
||||
if (!input.member_ids.includes(currentUser.id))
|
||||
throw new BadRequestException('Current user must be a chat member');
|
||||
if (new Set(input.member_ids).size !== input.member_ids.length)
|
||||
throw new BadRequestException('Duplicate chat member');
|
||||
return this.chatsRepository.create(input.title, input.member_ids);
|
||||
}
|
||||
|
||||
for (const memberId of input.member_ids) {
|
||||
if (!this.usersService.findById(memberId)) {
|
||||
throw new BadRequestException('Chat member does not exist');
|
||||
}
|
||||
}
|
||||
async getForUser(chatId: string, currentUser: User): Promise<Chat> {
|
||||
const chat = await this.chatsRepository.findForUser(
|
||||
chatId,
|
||||
currentUser,
|
||||
);
|
||||
if (!chat) throw new NotFoundException();
|
||||
return chat;
|
||||
}
|
||||
|
||||
const chat: Chat = {
|
||||
id: randomUUID(),
|
||||
title: input.title,
|
||||
member_ids: [...input.member_ids],
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
this.chatsRepository.save(chat);
|
||||
return chat;
|
||||
}
|
||||
|
||||
getForUser(chatId: string, currentUser: User): Chat {
|
||||
const chat = this.chatsRepository.findById(chatId);
|
||||
|
||||
if (!chat || !chat.member_ids.includes(currentUser.id)) {
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
return chat;
|
||||
}
|
||||
|
||||
listForUser(
|
||||
currentUser: User,
|
||||
limit: number,
|
||||
cursorValue?: string,
|
||||
): { items: Chat[]; next_cursor: string | null } {
|
||||
const scope = `chats:${currentUser.id}`;
|
||||
const cursor = cursorValue
|
||||
? decodeCursor(cursorValue, scope)
|
||||
: undefined;
|
||||
|
||||
const chats = this.chatsRepository
|
||||
.findAll()
|
||||
.filter((chat) => chat.member_ids.includes(currentUser.id))
|
||||
.sort((left, right) => {
|
||||
const byDate = left.created_at.localeCompare(right.created_at);
|
||||
return byDate !== 0 ? byDate : left.id.localeCompare(right.id);
|
||||
});
|
||||
|
||||
const start = cursor
|
||||
? chats.findIndex((chat) => isAfter(chat.created_at, chat.id, cursor))
|
||||
: 0;
|
||||
const visible = chats.slice(start < 0 ? chats.length : start);
|
||||
const items = visible.slice(0, limit);
|
||||
const hasMore = visible.length > limit;
|
||||
const last = items.at(-1);
|
||||
|
||||
return {
|
||||
items,
|
||||
next_cursor:
|
||||
hasMore && last
|
||||
? encodeCursor({
|
||||
scope,
|
||||
created_at: last.created_at,
|
||||
id: last.id,
|
||||
})
|
||||
: null,
|
||||
};
|
||||
}
|
||||
async listForUser(
|
||||
currentUser: User,
|
||||
limit: number,
|
||||
cursorValue?: string,
|
||||
): Promise<{ items: Chat[]; next_cursor: string | null }> {
|
||||
const scope = `chats:${currentUser.id}`;
|
||||
const cursor = cursorValue
|
||||
? decodeCursor(cursorValue, scope)
|
||||
: undefined;
|
||||
const page = await this.chatsRepository.findPageForUser(
|
||||
currentUser,
|
||||
limit,
|
||||
cursor,
|
||||
);
|
||||
const last = page.items.at(-1);
|
||||
return {
|
||||
items: page.items,
|
||||
next_cursor:
|
||||
page.hasMore && last
|
||||
? encodeCursor({
|
||||
scope,
|
||||
created_at: last.created_at,
|
||||
id: last.id,
|
||||
})
|
||||
: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import type { User } from '../../users/user.js';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, context: ExecutionContext): User => {
|
||||
const request = context.switchToHttp().getRequest<FastifyRequest>();
|
||||
return request.currentUser!;
|
||||
},
|
||||
);
|
||||
@@ -2,42 +2,84 @@ import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
ServiceUnavailableException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { isUUID } from 'class-validator';
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import type { User } from '../../users/user.js';
|
||||
import { RedisClient } from '../../redis/redis.client.js';
|
||||
import { UsersService } from '../../users/users.service.js';
|
||||
|
||||
export type RequestWithCurrentUser = {
|
||||
headers: {
|
||||
'x-user-id'?: string | string[];
|
||||
};
|
||||
currentUser?: User;
|
||||
};
|
||||
import { MetricsService } from '../../metrics/metrics.service.js';
|
||||
|
||||
@Injectable()
|
||||
export class CurrentUserGuard implements CanActivate {
|
||||
constructor(private readonly usersService: UsersService) {}
|
||||
constructor(
|
||||
private readonly redis: RedisClient,
|
||||
private readonly users: UsersService,
|
||||
private readonly metrics: MetricsService,
|
||||
) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const request = context
|
||||
.switchToHttp()
|
||||
.getRequest<RequestWithCurrentUser>();
|
||||
|
||||
const header = request.headers['x-user-id'];
|
||||
|
||||
if (typeof header !== 'string' || !isUUID(header)) {
|
||||
throw new UnauthorizedException();
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<FastifyRequest>();
|
||||
const authorization = request.headers.authorization;
|
||||
if (
|
||||
typeof authorization !== 'string' ||
|
||||
!/^Bearer\s+[^\s]+$/u.test(authorization)
|
||||
) {
|
||||
throw new UnauthorizedException({
|
||||
message: 'Unauthorized',
|
||||
challenge: 'Bearer realm="messenger"',
|
||||
});
|
||||
}
|
||||
|
||||
const user = this.usersService.findById(header);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException();
|
||||
let session: string | null;
|
||||
try {
|
||||
this.metrics.increment('session_get');
|
||||
session = await this.redis.get(
|
||||
`session:${authorization.slice(7).trim()}`,
|
||||
);
|
||||
} catch {
|
||||
throw new ServiceUnavailableException('Session store unavailable');
|
||||
}
|
||||
|
||||
if (!session)
|
||||
throw new UnauthorizedException({
|
||||
message: 'Unauthorized',
|
||||
challenge: 'Bearer realm="messenger"',
|
||||
});
|
||||
let userId: string;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(session);
|
||||
if (
|
||||
typeof parsed !== 'object' ||
|
||||
parsed === null ||
|
||||
!('user_id' in parsed) ||
|
||||
typeof parsed.user_id !== 'string' ||
|
||||
!('expires_at' in parsed) ||
|
||||
typeof parsed.expires_at !== 'string' ||
|
||||
!/^(?:\d{4})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u.test(
|
||||
parsed.expires_at,
|
||||
)
|
||||
)
|
||||
throw new Error('invalid session');
|
||||
const expiresAt = Date.parse(parsed.expires_at);
|
||||
if (!Number.isFinite(expiresAt) || Date.now() >= expiresAt)
|
||||
throw new Error('expired session');
|
||||
userId = parsed.user_id;
|
||||
} catch {
|
||||
throw new UnauthorizedException({
|
||||
message: 'Unauthorized',
|
||||
challenge: 'Bearer realm="messenger"',
|
||||
});
|
||||
}
|
||||
let user: User | undefined;
|
||||
try {
|
||||
user = await this.users.findById(userId);
|
||||
} catch {
|
||||
throw new ServiceUnavailableException(
|
||||
'Authentication service unavailable',
|
||||
);
|
||||
}
|
||||
if (!user) throw new UnauthorizedException();
|
||||
request.currentUser = user;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,85 +5,114 @@ import {
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
type RequestWithId = {
|
||||
requestId?: string;
|
||||
};
|
||||
type RequestWithId = { requestId?: string; method?: string; url?: string };
|
||||
type ExceptionBody = { message?: unknown; challenge?: unknown };
|
||||
|
||||
type HttpResponse = {
|
||||
header(name: string, value: string): void;
|
||||
status(code: number): HttpResponse;
|
||||
send(body: unknown): void;
|
||||
};
|
||||
// Connection/session loss codes reported by node-postgres and the network layer.
|
||||
const UNAVAILABLE_ERROR_CODES = new Set([
|
||||
'ECONNREFUSED',
|
||||
'ECONNRESET',
|
||||
'ENOTFOUND',
|
||||
'ETIMEDOUT',
|
||||
'EPIPE',
|
||||
'08000',
|
||||
'08001',
|
||||
'08003',
|
||||
'08004',
|
||||
'08006',
|
||||
'57P01',
|
||||
'57P02',
|
||||
'57P03',
|
||||
'53300',
|
||||
]);
|
||||
|
||||
function isDependencyOutage(exception: unknown): boolean {
|
||||
if (typeof exception !== 'object' || exception === null) return false;
|
||||
const code = (exception as { code?: unknown }).code;
|
||||
return typeof code === 'string' && UNAVAILABLE_ERROR_CODES.has(code);
|
||||
}
|
||||
|
||||
function errorCodeForStatus(status: number): string {
|
||||
switch (status) {
|
||||
case HttpStatus.BAD_REQUEST:
|
||||
return 'invalid_request';
|
||||
case HttpStatus.UNAUTHORIZED:
|
||||
return 'unauthorized';
|
||||
case HttpStatus.NOT_FOUND:
|
||||
return 'not_found';
|
||||
case HttpStatus.CONFLICT:
|
||||
return 'conflict';
|
||||
case HttpStatus.PAYLOAD_TOO_LARGE:
|
||||
return 'payload_too_large';
|
||||
case HttpStatus.UNSUPPORTED_MEDIA_TYPE:
|
||||
return 'unsupported_media_type';
|
||||
case HttpStatus.TOO_MANY_REQUESTS:
|
||||
return 'rate_limited';
|
||||
case HttpStatus.SERVICE_UNAVAILABLE:
|
||||
return 'unavailable';
|
||||
default:
|
||||
return 'internal_error';
|
||||
}
|
||||
const codes: Record<number, string> = {
|
||||
[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',
|
||||
};
|
||||
return codes[status] ?? 'internal_error';
|
||||
}
|
||||
|
||||
@Catch()
|
||||
export class ApiExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: any, host: ArgumentsHost) {
|
||||
const context = host.switchToHttp();
|
||||
|
||||
const request = context.getRequest<RequestWithId>();
|
||||
|
||||
const response = context.getResponse<HttpResponse>();
|
||||
constructor(private readonly adapterHost: HttpAdapterHost) {}
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost): void {
|
||||
const http = host.switchToHttp();
|
||||
const request = http.getRequest<RequestWithId>();
|
||||
const response = http.getResponse<unknown>();
|
||||
const adapter = this.adapterHost.httpAdapter;
|
||||
const requestId = request.requestId ?? randomUUID();
|
||||
|
||||
request.requestId = requestId;
|
||||
response.header('X-Request-Id', requestId);
|
||||
|
||||
let status = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
let message = 'Internal server error';
|
||||
|
||||
let challenge: string | undefined;
|
||||
if (exception instanceof HttpException) {
|
||||
status = exception.getStatus();
|
||||
const exceptionResponse = exception.getResponse();
|
||||
const body = exception.getResponse();
|
||||
const details: ExceptionBody =
|
||||
typeof body === 'object' && body !== null
|
||||
? (body as ExceptionBody)
|
||||
: {};
|
||||
const rawMessage =
|
||||
typeof exceptionResponse === 'object' &&
|
||||
exceptionResponse !== null &&
|
||||
'message' in exceptionResponse
|
||||
? exceptionResponse.message
|
||||
'message' in details ? details.message : undefined;
|
||||
challenge =
|
||||
typeof details.challenge === 'string'
|
||||
? details.challenge
|
||||
: undefined;
|
||||
|
||||
message = Array.isArray(rawMessage)
|
||||
? rawMessage.join('; ')
|
||||
: typeof rawMessage === 'string'
|
||||
? rawMessage
|
||||
: 'Request failed';
|
||||
|
||||
if (status === HttpStatus.NOT_FOUND) {
|
||||
message = 'Resource not found';
|
||||
}
|
||||
if (status === HttpStatus.NOT_FOUND) message = 'Resource not found';
|
||||
if (status >= HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
message =
|
||||
status === HttpStatus.SERVICE_UNAVAILABLE
|
||||
? 'Service unavailable'
|
||||
: 'Internal server error';
|
||||
} else if (isDependencyOutage(exception)) {
|
||||
// A dropped dependency is a bounded outage, not an internal fault.
|
||||
status = HttpStatus.SERVICE_UNAVAILABLE;
|
||||
message = 'Service unavailable';
|
||||
}
|
||||
|
||||
response.status(status).send({
|
||||
error: {
|
||||
code: errorCodeForStatus(status),
|
||||
message: message,
|
||||
request_id: requestId,
|
||||
if (status === HttpStatus.UNAUTHORIZED) {
|
||||
const authChallenge =
|
||||
challenge ??
|
||||
(request.method === 'POST' &&
|
||||
request.url?.startsWith('/api/v1/auth/sessions')
|
||||
? 'Basic realm="messenger", charset="UTF-8"'
|
||||
: 'Bearer realm="messenger"');
|
||||
adapter.setHeader(response, 'WWW-Authenticate', authChallenge);
|
||||
}
|
||||
adapter.setHeader(response, 'X-Request-Id', requestId);
|
||||
adapter.reply(
|
||||
response,
|
||||
{
|
||||
error: {
|
||||
code: errorCodeForStatus(status),
|
||||
message,
|
||||
request_id: requestId,
|
||||
},
|
||||
},
|
||||
});
|
||||
status,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,54 +1,57 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
export type Cursor = {
|
||||
scope: string;
|
||||
created_at: string;
|
||||
id: string;
|
||||
scope: string;
|
||||
created_at: string;
|
||||
id: string;
|
||||
};
|
||||
|
||||
export function encodeCursor(cursor: Cursor): string {
|
||||
return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
|
||||
return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
|
||||
}
|
||||
|
||||
export function decodeCursor(value: string, expectedScope: string): Cursor {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(
|
||||
Buffer.from(value, 'base64url').toString('utf8'),
|
||||
);
|
||||
|
||||
if (
|
||||
typeof parsed !== 'object' ||
|
||||
parsed === null ||
|
||||
!('scope' in parsed) ||
|
||||
!('created_at' in parsed) ||
|
||||
!('id' in parsed) ||
|
||||
typeof parsed.scope !== 'string' ||
|
||||
typeof parsed.created_at !== 'string' ||
|
||||
typeof parsed.id !== 'string' ||
|
||||
parsed.scope !== expectedScope ||
|
||||
parsed.created_at.length === 0 ||
|
||||
parsed.id.length === 0
|
||||
) {
|
||||
throw new Error('invalid cursor');
|
||||
}
|
||||
|
||||
return {
|
||||
scope: parsed.scope,
|
||||
created_at: parsed.created_at,
|
||||
id: parsed.id,
|
||||
};
|
||||
} catch {
|
||||
throw new BadRequestException('Invalid cursor');
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(
|
||||
Buffer.from(value, 'base64url').toString('utf8'),
|
||||
);
|
||||
if (
|
||||
typeof parsed !== 'object' ||
|
||||
parsed === null ||
|
||||
!('scope' in parsed) ||
|
||||
!('created_at' in parsed) ||
|
||||
!('id' in parsed) ||
|
||||
typeof parsed.scope !== 'string' ||
|
||||
typeof parsed.created_at !== 'string' ||
|
||||
typeof parsed.id !== 'string' ||
|
||||
parsed.scope !== expectedScope ||
|
||||
!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(
|
||||
parsed.id,
|
||||
) ||
|
||||
!/^(?:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)$/u.test(
|
||||
parsed.created_at,
|
||||
)
|
||||
)
|
||||
throw new Error('invalid cursor');
|
||||
const timestamp = Date.parse(parsed.created_at);
|
||||
if (!Number.isFinite(timestamp)) throw new Error('invalid cursor');
|
||||
return {
|
||||
scope: parsed.scope,
|
||||
created_at: parsed.created_at,
|
||||
id: parsed.id,
|
||||
};
|
||||
} catch {
|
||||
throw new BadRequestException('Invalid cursor');
|
||||
}
|
||||
}
|
||||
|
||||
export function isAfter(
|
||||
createdAt: string,
|
||||
id: string,
|
||||
cursor: Cursor,
|
||||
createdAt: string,
|
||||
id: string,
|
||||
cursor: Cursor,
|
||||
): boolean {
|
||||
return (
|
||||
createdAt > cursor.created_at ||
|
||||
(createdAt === cursor.created_at && id > cursor.id)
|
||||
);
|
||||
return (
|
||||
createdAt > cursor.created_at ||
|
||||
(createdAt === cursor.created_at && id > cursor.id)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,32 +4,47 @@ import {
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { Observable } from 'rxjs';
|
||||
import { finalize, Observable } from 'rxjs';
|
||||
import { MetricsService } from '../../metrics/metrics.service.js';
|
||||
const INSTANCE_ID = randomUUID();
|
||||
|
||||
type RequestWithId = {
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
type ResponseWithHeader = {
|
||||
header(name: string, value: string): void;
|
||||
};
|
||||
type RequestWithId = { requestId?: string };
|
||||
|
||||
@Injectable()
|
||||
export class RequestIdInterceptor implements NestInterceptor {
|
||||
constructor(
|
||||
private readonly adapterHost: HttpAdapterHost,
|
||||
private readonly metrics: MetricsService,
|
||||
) {}
|
||||
|
||||
intercept(
|
||||
context: ExecutionContext,
|
||||
next: CallHandler<any>,
|
||||
): Observable<any> | Promise<Observable<any>> {
|
||||
next: CallHandler,
|
||||
): Observable<unknown> {
|
||||
const request = context.switchToHttp().getRequest<RequestWithId>();
|
||||
|
||||
const response = context.switchToHttp().getResponse<ResponseWithHeader>();
|
||||
|
||||
const response = context.switchToHttp().getResponse<unknown>();
|
||||
const requestId = randomUUID();
|
||||
|
||||
const startedAt = performance.now();
|
||||
request.requestId = requestId;
|
||||
response.header('X-Request-Id', requestId);
|
||||
|
||||
return next.handle();
|
||||
this.adapterHost.httpAdapter.setHeader(
|
||||
response,
|
||||
'X-Request-Id',
|
||||
requestId,
|
||||
);
|
||||
this.adapterHost.httpAdapter.setHeader(
|
||||
response,
|
||||
'X-Instance-Id',
|
||||
INSTANCE_ID,
|
||||
);
|
||||
this.metrics.increment('request_count');
|
||||
return next
|
||||
.handle()
|
||||
.pipe(
|
||||
finalize(() =>
|
||||
this.metrics.observeLatency(performance.now() - startedAt),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { parseAppConfig } from './app-config.schema.js';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
cache: true,
|
||||
validate: parseAppConfig,
|
||||
}),
|
||||
],
|
||||
exports: [ConfigModule],
|
||||
})
|
||||
export class AppConfigModule {}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { z } from 'zod';
|
||||
|
||||
function numeric(
|
||||
name: string,
|
||||
minimum: number,
|
||||
maximum: number | undefined,
|
||||
fallback: number,
|
||||
) {
|
||||
let schema = z
|
||||
.number({ message: `${name} must be a number` })
|
||||
.int()
|
||||
.min(minimum);
|
||||
if (maximum !== undefined) schema = schema.max(maximum);
|
||||
return z.preprocess(
|
||||
(value) =>
|
||||
typeof value === 'string' && value.trim() !== ''
|
||||
? Number(value)
|
||||
: value,
|
||||
schema.default(fallback),
|
||||
);
|
||||
}
|
||||
|
||||
function requiredString(name: string) {
|
||||
return z
|
||||
.string({ message: `${name} is required` })
|
||||
.min(1, `${name} is required`);
|
||||
}
|
||||
|
||||
export const appConfigSchema = z
|
||||
.object({
|
||||
APP_HOST: z.string().min(1).default('0.0.0.0'),
|
||||
APP_PORT: numeric('APP_PORT', 1, 65535, 8080),
|
||||
APP_ENV: z.string().min(1).default('lab'),
|
||||
SESSION_TTL_SECONDS: numeric('SESSION_TTL_SECONDS', 2, undefined, 3600),
|
||||
DATABASE_URL: requiredString('DATABASE_URL'),
|
||||
REDIS_URL: requiredString('REDIS_URL'),
|
||||
DATABASE_POOL_MAX: numeric('DATABASE_POOL_MAX', 1, 100, 10),
|
||||
DATABASE_CONNECTION_TIMEOUT_MS: numeric(
|
||||
'DATABASE_CONNECTION_TIMEOUT_MS',
|
||||
1,
|
||||
undefined,
|
||||
5000,
|
||||
),
|
||||
DATABASE_STATEMENT_TIMEOUT_MS: numeric(
|
||||
'DATABASE_STATEMENT_TIMEOUT_MS',
|
||||
1,
|
||||
undefined,
|
||||
5000,
|
||||
),
|
||||
CACHE_TTL_SECONDS: numeric('CACHE_TTL_SECONDS', 1, undefined, 30),
|
||||
CACHE_MODE: z.enum(['protected', 'naive']).default('protected'),
|
||||
CACHE_LOCK_TTL_MS: numeric('CACHE_LOCK_TTL_MS', 1, undefined, 1000),
|
||||
CACHE_MISS_DELAY_MS: numeric('CACHE_MISS_DELAY_MS', 0, undefined, 0),
|
||||
METRICS_TOKEN: z.string().min(1).optional(),
|
||||
DRAIN_DELAY_MS: numeric('DRAIN_DELAY_MS', 0, undefined, 5000),
|
||||
})
|
||||
.strip();
|
||||
|
||||
export type AppConfig = z.infer<typeof appConfigSchema>;
|
||||
export type AppConfigKey = keyof AppConfig;
|
||||
|
||||
function resolveSecret(
|
||||
raw: Record<string, unknown>,
|
||||
key: 'DATABASE_URL' | 'REDIS_URL',
|
||||
): unknown {
|
||||
const fileKey = `${key}_FILE`;
|
||||
const path = raw[fileKey];
|
||||
if (typeof path !== 'string' || path.length === 0) return raw[key];
|
||||
try {
|
||||
const value = readFileSync(path, 'utf8').trim();
|
||||
if (value.length === 0)
|
||||
throw new Error(`${fileKey} contains an empty value`);
|
||||
return value;
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof Error &&
|
||||
error.message.includes('contains an empty value')
|
||||
)
|
||||
throw error;
|
||||
throw new Error(`${fileKey} could not be read`);
|
||||
}
|
||||
}
|
||||
|
||||
export function parseAppConfig(raw: Record<string, unknown>): AppConfig {
|
||||
return appConfigSchema.parse({
|
||||
...raw,
|
||||
DATABASE_URL: resolveSecret(raw, 'DATABASE_URL'),
|
||||
REDIS_URL: resolveSecret(raw, 'REDIS_URL'),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import pg from 'pg';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
|
||||
@Injectable()
|
||||
export class DatabaseClient implements OnModuleDestroy {
|
||||
readonly pool: pg.Pool;
|
||||
private readonly logger = new Logger(DatabaseClient.name);
|
||||
|
||||
constructor(
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {
|
||||
this.pool = new pg.Pool({
|
||||
connectionString: this.config.getOrThrow('DATABASE_URL'),
|
||||
max: this.config.getOrThrow('DATABASE_POOL_MAX'),
|
||||
connectionTimeoutMillis: this.config.getOrThrow(
|
||||
'DATABASE_CONNECTION_TIMEOUT_MS',
|
||||
),
|
||||
statement_timeout: this.config.getOrThrow(
|
||||
'DATABASE_STATEMENT_TIMEOUT_MS',
|
||||
),
|
||||
});
|
||||
// Idle clients emit 'error' on the pool when the database drops; without a
|
||||
// listener Node treats it as uncaught and terminates the process.
|
||||
this.pool.on('error', (error: Error) => {
|
||||
this.metrics.increment('database.pool_error');
|
||||
this.logger.warn(`PostgreSQL pool error: ${error.message}`);
|
||||
});
|
||||
}
|
||||
|
||||
query<T extends pg.QueryResultRow = pg.QueryResultRow>(
|
||||
label: string,
|
||||
text: string,
|
||||
values: readonly unknown[] = [],
|
||||
): Promise<pg.QueryResult<T>> {
|
||||
this.metrics.increment(label);
|
||||
return this.pool.query<T>({ text, values: [...values] });
|
||||
}
|
||||
|
||||
async health(): Promise<void> {
|
||||
await this.query('health.database', 'SELECT 1');
|
||||
}
|
||||
|
||||
async withTransaction<T>(
|
||||
work: (client: pg.PoolClient) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const result = await work(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
try {
|
||||
await client.query('ROLLBACK');
|
||||
} catch (rollbackError) {
|
||||
this.metrics.increment('database.rollback_error');
|
||||
this.logger.warn(
|
||||
`Rollback failed: ${rollbackError instanceof Error ? rollbackError.message : 'unknown error'}`,
|
||||
);
|
||||
}
|
||||
// Callers must see the operation error, not the rollback error.
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
await this.pool.end();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
import { DatabaseClient } from './database.client.js';
|
||||
|
||||
@Module({
|
||||
imports: [MetricsModule],
|
||||
providers: [DatabaseClient],
|
||||
exports: [DatabaseClient],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { readdir, readFile } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { DatabaseClient } from './database.client.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import { parseAppConfig } from '../config/app-config.schema.js';
|
||||
|
||||
const migrationsDirectory = join(
|
||||
dirname(fileURLToPath(import.meta.url)),
|
||||
'migrations',
|
||||
);
|
||||
|
||||
async function migrationFiles(): Promise<string[]> {
|
||||
const files = await readdir(migrationsDirectory);
|
||||
return files.filter((file) => /^\d+_.+\.sql$/u.test(file)).sort();
|
||||
}
|
||||
|
||||
export async function runMigrations(database: DatabaseClient): Promise<void> {
|
||||
await database.query(
|
||||
'migrations.ensure_table',
|
||||
`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)`,
|
||||
);
|
||||
|
||||
for (const version of await migrationFiles()) {
|
||||
await database.withTransaction(async (client) => {
|
||||
const applied = await client.query({
|
||||
text: 'SELECT version FROM schema_migrations WHERE version = $1',
|
||||
values: [version],
|
||||
});
|
||||
if (applied.rowCount) return;
|
||||
|
||||
const sql = await readFile(
|
||||
join(migrationsDirectory, version),
|
||||
'utf8',
|
||||
);
|
||||
await client.query(sql);
|
||||
await client.query({
|
||||
text: 'INSERT INTO schema_migrations (version) VALUES ($1)',
|
||||
values: [version],
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const config = parseAppConfig(process.env as Record<string, unknown>);
|
||||
const database = new DatabaseClient(
|
||||
{
|
||||
getOrThrow: (key: keyof typeof config) => config[key],
|
||||
} as never,
|
||||
new MetricsService(),
|
||||
);
|
||||
try {
|
||||
await runMigrations(database);
|
||||
} finally {
|
||||
await database.onModuleDestroy();
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
|
||||
@@ -0,0 +1,41 @@
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL UNIQUE,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
message_version bigint NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT messages_sender_member_fk
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||
ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
CREATE INDEX IF NOT EXISTS chat_members_user_chat_idx
|
||||
ON chat_members (user_id, chat_id);
|
||||
@@ -0,0 +1,5 @@
|
||||
-- HTTP timestamps and keyset cursors use JavaScript millisecond precision.
|
||||
-- Store the same precision so a returned cursor cannot point before its own row.
|
||||
ALTER TABLE users ALTER COLUMN created_at TYPE timestamptz(3);
|
||||
ALTER TABLE chats ALTER COLUMN created_at TYPE timestamptz(3);
|
||||
ALTER TABLE messages ALTER COLUMN created_at TYPE timestamptz(3);
|
||||
@@ -3,15 +3,15 @@ import { HealthService } from './health.service.js';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(private readonly healthService: HealthService) {}
|
||||
constructor(private readonly healthService: HealthService) {}
|
||||
|
||||
@Get('live')
|
||||
getLive() {
|
||||
return this.healthService.getLiveness();
|
||||
}
|
||||
@Get('live')
|
||||
getLive() {
|
||||
return this.healthService.getLiveness();
|
||||
}
|
||||
|
||||
@Get('ready')
|
||||
getReady() {
|
||||
return this.healthService.getReadiness();
|
||||
}
|
||||
@Get('ready')
|
||||
async getReady() {
|
||||
return this.healthService.getReadiness();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller.js';
|
||||
import { HealthService } from './health.service.js';
|
||||
import { DatabaseModule } from '../database/database.module.js';
|
||||
import { RedisModule } from '../redis/redis.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
controllers: [HealthController],
|
||||
providers: [HealthService],
|
||||
imports: [DatabaseModule, RedisModule],
|
||||
controllers: [HealthController],
|
||||
providers: [HealthService],
|
||||
})
|
||||
export class HealthModule {}
|
||||
|
||||
@@ -1,57 +1,46 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { ServiceUnavailableException } from '@nestjs/common';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { HealthService } from './health.service.js';
|
||||
|
||||
describe('HealthService', () => {
|
||||
const originalDrainDelay = process.env.DRAIN_DELAY_MS;
|
||||
it('reports liveness and readiness when dependencies are healthy', async () => {
|
||||
const database = { health: vi.fn().mockResolvedValue(undefined) };
|
||||
const redis = { health: vi.fn().mockResolvedValue(undefined) };
|
||||
const config = { get: vi.fn().mockReturnValue(0) };
|
||||
const service = new HealthService(
|
||||
database as never,
|
||||
redis as never,
|
||||
config as never,
|
||||
);
|
||||
expect(service.getLiveness()).toEqual({ status: 'ok' });
|
||||
await expect(service.getReadiness()).resolves.toEqual({ status: 'ok' });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
it('rejects readiness when a dependency is unavailable', async () => {
|
||||
const database = {
|
||||
health: vi.fn().mockRejectedValue(new Error('down')),
|
||||
};
|
||||
const redis = { health: vi.fn().mockResolvedValue(undefined) };
|
||||
const service = new HealthService(
|
||||
database as never,
|
||||
redis as never,
|
||||
{ get: vi.fn() } as never,
|
||||
);
|
||||
await expect(service.getReadiness()).rejects.toBeInstanceOf(
|
||||
ServiceUnavailableException,
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
if (originalDrainDelay === undefined) {
|
||||
delete process.env.DRAIN_DELAY_MS;
|
||||
} else {
|
||||
process.env.DRAIN_DELAY_MS = originalDrainDelay;
|
||||
}
|
||||
});
|
||||
|
||||
it('reports live and ready before shutdown starts', () => {
|
||||
const service = new HealthService();
|
||||
|
||||
expect(service.getLiveness()).toEqual({ status: 'ok' });
|
||||
expect(service.getReadiness()).toEqual({ status: 'ok' });
|
||||
});
|
||||
|
||||
it('keeps liveness healthy but rejects readiness while draining', () => {
|
||||
const service = new HealthService();
|
||||
service.setDraining();
|
||||
|
||||
expect(service.getLiveness()).toEqual({ status: 'ok' });
|
||||
expect(() => service.getReadiness()).toThrow(ServiceUnavailableException);
|
||||
expect(() => service.getReadiness()).toThrow('Service is shutting down');
|
||||
});
|
||||
|
||||
it('waits for the configured drain window after a termination signal', async () => {
|
||||
process.env.DRAIN_DELAY_MS = '5000';
|
||||
const service = new HealthService();
|
||||
|
||||
const shutdown = service.beforeApplicationShutdown('SIGTERM');
|
||||
await vi.advanceTimersByTimeAsync(4999);
|
||||
expect(() => service.getReadiness()).toThrow('Service is shutting down');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(shutdown).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not delay explicit application close without a signal', async () => {
|
||||
process.env.DRAIN_DELAY_MS = '5000';
|
||||
const service = new HealthService();
|
||||
|
||||
await expect(service.beforeApplicationShutdown()).resolves.toBeUndefined();
|
||||
expect(() => service.getReadiness()).toThrow('Service is shutting down');
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
it('keeps liveness healthy while draining', async () => {
|
||||
const service = new HealthService(
|
||||
{ health: vi.fn() } as never,
|
||||
{ health: vi.fn() } as never,
|
||||
{ get: vi.fn() } as never,
|
||||
);
|
||||
service.setDraining();
|
||||
expect(service.getLiveness()).toEqual({ status: 'ok' });
|
||||
await expect(service.getReadiness()).rejects.toThrow(
|
||||
'Service is shutting down',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,45 +1,47 @@
|
||||
import {
|
||||
Injectable,
|
||||
ServiceUnavailableException,
|
||||
Global,
|
||||
Injectable,
|
||||
Module,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import type { BeforeApplicationShutdown } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import { RedisClient } from '../redis/redis.client.js';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
|
||||
@Injectable()
|
||||
export class HealthService implements BeforeApplicationShutdown {
|
||||
private ready = true;
|
||||
private readonly drainDelayMs = this.readDrainDelay();
|
||||
|
||||
getLiveness() {
|
||||
return { status: 'ok' as const };
|
||||
}
|
||||
|
||||
getReadiness() {
|
||||
if (!this.ready) {
|
||||
throw new ServiceUnavailableException('Service is shutting down');
|
||||
}
|
||||
|
||||
return { status: 'ok' as const };
|
||||
}
|
||||
|
||||
setDraining(): void {
|
||||
this.ready = false;
|
||||
}
|
||||
|
||||
async beforeApplicationShutdown(signal?: string): Promise<void> {
|
||||
this.setDraining();
|
||||
|
||||
// Explicit app.close() in tests should remain immediate. Signals get a
|
||||
// drain window so orchestrators can observe readiness=503 before Nest
|
||||
// closes the HTTP server.
|
||||
if (signal && this.drainDelayMs > 0) {
|
||||
await new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, this.drainDelayMs);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private readDrainDelay(): number {
|
||||
const value = Number.parseInt(process.env.DRAIN_DELAY_MS ?? '5000', 10);
|
||||
return Number.isFinite(value) && value >= 0 ? value : 5000;
|
||||
}
|
||||
export class HealthService {
|
||||
private ready = true;
|
||||
constructor(
|
||||
private readonly database: DatabaseClient,
|
||||
private readonly redis: RedisClient,
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
) {}
|
||||
getLiveness() {
|
||||
return { status: 'ok' as const };
|
||||
}
|
||||
async getReadiness() {
|
||||
if (!this.ready)
|
||||
throw new ServiceUnavailableException('Service is shutting down');
|
||||
try {
|
||||
await Promise.all([this.database.health(), this.redis.health()]);
|
||||
} catch {
|
||||
throw new ServiceUnavailableException('Dependencies unavailable');
|
||||
}
|
||||
return { status: 'ok' as const };
|
||||
}
|
||||
setDraining() {
|
||||
this.ready = false;
|
||||
}
|
||||
async beforeApplicationShutdown(signal?: string): Promise<void> {
|
||||
this.setDraining();
|
||||
const delay = this.config.get<number>('DRAIN_DELAY_MS') ?? 5000;
|
||||
if (signal && delay > 0) {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Global()
|
||||
@Module({ providers: [HealthService], exports: [HealthService] })
|
||||
export class HealthServiceModule {}
|
||||
|
||||
+15
-14
@@ -1,23 +1,26 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
} from '@nestjs/platform-fastify';
|
||||
import { AppModule } from './app.module.js';
|
||||
import { ApiExceptionFilter } from './common/errors/api-exception.filter.js';
|
||||
import { MetricsService } from './metrics/metrics.service.js';
|
||||
import { RequestIdInterceptor } from './common/http/request-id.interceptor.js';
|
||||
|
||||
async function bootstrap() {
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.create<NestFastifyApplication>(
|
||||
AppModule,
|
||||
new FastifyAdapter({
|
||||
logger: true,
|
||||
}),
|
||||
new FastifyAdapter({ logger: true }),
|
||||
);
|
||||
app.useGlobalInterceptors(
|
||||
new RequestIdInterceptor(
|
||||
app.get(HttpAdapterHost),
|
||||
app.get(MetricsService),
|
||||
),
|
||||
);
|
||||
|
||||
app.useGlobalInterceptors(new RequestIdInterceptor());
|
||||
app.useGlobalFilters(new ApiExceptionFilter());
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
@@ -27,12 +30,10 @@ async function bootstrap() {
|
||||
);
|
||||
app.enableShutdownHooks();
|
||||
|
||||
const port = Number(process.env.APP_PORT ?? '8080');
|
||||
const host = process.env.APP_HOST ?? '0.0.0.0';
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error('APP_PORT must be an integer between 1 and 65535');
|
||||
}
|
||||
|
||||
const config = app.get(ConfigService);
|
||||
const port = config.getOrThrow<number>('APP_PORT');
|
||||
const host = config.getOrThrow<string>('APP_HOST');
|
||||
await app.listen(port, host);
|
||||
}
|
||||
|
||||
await bootstrap();
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { MetricsService } from '../../metrics/metrics.service.js';
|
||||
import { MessagesCacheService } from './messages-cache.service.js';
|
||||
|
||||
describe('MessagesCacheService metrics', () => {
|
||||
it('records a miss and a hit for a protected page fill', async () => {
|
||||
const metrics = new MetricsService();
|
||||
const page = { items: [], next_cursor: null };
|
||||
const redis = {
|
||||
get: vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValue(JSON.stringify(page)),
|
||||
setNxPx: vi.fn().mockResolvedValue(true),
|
||||
set: vi.fn().mockResolvedValue('OK'),
|
||||
unlock: vi.fn().mockResolvedValue(1),
|
||||
};
|
||||
const config = new ConfigService({
|
||||
CACHE_MODE: 'protected',
|
||||
CACHE_LOCK_TTL_MS: 1000,
|
||||
CACHE_TTL_SECONDS: 30,
|
||||
});
|
||||
const service = new MessagesCacheService(
|
||||
redis as never,
|
||||
config,
|
||||
metrics,
|
||||
);
|
||||
await service.getOrLoad('chat', 1n, undefined, 50, async () => page);
|
||||
await service.getOrLoad('chat', 1n, undefined, 50, async () => page);
|
||||
expect(metrics.snapshot().counters).toMatchObject({
|
||||
cache_miss: 1,
|
||||
cache_hit: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MessagesCacheService } from './messages-cache.service.js';
|
||||
import { MetricsModule } from '../../metrics/metrics.module.js';
|
||||
import { RedisModule } from '../../redis/redis.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [RedisModule, MetricsModule],
|
||||
providers: [MessagesCacheService],
|
||||
exports: [MessagesCacheService],
|
||||
})
|
||||
export class MessagesCacheModule {}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { AppConfig } from '../../config/app-config.schema.js';
|
||||
import type { RedisClient } from '../../redis/redis.client.js';
|
||||
import { MessagesCacheService } from './messages-cache.service.js';
|
||||
import { MetricsService } from '../../metrics/metrics.service.js';
|
||||
|
||||
function serviceWithRedis(redis: Partial<RedisClient>): MessagesCacheService {
|
||||
const config = new ConfigService<AppConfig>({
|
||||
CACHE_MODE: 'protected',
|
||||
CACHE_LOCK_TTL_MS: 1000,
|
||||
CACHE_TTL_SECONDS: 30,
|
||||
CACHE_MISS_DELAY_MS: 0,
|
||||
});
|
||||
return new MessagesCacheService(
|
||||
redis as RedisClient,
|
||||
config,
|
||||
new MetricsService(),
|
||||
);
|
||||
}
|
||||
|
||||
describe('MessagesCacheService fallback', () => {
|
||||
it('loads from the authoritative source when Redis read fails', async () => {
|
||||
const load = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ items: [{ id: 'db' }], next_cursor: null });
|
||||
const service = serviceWithRedis({
|
||||
get: vi.fn().mockRejectedValue(new Error('redis down')),
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.getOrLoad('chat', 1n, undefined, 50, load),
|
||||
).resolves.toEqual({
|
||||
items: [{ id: 'db' }],
|
||||
next_cursor: null,
|
||||
});
|
||||
expect(load).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('falls back after bounded lock contention', async () => {
|
||||
const load = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ items: [{ id: 'db' }], next_cursor: null });
|
||||
const service = serviceWithRedis({
|
||||
get: vi.fn().mockResolvedValue(null),
|
||||
setNxPx: vi.fn().mockResolvedValue(false),
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.getOrLoad('chat', 1n, undefined, 50, load),
|
||||
).resolves.toEqual({
|
||||
items: [{ id: 'db' }],
|
||||
next_cursor: null,
|
||||
});
|
||||
expect(load).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('returns the authoritative page when cache write fails', async () => {
|
||||
const page = { items: [{ id: 'db' }], next_cursor: null };
|
||||
const load = vi.fn().mockResolvedValue(page);
|
||||
const service = serviceWithRedis({
|
||||
get: vi.fn().mockResolvedValue(null),
|
||||
setNxPx: vi.fn().mockResolvedValue(true),
|
||||
set: vi.fn().mockRejectedValue(new Error('redis down')),
|
||||
unlock: vi.fn().mockResolvedValue(1),
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.getOrLoad('chat', 1n, undefined, 50, load),
|
||||
).resolves.toEqual(page);
|
||||
});
|
||||
});
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import type { AppConfig } from '../../config/app-config.schema.js';
|
||||
import { RedisClient } from '../../redis/redis.client.js';
|
||||
import { MetricsService } from '../../metrics/metrics.service.js';
|
||||
|
||||
const LOCK_RETRY_COUNT = 4;
|
||||
const LOCK_RETRY_DELAY_MS = 25;
|
||||
|
||||
export type CachePage = {
|
||||
items: unknown[];
|
||||
next_cursor: string | null;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class MessagesCacheService {
|
||||
private readonly logger = new Logger(MessagesCacheService.name);
|
||||
|
||||
constructor(
|
||||
private readonly redis: RedisClient,
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {}
|
||||
|
||||
async getOrLoad(
|
||||
chatId: string,
|
||||
version: bigint,
|
||||
cursor: string | undefined,
|
||||
limit: number,
|
||||
loader: () => Promise<CachePage>,
|
||||
): Promise<CachePage> {
|
||||
const key = this.cacheKey(chatId, version, cursor, limit);
|
||||
if (this.config.getOrThrow('CACHE_MODE') === 'naive') {
|
||||
return this.loadNaively(key, loader);
|
||||
}
|
||||
|
||||
let cached: string | null;
|
||||
try {
|
||||
cached = await this.redis.get(key);
|
||||
} catch (error) {
|
||||
return this.fallbackToDatabase('read', error, loader);
|
||||
}
|
||||
const cachedPage = this.parsePage(cached);
|
||||
if (cachedPage) {
|
||||
this.metrics.increment('cache_hit');
|
||||
return cachedPage;
|
||||
}
|
||||
this.metrics.increment('cache_miss');
|
||||
|
||||
const lockKey = `lock:${key}`;
|
||||
const owner = `${process.pid}:${Math.random().toString(36).slice(2)}`;
|
||||
for (let attempt = 0; attempt < LOCK_RETRY_COUNT; attempt += 1) {
|
||||
let locked: boolean;
|
||||
try {
|
||||
locked = await this.redis.setNxPx(
|
||||
lockKey,
|
||||
owner,
|
||||
this.config.getOrThrow('CACHE_LOCK_TTL_MS'),
|
||||
);
|
||||
} catch (error) {
|
||||
return this.fallbackToDatabase('lock', error, loader);
|
||||
}
|
||||
if (locked) return this.fillLocked(key, lockKey, owner, loader);
|
||||
|
||||
if (attempt === 0) this.metrics.increment('cache_lock_wait');
|
||||
try {
|
||||
const waitedPage = this.parsePage(await this.redis.get(key));
|
||||
if (waitedPage) {
|
||||
this.metrics.increment('cache_hit');
|
||||
return waitedPage;
|
||||
}
|
||||
} catch (error) {
|
||||
return this.fallbackToDatabase('waiting read', error, loader);
|
||||
}
|
||||
await delay(LOCK_RETRY_DELAY_MS);
|
||||
}
|
||||
|
||||
// The owner did not publish the page within the bounded wait: serve the
|
||||
// authoritative result instead of blocking the request further.
|
||||
this.metrics.increment('cache_lock_timeout');
|
||||
return loader();
|
||||
}
|
||||
|
||||
private async fillLocked(
|
||||
key: string,
|
||||
lockKey: string,
|
||||
owner: string,
|
||||
loader: () => Promise<CachePage>,
|
||||
): Promise<CachePage> {
|
||||
try {
|
||||
let secondCheck: string | null;
|
||||
try {
|
||||
secondCheck = await this.redis.get(key);
|
||||
} catch (error) {
|
||||
return this.fallbackToDatabase('double-check', error, loader);
|
||||
}
|
||||
const secondPage = this.parsePage(secondCheck);
|
||||
if (secondPage) {
|
||||
this.metrics.increment('cache_hit');
|
||||
return secondPage;
|
||||
}
|
||||
|
||||
const page = await loader();
|
||||
try {
|
||||
await this.redis.set(key, JSON.stringify(page), {
|
||||
EX: this.config.getOrThrow('CACHE_TTL_SECONDS'),
|
||||
});
|
||||
} catch (error) {
|
||||
// Redis is derived state: the page is still valid for this response,
|
||||
// but the failure must stay visible in metrics and logs.
|
||||
this.metrics.increment('cache_write_error');
|
||||
this.logger.warn(
|
||||
`Cache fill failed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
}
|
||||
return page;
|
||||
} finally {
|
||||
try {
|
||||
await this.redis.unlock(lockKey, owner);
|
||||
} catch (error) {
|
||||
// The lock has a TTL, so a stale lock expires on its own; a successful
|
||||
// response must not be replaced by an unlock failure.
|
||||
this.metrics.increment('cache_unlock_error');
|
||||
this.logger.warn(
|
||||
`Cache unlock failed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private cacheKey(
|
||||
chatId: string,
|
||||
version: bigint,
|
||||
cursor: string | undefined,
|
||||
limit: number,
|
||||
): string {
|
||||
return `messages:${chatId}:v${version.toString()}:c${cursor ?? 'start'}:l${limit}`;
|
||||
}
|
||||
|
||||
private async loadNaively(
|
||||
key: string,
|
||||
loader: () => Promise<CachePage>,
|
||||
): Promise<CachePage> {
|
||||
let cached: string | null;
|
||||
try {
|
||||
cached = await this.redis.get(key);
|
||||
} catch (error) {
|
||||
return this.fallbackToDatabase('naive read', error, loader);
|
||||
}
|
||||
const cachedPage = this.parsePage(cached);
|
||||
if (cachedPage) {
|
||||
this.metrics.increment('cache_hit');
|
||||
return cachedPage;
|
||||
}
|
||||
this.metrics.increment('cache_miss');
|
||||
|
||||
const cacheMissDelay = this.config.getOrThrow('CACHE_MISS_DELAY_MS');
|
||||
if (cacheMissDelay > 0) await delay(cacheMissDelay);
|
||||
const page = await loader();
|
||||
try {
|
||||
await this.redis.set(key, JSON.stringify(page), {
|
||||
EX: this.config.getOrThrow('CACHE_TTL_SECONDS'),
|
||||
});
|
||||
} catch (error) {
|
||||
this.metrics.increment('cache_write_error');
|
||||
this.logger.warn(
|
||||
`Cache fill failed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
private async fallbackToDatabase(
|
||||
stage: string,
|
||||
error: unknown,
|
||||
loader: () => Promise<CachePage>,
|
||||
): Promise<CachePage> {
|
||||
this.metrics.increment('cache_fallback');
|
||||
this.logger.warn(
|
||||
`Cache ${stage} failed, serving PostgreSQL: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
return loader();
|
||||
}
|
||||
|
||||
private parsePage(value: string | null): CachePage | undefined {
|
||||
if (!value) return undefined;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (
|
||||
typeof parsed !== 'object' ||
|
||||
parsed === null ||
|
||||
!('items' in parsed) ||
|
||||
!('next_cursor' in parsed) ||
|
||||
!Array.isArray(parsed.items) ||
|
||||
(parsed.next_cursor !== null &&
|
||||
typeof parsed.next_cursor !== 'string')
|
||||
)
|
||||
return undefined;
|
||||
return { items: parsed.items, next_cursor: parsed.next_cursor };
|
||||
} catch {
|
||||
// A malformed entry is treated as a miss and overwritten by the owner fill.
|
||||
this.metrics.increment('cache_corrupt_entry');
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { IsString, Length } from 'class-validator';
|
||||
|
||||
export class CreateMessageDto {
|
||||
@IsString()
|
||||
@Length(1, 4000)
|
||||
text!: string;
|
||||
@IsString()
|
||||
@Length(1, 4000)
|
||||
text!: string;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export type Message = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
@@ -1,55 +1,46 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
DefaultValuePipe,
|
||||
Get,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
DefaultValuePipe,
|
||||
Get,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import { CurrentUser } from '../common/auth/current-user.decorator.js';
|
||||
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
|
||||
import type { RequestWithCurrentUser } from '../common/auth/current-user.guard.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import { CreateMessageDto } from './dto/create-message.dto.js';
|
||||
import { MessagesService } from './messages.service.js';
|
||||
|
||||
type MessageRequest = FastifyRequest & RequestWithCurrentUser;
|
||||
|
||||
@Controller('api/v1/chats/:chatId/messages')
|
||||
@UseGuards(CurrentUserGuard)
|
||||
export class MessagesController {
|
||||
constructor(private readonly messagesService: MessagesService) {}
|
||||
constructor(private readonly messagesService: MessagesService) {}
|
||||
|
||||
@Post()
|
||||
create(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@Body() body: CreateMessageDto,
|
||||
@Req() request: MessageRequest,
|
||||
) {
|
||||
return this.messagesService.create(chatId, body, request.currentUser!);
|
||||
}
|
||||
@Post()
|
||||
create(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@Body() body: CreateMessageDto,
|
||||
@CurrentUser() currentUser: User,
|
||||
) {
|
||||
return this.messagesService.create(chatId, body, currentUser);
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@Req() request: MessageRequest,
|
||||
@Query('limit', new DefaultValuePipe(50), new ParseIntPipe()) limit: number,
|
||||
@Query('cursor') cursor?: string,
|
||||
) {
|
||||
if (limit < 1 || limit > 100) {
|
||||
throw new BadRequestException('limit must be between 1 and 100');
|
||||
}
|
||||
|
||||
return this.messagesService.list(
|
||||
chatId,
|
||||
request.currentUser!,
|
||||
limit,
|
||||
cursor,
|
||||
);
|
||||
}
|
||||
@Get()
|
||||
list(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@CurrentUser() currentUser: User,
|
||||
@Query('limit', new DefaultValuePipe(50), new ParseIntPipe())
|
||||
limit: number,
|
||||
@Query('cursor') cursor?: string,
|
||||
) {
|
||||
if (limit < 1 || limit > 100)
|
||||
throw new BadRequestException('limit must be between 1 and 100');
|
||||
return this.messagesService.list(chatId, currentUser, limit, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { DatabaseModule } from '../database/database.module.js';
|
||||
import { ChatsModule } from '../chats/chats.module.js';
|
||||
import { UsersModule } from '../users/users.module.js';
|
||||
import { MessagesController } from './messages.controller.js';
|
||||
import { MessagesRepository } from './messages.repository.js';
|
||||
import { MessagesService } from './messages.service.js';
|
||||
import { MessagesCacheModule } from './cache/messages-cache.module.js';
|
||||
import { UsersModule } from '../users/users.module.js';
|
||||
import { RedisModule } from '../redis/redis.module.js';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [UsersModule, ChatsModule],
|
||||
controllers: [MessagesController],
|
||||
providers: [MessagesRepository, MessagesService],
|
||||
imports: [
|
||||
ChatsModule,
|
||||
MessagesCacheModule,
|
||||
DatabaseModule,
|
||||
UsersModule,
|
||||
RedisModule,
|
||||
MetricsModule,
|
||||
],
|
||||
controllers: [MessagesController],
|
||||
providers: [MessagesRepository, MessagesService],
|
||||
})
|
||||
export class MessagesModule {}
|
||||
|
||||
@@ -1,42 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { Cursor } from '../common/http/cursor.js';
|
||||
import type { Message } from './message.js';
|
||||
import { MessagesRepository } from './messages.repository.js';
|
||||
|
||||
const message = (id: string, created_at: string): Message => ({
|
||||
id,
|
||||
chat_id: 'chat',
|
||||
sender_id: 'sender',
|
||||
text: id,
|
||||
created_at,
|
||||
id,
|
||||
chat_id: 'chat',
|
||||
sender_id: 'sender',
|
||||
text: id,
|
||||
created_at,
|
||||
});
|
||||
|
||||
describe('MessagesRepository', () => {
|
||||
it('appends messages whose key is after the current tail', () => {
|
||||
const repository = new MessagesRepository();
|
||||
repository.save(message('1', '2026-01-01T00:00:00.000Z'));
|
||||
repository.save(message('2', '2026-01-01T00:00:01.000Z'));
|
||||
it('uses named SQL history and a keyset cursor', async () => {
|
||||
const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 });
|
||||
const repository = new MessagesRepository({
|
||||
query,
|
||||
withTransaction: vi.fn(),
|
||||
} as never);
|
||||
const cursor: Cursor = {
|
||||
scope: 'messages:chat',
|
||||
created_at: '2026-01-01T00:00:01.000Z',
|
||||
id: '1',
|
||||
};
|
||||
await repository.findPage('chat', 10, cursor);
|
||||
expect(query).toHaveBeenCalledWith(
|
||||
'messages.history',
|
||||
expect.stringContaining('(created_at, id) >'),
|
||||
expect.arrayContaining(['chat', cursor.created_at, cursor.id, 11]),
|
||||
);
|
||||
});
|
||||
|
||||
expect(repository.findByChatId('chat').map((item) => item.id)).toEqual([
|
||||
'1',
|
||||
'2',
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps key order for delayed out-of-order messages', () => {
|
||||
const repository = new MessagesRepository();
|
||||
repository.save(message('2', '2026-01-01T00:00:02.000Z'));
|
||||
repository.save(message('1', '2026-01-01T00:00:01.000Z'));
|
||||
repository.save(message('3', '2026-01-01T00:00:03.000Z'));
|
||||
|
||||
const messages = repository.findByChatId('chat');
|
||||
expect(messages.map((item) => item.id)).toEqual(['1', '2', '3']);
|
||||
|
||||
const cursor: Cursor = {
|
||||
scope: 'messages:chat',
|
||||
created_at: '2026-01-01T00:00:01.000Z',
|
||||
id: '1',
|
||||
};
|
||||
expect(repository.findFirstAfter('chat', cursor)).toBe(1);
|
||||
});
|
||||
it('returns rows in response shape', async () => {
|
||||
const query = vi
|
||||
.fn()
|
||||
.mockResolvedValue({
|
||||
rows: [message('1', '2026-01-01T00:00:00.000Z')],
|
||||
rowCount: 1,
|
||||
});
|
||||
const repository = new MessagesRepository({ query } as never);
|
||||
await expect(repository.findPage('chat', 1)).resolves.toEqual({
|
||||
items: [message('1', '2026-01-01T00:00:00.000Z')],
|
||||
hasMore: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,68 +1,93 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import type { Cursor } from '../common/http/cursor.js';
|
||||
import { isAfter } from '../common/http/cursor.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import type { Message } from './message.js';
|
||||
|
||||
type MessageRow = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: Date | string;
|
||||
};
|
||||
|
||||
function toMessage(row: MessageRow): Message {
|
||||
return {
|
||||
id: row.id,
|
||||
chat_id: row.chat_id,
|
||||
sender_id: row.sender_id,
|
||||
text: row.text,
|
||||
created_at: new Date(row.created_at).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MessagesRepository {
|
||||
private readonly messagesByChatId = new Map<string, Message[]>();
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
save(message: Message): void {
|
||||
const messages = this.messagesByChatId.get(message.chat_id) ?? [];
|
||||
const last = messages.at(-1);
|
||||
async create(
|
||||
chatId: string,
|
||||
senderId: string,
|
||||
text: string,
|
||||
): Promise<Message> {
|
||||
const id = randomUUID();
|
||||
return this.database.withTransaction(async (client) => {
|
||||
const membership = await client.query({
|
||||
name: 'messages.checkMembership',
|
||||
text: 'SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2',
|
||||
values: [chatId, senderId],
|
||||
});
|
||||
if (!membership.rowCount) throw new NotFoundException();
|
||||
const result = await client.query<MessageRow>({
|
||||
name: 'messages.insert',
|
||||
text: 'INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) RETURNING id, chat_id, sender_id, text, created_at',
|
||||
values: [id, chatId, senderId, text],
|
||||
});
|
||||
await client.query({
|
||||
name: 'messages.incrementVersion',
|
||||
text: 'UPDATE chats SET message_version = message_version + 1 WHERE id = $1',
|
||||
values: [chatId],
|
||||
});
|
||||
return toMessage(result.rows[0]);
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
!last ||
|
||||
last.created_at < message.created_at ||
|
||||
(last.created_at === message.created_at && last.id < message.id)
|
||||
) {
|
||||
messages.push(message);
|
||||
this.messagesByChatId.set(message.chat_id, messages);
|
||||
return;
|
||||
}
|
||||
async getVersion(chatId: string, userId: string): Promise<bigint> {
|
||||
const result = await this.database.query<{ message_version: string }>(
|
||||
'messages.version',
|
||||
'SELECT c.message_version FROM chats c WHERE c.id = $1 AND EXISTS (SELECT 1 FROM chat_members WHERE chat_id = c.id AND user_id = $2)',
|
||||
[chatId, userId],
|
||||
);
|
||||
if (!result.rows[0]) throw new NotFoundException();
|
||||
return BigInt(result.rows[0].message_version);
|
||||
}
|
||||
|
||||
// Preserve keyset order if a delayed request carries an older key.
|
||||
let low = 0;
|
||||
let high = messages.length;
|
||||
|
||||
while (low < high) {
|
||||
const middle = Math.floor((low + high) / 2);
|
||||
const current = messages[middle];
|
||||
const comesAfter =
|
||||
current.created_at > message.created_at ||
|
||||
(current.created_at === message.created_at && current.id > message.id);
|
||||
|
||||
if (comesAfter) high = middle;
|
||||
else low = middle + 1;
|
||||
}
|
||||
|
||||
messages.splice(low, 0, message);
|
||||
this.messagesByChatId.set(message.chat_id, messages);
|
||||
}
|
||||
|
||||
findByChatId(chatId: string): Message[] {
|
||||
return this.messagesByChatId.get(chatId) ?? [];
|
||||
}
|
||||
|
||||
findFirstAfter(chatId: string, cursor: Cursor): number {
|
||||
const messages = this.messagesByChatId.get(chatId) ?? [];
|
||||
if (process.env.BENCHMARK_CURSOR_SEARCH === 'linear') {
|
||||
return messages.findIndex((message) =>
|
||||
isAfter(message.created_at, message.id, cursor),
|
||||
);
|
||||
}
|
||||
|
||||
let low = 0;
|
||||
let high = messages.length;
|
||||
while (low < high) {
|
||||
const middle = Math.floor((low + high) / 2);
|
||||
if (isAfter(messages[middle].created_at, messages[middle].id, cursor)) {
|
||||
high = middle;
|
||||
} else {
|
||||
low = middle + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return low;
|
||||
}
|
||||
async findPage(
|
||||
chatId: string,
|
||||
limit: number,
|
||||
cursor?: Cursor,
|
||||
): Promise<{ items: Message[]; hasMore: boolean }> {
|
||||
const values: unknown[] = [chatId];
|
||||
let predicate = '';
|
||||
if (cursor) {
|
||||
values.push(cursor.created_at, cursor.id);
|
||||
predicate = 'AND (created_at, id) > ($2::timestamptz, $3::uuid)';
|
||||
}
|
||||
values.push(limit + 1);
|
||||
const result = await this.database.query<MessageRow>(
|
||||
'messages.history',
|
||||
`SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 ${predicate} ORDER BY created_at, id LIMIT $${values.length}`,
|
||||
values,
|
||||
);
|
||||
return {
|
||||
items: result.rows.slice(0, limit).map(toMessage),
|
||||
hasMore: result.rows.length > limit,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,75 +1,75 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { decodeCursor, encodeCursor } from '../common/http/cursor.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import { ChatsService } from '../chats/chats.service.js';
|
||||
import type { CreateMessageDto } from './dto/create-message.dto.js';
|
||||
import type { Message } from './message.js';
|
||||
import { MessagesRepository } from './messages.repository.js';
|
||||
import { MessagesCacheService } from './cache/messages-cache.service.js';
|
||||
|
||||
@Injectable()
|
||||
export class MessagesService {
|
||||
constructor(
|
||||
private readonly messagesRepository: MessagesRepository,
|
||||
private readonly chatsService: ChatsService,
|
||||
) {}
|
||||
constructor(
|
||||
private readonly messagesRepository: MessagesRepository,
|
||||
private readonly chatsService: ChatsService,
|
||||
private readonly cache: MessagesCacheService,
|
||||
) {}
|
||||
|
||||
create(
|
||||
chatId: string,
|
||||
input: CreateMessageDto,
|
||||
currentUser: User,
|
||||
): Message {
|
||||
const chat = this.chatsService.getForUser(chatId, currentUser);
|
||||
async create(
|
||||
chatId: string,
|
||||
input: CreateMessageDto,
|
||||
currentUser: User,
|
||||
): Promise<Message> {
|
||||
await this.chatsService.getForUser(chatId, currentUser);
|
||||
if ([...input.text].every((character) => /\s/u.test(character)))
|
||||
throw new BadRequestException('Message text cannot be blank');
|
||||
return this.messagesRepository.create(
|
||||
chatId,
|
||||
currentUser.id,
|
||||
input.text,
|
||||
);
|
||||
}
|
||||
|
||||
if ([...input.text].every((character) => /\s/u.test(character))) {
|
||||
throw new BadRequestException('Message text cannot be blank');
|
||||
}
|
||||
|
||||
const message: Message = {
|
||||
id: randomUUID(),
|
||||
chat_id: chat.id,
|
||||
sender_id: currentUser.id,
|
||||
text: input.text,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
this.messagesRepository.save(message);
|
||||
return message;
|
||||
}
|
||||
|
||||
list(
|
||||
chatId: string,
|
||||
currentUser: User,
|
||||
limit: number,
|
||||
cursorValue?: string,
|
||||
): { items: Message[]; next_cursor: string | null } {
|
||||
this.chatsService.getForUser(chatId, currentUser);
|
||||
|
||||
const scope = `messages:${chatId}`;
|
||||
const cursor = cursorValue
|
||||
? decodeCursor(cursorValue, scope)
|
||||
: undefined;
|
||||
const messages = this.messagesRepository.findByChatId(chatId);
|
||||
const start = cursor
|
||||
? this.messagesRepository.findFirstAfter(chatId, cursor)
|
||||
: 0;
|
||||
const items = messages.slice(start, start + limit);
|
||||
const hasMore = messages.length > start + limit;
|
||||
const last = items.at(-1);
|
||||
|
||||
return {
|
||||
items,
|
||||
next_cursor:
|
||||
hasMore && last
|
||||
? encodeCursor({
|
||||
scope,
|
||||
created_at: last.created_at,
|
||||
id: last.id,
|
||||
})
|
||||
: null,
|
||||
};
|
||||
}
|
||||
async list(
|
||||
chatId: string,
|
||||
currentUser: User,
|
||||
limit: number,
|
||||
cursorValue?: string,
|
||||
): Promise<{ items: Message[]; next_cursor: string | null }> {
|
||||
await this.chatsService.getForUser(chatId, currentUser);
|
||||
const scope = `messages:${chatId}`;
|
||||
const cursor = cursorValue
|
||||
? decodeCursor(cursorValue, scope)
|
||||
: undefined;
|
||||
const version = await this.messagesRepository.getVersion(
|
||||
chatId,
|
||||
currentUser.id,
|
||||
);
|
||||
const page = await this.cache.getOrLoad(
|
||||
chatId,
|
||||
version,
|
||||
cursorValue,
|
||||
limit,
|
||||
async () => {
|
||||
const loaded = await this.messagesRepository.findPage(
|
||||
chatId,
|
||||
limit,
|
||||
cursor,
|
||||
);
|
||||
const lastLoaded = loaded.items.at(-1);
|
||||
return {
|
||||
items: loaded.items,
|
||||
next_cursor:
|
||||
loaded.hasMore && lastLoaded
|
||||
? encodeCursor({
|
||||
scope,
|
||||
created_at: lastLoaded.created_at,
|
||||
id: lastLoaded.id,
|
||||
})
|
||||
: null,
|
||||
};
|
||||
},
|
||||
);
|
||||
return page as { items: Message[]; next_cursor: string | null };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Headers,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Post,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { MetricsService } from './metrics.service.js';
|
||||
|
||||
@Controller('internal')
|
||||
export class MetricsController {
|
||||
constructor(
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {}
|
||||
|
||||
@Get('metrics')
|
||||
get(@Headers('authorization') authorization?: string) {
|
||||
this.requireToken(authorization);
|
||||
return this.metrics.snapshot();
|
||||
}
|
||||
|
||||
@Post('metrics/reset')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
reset(@Headers('authorization') authorization?: string): { status: 'ok' } {
|
||||
this.requireToken(authorization);
|
||||
this.metrics.reset();
|
||||
return { status: 'ok' };
|
||||
}
|
||||
|
||||
private requireToken(authorization?: string): void {
|
||||
const token = this.config.get<string>('METRICS_TOKEN');
|
||||
if (!token || authorization !== `Bearer ${token}`)
|
||||
throw new UnauthorizedException({
|
||||
message: 'Unauthorized',
|
||||
challenge: 'Bearer realm="metrics"',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MetricsController } from './metrics.controller.js';
|
||||
import { MetricsService } from './metrics.service.js';
|
||||
|
||||
@Module({
|
||||
controllers: [MetricsController],
|
||||
providers: [MetricsService],
|
||||
exports: [MetricsService],
|
||||
})
|
||||
export class MetricsModule {}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { MetricsService } from './metrics.service.js';
|
||||
|
||||
describe('MetricsService', () => {
|
||||
it('computes nearest-rank percentiles from observed latencies', () => {
|
||||
const metrics = new MetricsService();
|
||||
metrics.increment('cache_hit');
|
||||
metrics.increment('cache_hit');
|
||||
metrics.observeLatency(30);
|
||||
metrics.observeLatency(10);
|
||||
metrics.observeLatency(20);
|
||||
expect(metrics.snapshot()).toEqual({
|
||||
counters: { cache_hit: 2 },
|
||||
latency_ms: {
|
||||
count: 3,
|
||||
sample_count: 3,
|
||||
p50: 20,
|
||||
p95: 30,
|
||||
p99: 30,
|
||||
max: 30,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps snapshots isolated from callers and later observations', () => {
|
||||
const metrics = new MetricsService();
|
||||
metrics.increment('cache_hit');
|
||||
const snapshot = metrics.snapshot();
|
||||
snapshot.counters.cache_hit = 99;
|
||||
metrics.increment('cache_hit');
|
||||
expect(metrics.snapshot().counters.cache_hit).toBe(2);
|
||||
expect(snapshot.latency_ms.count).toBe(0);
|
||||
});
|
||||
|
||||
it('bounds retained samples but keeps cumulative count and maximum', () => {
|
||||
const metrics = new MetricsService();
|
||||
metrics.observeLatency(9000);
|
||||
for (let index = 0; index < 4096; index += 1)
|
||||
metrics.observeLatency(10);
|
||||
expect(metrics.snapshot().latency_ms).toEqual({
|
||||
count: 4097,
|
||||
sample_count: 4096,
|
||||
p50: 10,
|
||||
p95: 10,
|
||||
p99: 10,
|
||||
max: 9000,
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores invalid latency observations', () => {
|
||||
const metrics = new MetricsService();
|
||||
for (const value of [-1, NaN, Infinity]) metrics.observeLatency(value);
|
||||
expect(metrics.snapshot().latency_ms).toEqual({
|
||||
count: 0,
|
||||
sample_count: 0,
|
||||
p50: 0,
|
||||
p95: 0,
|
||||
p99: 0,
|
||||
max: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
const LATENCY_SAMPLE_CAPACITY = 4096;
|
||||
|
||||
type LatencySnapshot = {
|
||||
count: number;
|
||||
sample_count: number;
|
||||
p50: number;
|
||||
p95: number;
|
||||
p99: number;
|
||||
max: number;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class MetricsService {
|
||||
private readonly counters: Record<string, number> = {};
|
||||
private readonly latencies: number[] = [];
|
||||
private latencyCount = 0;
|
||||
private maximumLatency = 0;
|
||||
private nextSample = 0;
|
||||
|
||||
increment(name: string): void {
|
||||
this.counters[name] = (this.counters[name] ?? 0) + 1;
|
||||
}
|
||||
|
||||
observeLatency(milliseconds: number): void {
|
||||
if (!Number.isFinite(milliseconds) || milliseconds < 0) return;
|
||||
this.latencyCount += 1;
|
||||
this.maximumLatency = Math.max(this.maximumLatency, milliseconds);
|
||||
this.latencies[this.nextSample] = milliseconds;
|
||||
this.nextSample = (this.nextSample + 1) % LATENCY_SAMPLE_CAPACITY;
|
||||
}
|
||||
|
||||
snapshot(): {
|
||||
counters: Record<string, number>;
|
||||
latency_ms: LatencySnapshot;
|
||||
} {
|
||||
const sorted = [...this.latencies].sort((left, right) => left - right);
|
||||
return {
|
||||
counters: { ...this.counters },
|
||||
latency_ms: {
|
||||
count: this.latencyCount,
|
||||
sample_count: sorted.length,
|
||||
p50: this.percentile(sorted, 0.5),
|
||||
p95: this.percentile(sorted, 0.95),
|
||||
p99: this.percentile(sorted, 0.99),
|
||||
max: this.maximumLatency,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
for (const name of Object.keys(this.counters))
|
||||
delete this.counters[name];
|
||||
this.latencies.length = 0;
|
||||
this.latencyCount = 0;
|
||||
this.maximumLatency = 0;
|
||||
this.nextSample = 0;
|
||||
}
|
||||
|
||||
private percentile(sorted: number[], percentile: number): number {
|
||||
if (sorted.length === 0) return 0;
|
||||
const index = Math.min(
|
||||
sorted.length - 1,
|
||||
Math.ceil(sorted.length * percentile) - 1,
|
||||
);
|
||||
return sorted[index];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { createClient, type RedisClientType } from 'redis';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
|
||||
const UNLOCK_SCRIPT =
|
||||
'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';
|
||||
type Client = RedisClientType;
|
||||
|
||||
@Injectable()
|
||||
export class RedisClient implements OnModuleInit, OnModuleDestroy {
|
||||
readonly client: Client;
|
||||
private readonly logger = new Logger(RedisClient.name);
|
||||
|
||||
constructor(
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {
|
||||
this.client = createClient({
|
||||
url: this.config.getOrThrow('REDIS_URL'),
|
||||
disableOfflineQueue: true,
|
||||
socket: {
|
||||
reconnectStrategy: (attempt) =>
|
||||
Math.min(1000 + attempt * 250, 5000),
|
||||
connectTimeout: 5000,
|
||||
},
|
||||
}) as Client;
|
||||
// Reconnect failures must be visible; the readiness probe pings Redis.
|
||||
this.client.on('error', (error: Error) => {
|
||||
this.metrics.increment('redis.error');
|
||||
this.logger.warn(`Redis error: ${error.message}`);
|
||||
});
|
||||
}
|
||||
|
||||
async onModuleInit(): Promise<void> {
|
||||
await this.client.connect();
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
if (this.client.isOpen) await this.client.quit();
|
||||
}
|
||||
|
||||
async health(): Promise<void> {
|
||||
this.metrics.increment('redis.ping');
|
||||
await this.client.ping();
|
||||
}
|
||||
|
||||
async get(key: string): Promise<string | null> {
|
||||
this.metrics.increment('redis.get');
|
||||
return this.client.get(key);
|
||||
}
|
||||
|
||||
async set(
|
||||
key: string,
|
||||
value: string,
|
||||
options?: { EX?: number; PX?: number; NX?: boolean },
|
||||
): Promise<string | null> {
|
||||
this.metrics.increment('redis.set');
|
||||
return this.client.set(key, value, options);
|
||||
}
|
||||
|
||||
async setNxEx(
|
||||
key: string,
|
||||
value: string,
|
||||
seconds: number,
|
||||
): Promise<boolean> {
|
||||
this.metrics.increment('redis.set');
|
||||
return (
|
||||
(await this.client.set(key, value, { NX: true, EX: seconds })) ===
|
||||
'OK'
|
||||
);
|
||||
}
|
||||
|
||||
async setNxPx(
|
||||
key: string,
|
||||
value: string,
|
||||
milliseconds: number,
|
||||
): Promise<boolean> {
|
||||
this.metrics.increment('redis.set');
|
||||
return (
|
||||
(await this.client.set(key, value, {
|
||||
NX: true,
|
||||
PX: milliseconds,
|
||||
})) === 'OK'
|
||||
);
|
||||
}
|
||||
|
||||
async del(key: string): Promise<number> {
|
||||
this.metrics.increment('redis.del');
|
||||
return this.client.del(key);
|
||||
}
|
||||
|
||||
async incr(key: string): Promise<number> {
|
||||
this.metrics.increment('redis.incr');
|
||||
return this.client.incr(key);
|
||||
}
|
||||
|
||||
async expire(key: string, seconds: number): Promise<boolean> {
|
||||
this.metrics.increment('redis.expire');
|
||||
return (await this.client.expire(key, seconds)) === 1;
|
||||
}
|
||||
|
||||
async scan(
|
||||
cursor: number,
|
||||
pattern?: string,
|
||||
count = 100,
|
||||
): Promise<{ cursor: number; keys: string[] }> {
|
||||
this.metrics.increment('redis.scan');
|
||||
const result = await this.client.scan(String(cursor), {
|
||||
MATCH: pattern,
|
||||
COUNT: count,
|
||||
});
|
||||
return { cursor: Number(result.cursor), keys: result.keys };
|
||||
}
|
||||
|
||||
async unlock(key: string, owner: string): Promise<number> {
|
||||
this.metrics.increment('redis.unlock');
|
||||
return Number(
|
||||
await this.client.eval(UNLOCK_SCRIPT, {
|
||||
keys: [key],
|
||||
arguments: [owner],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
pipeline(commands: Array<[string, ...string[]]>): Promise<unknown[]> {
|
||||
this.metrics.increment('redis.pipeline');
|
||||
const multi = this.client.multi();
|
||||
for (const [command, ...args] of commands)
|
||||
multi.addCommand([command, ...args]);
|
||||
return multi.exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
import { RedisClient } from './redis.client.js';
|
||||
|
||||
@Module({
|
||||
imports: [MetricsModule],
|
||||
providers: [RedisClient],
|
||||
exports: [RedisClient],
|
||||
})
|
||||
export class RedisModule {}
|
||||
@@ -1,11 +1,18 @@
|
||||
import { IsNotEmpty, IsString, Matches } from 'class-validator';
|
||||
import { IsString, Length, Matches } from 'class-validator';
|
||||
|
||||
export class CreateUserDTO {
|
||||
@IsString()
|
||||
@Matches(/^[a-z0-9_]{3,32}$/)
|
||||
username: string;
|
||||
username!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
display_name: string;
|
||||
@Length(1, 100)
|
||||
@Matches(/\S/u, {
|
||||
message: 'display_name must contain a non-whitespace character',
|
||||
})
|
||||
display_name!: string;
|
||||
|
||||
@IsString()
|
||||
@Length(12, 128)
|
||||
password!: string;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import { UsersService } from './users.service.js';
|
||||
import { CreateUserDTO } from './dto/create-user.dto.js';
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
|
||||
import { CurrentUser } from '../common/auth/current-user.decorator.js';
|
||||
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
|
||||
import type { User } from './user.js';
|
||||
import { CreateUserDTO } from './dto/create-user.dto.js';
|
||||
import { UsersService } from './users.service.js';
|
||||
|
||||
@Controller('api/v1/users')
|
||||
export class UsersController {
|
||||
@@ -15,7 +16,7 @@ export class UsersController {
|
||||
|
||||
@Get('/me')
|
||||
@UseGuards(CurrentUserGuard)
|
||||
getMe(@Req() request: FastifyRequest) {
|
||||
return request.currentUser;
|
||||
getMe(@CurrentUser() currentUser: User) {
|
||||
return currentUser;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,14 @@ import { UsersController } from './users.controller.js';
|
||||
import { UsersRepository } from './users.repository.js';
|
||||
import { UsersService } from './users.service.js';
|
||||
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
|
||||
import { RedisModule } from '../redis/redis.module.js';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
import { DatabaseModule } from '../database/database.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, RedisModule, MetricsModule],
|
||||
controllers: [UsersController],
|
||||
providers: [UsersRepository, UsersService, CurrentUserGuard],
|
||||
exports: [UsersService, CurrentUserGuard],
|
||||
exports: [UsersService, CurrentUserGuard, RedisModule, MetricsModule],
|
||||
})
|
||||
export class UsersModule {}
|
||||
|
||||
@@ -1,25 +1,71 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { User } from './user.js';
|
||||
import { ConflictException, Injectable } from '@nestjs/common';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import type { User } from './user.js';
|
||||
|
||||
type UserRow = {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
password_hash: string;
|
||||
created_at: Date | string;
|
||||
};
|
||||
|
||||
function toUser(row: UserRow): User {
|
||||
return {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
display_name: row.display_name,
|
||||
created_at: new Date(row.created_at).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class UsersRepository {
|
||||
private readonly usersById = new Map<string, User>();
|
||||
private readonly userIdByUsername = new Map<string, string>();
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
findById(id: string): User | undefined {
|
||||
return this.usersById.get(id);
|
||||
}
|
||||
async findById(id: string): Promise<User | undefined> {
|
||||
const result = await this.database.query<UserRow>(
|
||||
'users.findById',
|
||||
'SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1',
|
||||
[id],
|
||||
);
|
||||
const row = result.rows[0];
|
||||
return row ? toUser(row) : undefined;
|
||||
}
|
||||
|
||||
findByUsername(username: string): User | undefined {
|
||||
const userId = this.userIdByUsername.get(username);
|
||||
if (!userId) {
|
||||
return undefined;
|
||||
}
|
||||
return this.usersById.get(userId);
|
||||
}
|
||||
async findByUsername(
|
||||
username: string,
|
||||
): Promise<(User & { password_hash: string }) | undefined> {
|
||||
const result = await this.database.query<UserRow>(
|
||||
'users.findByUsername',
|
||||
'SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1',
|
||||
[username],
|
||||
);
|
||||
const row = result.rows[0];
|
||||
return row
|
||||
? { ...toUser(row), password_hash: row.password_hash }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
save(user: User): void {
|
||||
this.usersById.set(user.id, user);
|
||||
this.userIdByUsername.set(user.username, user.id);
|
||||
}
|
||||
async create(user: {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
password_hash: string;
|
||||
}): Promise<User> {
|
||||
try {
|
||||
const result = await this.database.query<UserRow>(
|
||||
'users.insert',
|
||||
`INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, username, display_name, password_hash, created_at`,
|
||||
[user.id, user.username, user.display_name, user.password_hash],
|
||||
);
|
||||
return toUser(result.rows[0]);
|
||||
} catch (error) {
|
||||
if ((error as { code?: string }).code === '23505')
|
||||
throw new ConflictException('Username already exists');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,45 +1,38 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { UsersRepository } from './users.repository.js';
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import argon2 from 'argon2';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { CreateUserDTO } from './dto/create-user.dto.js';
|
||||
import { User } from './user.js';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { UsersRepository } from './users.repository.js';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private readonly usersRepository: UsersRepository) {}
|
||||
|
||||
create(input: CreateUserDTO): User {
|
||||
const displayNameLength = [...input.display_name].length;
|
||||
|
||||
async create(input: CreateUserDTO): Promise<User> {
|
||||
if (
|
||||
displayNameLength < 1 ||
|
||||
displayNameLength > 100 ||
|
||||
[...input.display_name].length < 1 ||
|
||||
[...input.display_name].length > 100 ||
|
||||
input.display_name.trim().length === 0
|
||||
) {
|
||||
throw new BadRequestException('Invalid display name');
|
||||
}
|
||||
|
||||
if (this.usersRepository.findByUsername(input.username)) {
|
||||
throw new ConflictException('Username already exists');
|
||||
}
|
||||
|
||||
const user: User = {
|
||||
const passwordHash = await argon2.hash(input.password, {
|
||||
type: argon2.argon2id,
|
||||
});
|
||||
return this.usersRepository.create({
|
||||
id: randomUUID(),
|
||||
username: input.username,
|
||||
display_name: input.display_name,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
this.usersRepository.save(user);
|
||||
|
||||
return user;
|
||||
password_hash: passwordHash,
|
||||
});
|
||||
}
|
||||
|
||||
findById(id: string): User | undefined {
|
||||
findById(id: string): Promise<User | undefined> {
|
||||
return this.usersRepository.findById(id);
|
||||
}
|
||||
|
||||
findByUsername(username: string) {
|
||||
return this.usersRepository.findByUsername(username);
|
||||
}
|
||||
}
|
||||
|
||||
+399
-285
@@ -1,313 +1,427 @@
|
||||
import { HealthService } from './../src/health/health.service.js';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { Pool } from 'pg';
|
||||
import { createClient } from 'redis';
|
||||
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { App } from 'supertest/types';
|
||||
import { AppModule } from './../src/app.module.js';
|
||||
import { RequestIdInterceptor } from './../src/common/http/request-id.interceptor.js';
|
||||
import { ApiExceptionFilter } from './../src/common/errors/api-exception.filter.js';
|
||||
// The suite is black-box: run it against the compiled application process.
|
||||
// Vitest sets process.env.BASE_URL itself (Vite base), so the API URL uses its own name.
|
||||
const baseUrl = (process.env.API_BASE_URL ?? 'http://localhost:8080').replace(
|
||||
/\/+$/u,
|
||||
'',
|
||||
);
|
||||
const basicChallenge = 'Basic realm="messenger", charset="UTF-8"';
|
||||
const bearerChallenge = 'Bearer realm="messenger"';
|
||||
const password = 'integration:пароль🔐';
|
||||
const runId = randomUUID().replaceAll('-', '').slice(0, 12);
|
||||
const usernames: string[] = [];
|
||||
const tokens: string[] = [];
|
||||
let sequence = 0;
|
||||
let database: Pool;
|
||||
let redis: ReturnType<typeof createClient>;
|
||||
|
||||
describe('Foundation HTTP contract', () => {
|
||||
let app: INestApplication<App>;
|
||||
type User = {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
created_at: string;
|
||||
};
|
||||
type Session = {
|
||||
token: string;
|
||||
token_type: string;
|
||||
expires_at: string;
|
||||
user: User;
|
||||
};
|
||||
type Chat = {
|
||||
id: string;
|
||||
title: string;
|
||||
member_ids: string[];
|
||||
created_at: string;
|
||||
};
|
||||
type Message = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
};
|
||||
type Page<T> = { items: T[]; next_cursor: string | null };
|
||||
type ApiError = {
|
||||
error: { code: string; message: string; request_id: string };
|
||||
};
|
||||
type Actor = { user: User; password: string; token: string };
|
||||
type HttpResult<T> = { body: T; response: Response };
|
||||
|
||||
beforeEach(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
async function http<T = unknown>(
|
||||
path: string,
|
||||
init: RequestInit = {},
|
||||
): Promise<HttpResult<T>> {
|
||||
const response = await fetch(`${baseUrl}${path}`, init);
|
||||
const text = await response.text();
|
||||
let body: unknown = undefined;
|
||||
if (text) {
|
||||
try {
|
||||
body = JSON.parse(text);
|
||||
} catch {
|
||||
body = text;
|
||||
}
|
||||
}
|
||||
return { body: body as T, response };
|
||||
}
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
function json(
|
||||
body: unknown,
|
||||
headers: Record<string, string> = {},
|
||||
): RequestInit {
|
||||
return {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
};
|
||||
}
|
||||
|
||||
app.useGlobalInterceptors(new RequestIdInterceptor());
|
||||
app.useGlobalFilters(new ApiExceptionFilter());
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
function basic(username: string, secret: string): string {
|
||||
return `Basic ${Buffer.from(`${username}:${secret}`, 'utf8').toString('base64')}`;
|
||||
}
|
||||
|
||||
await app.init();
|
||||
function bearer(token: string): Record<string, string> {
|
||||
return { authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
async function register(
|
||||
displayName = 'Интеграционный пользователь',
|
||||
secret = password,
|
||||
): Promise<User> {
|
||||
const username = `e2e_${runId}_${sequence++}`.slice(0, 32);
|
||||
usernames.push(username);
|
||||
const result = await http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: displayName, password: secret }),
|
||||
);
|
||||
expect(result.response.status).toBe(201);
|
||||
return result.body;
|
||||
}
|
||||
|
||||
async function login(user: User, secret = password): Promise<Session> {
|
||||
const result = await http<Session>('/api/v1/auth/sessions', {
|
||||
method: 'POST',
|
||||
headers: { authorization: basic(user.username, secret) },
|
||||
});
|
||||
expect(result.response.status).toBe(201);
|
||||
tokens.push(result.body.token);
|
||||
return result.body;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
async function actor(displayName?: string): Promise<Actor> {
|
||||
const user = await register(displayName);
|
||||
const session = await login(user);
|
||||
return { user, password, token: session.token };
|
||||
}
|
||||
|
||||
it('returns liveness status with request id', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/health/live')
|
||||
.expect(200);
|
||||
function expectError(
|
||||
result: HttpResult<ApiError>,
|
||||
status: number,
|
||||
code: string,
|
||||
): void {
|
||||
expect(result.response.status).toBe(status);
|
||||
expect(result.body.error.code).toBe(code);
|
||||
expect(result.body.error.request_id).toBe(
|
||||
result.response.headers.get('x-request-id'),
|
||||
);
|
||||
}
|
||||
|
||||
expect(response.body).toEqual({ status: 'ok' });
|
||||
expect(response.headers['x-request-id']).toEqual(expect.any(String));
|
||||
expect(response.headers['x-request-id']).not.toHaveLength(0);
|
||||
});
|
||||
|
||||
it('returns readiness status with request id', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/health/ready')
|
||||
.expect(200);
|
||||
|
||||
expect(response.body).toEqual({ status: 'ok' });
|
||||
expect(response.headers['x-request-id']).toEqual(expect.any(String));
|
||||
});
|
||||
|
||||
it('keeps liveness alive while readiness is draining', async () => {
|
||||
app.get(HealthService).setDraining();
|
||||
|
||||
const liveResponse = await request(app.getHttpServer())
|
||||
.get('/health/live')
|
||||
.expect(200);
|
||||
expect(liveResponse.body).toEqual({ status: 'ok' });
|
||||
|
||||
const readyResponse = await request(app.getHttpServer())
|
||||
.get('/health/ready')
|
||||
.expect(503);
|
||||
const requestId = readyResponse.headers['x-request-id'];
|
||||
expect(requestId).toEqual(expect.any(String));
|
||||
expect(readyResponse.body).toEqual({
|
||||
error: {
|
||||
code: 'unavailable',
|
||||
message: 'Service is shutting down',
|
||||
request_id: requestId,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('returns contract error with matching request id for unknown route', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/health/unknown')
|
||||
.expect(404);
|
||||
|
||||
const requestId = response.headers['x-request-id'];
|
||||
|
||||
expect(requestId).toEqual(expect.any(String));
|
||||
expect(response.body).toEqual({
|
||||
error: {
|
||||
code: 'not_found',
|
||||
message: 'Resource not found',
|
||||
request_id: requestId,
|
||||
},
|
||||
describe('HTTP integration contract', () => {
|
||||
beforeAll(async () => {
|
||||
database = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
connectionTimeoutMillis: 5000,
|
||||
});
|
||||
redis = createClient({
|
||||
url: process.env.REDIS_URL,
|
||||
socket: { reconnectStrategy: false },
|
||||
});
|
||||
redis.on('error', () => {});
|
||||
await redis.connect();
|
||||
});
|
||||
|
||||
it('registers a user and returns it from /me', async () => {
|
||||
const created = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'alice',
|
||||
display_name: 'Алиса',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const user = created.body;
|
||||
|
||||
const current = await request(app.getHttpServer())
|
||||
.get('/api/v1/users/me')
|
||||
.set('X-User-Id', user.id)
|
||||
.expect(200);
|
||||
|
||||
expect(current.body).toEqual(user);
|
||||
afterAll(async () => {
|
||||
if (usernames.length) {
|
||||
await database.query('BEGIN');
|
||||
try {
|
||||
await database.query(
|
||||
`DELETE FROM messages WHERE sender_id IN (SELECT id FROM users WHERE username = ANY($1::text[]))`,
|
||||
[usernames],
|
||||
);
|
||||
await database.query(
|
||||
`DELETE FROM chats WHERE id IN (SELECT chat_id FROM chat_members WHERE user_id IN (SELECT id FROM users WHERE username = ANY($1::text[])))`,
|
||||
[usernames],
|
||||
);
|
||||
await database.query(
|
||||
'DELETE FROM users WHERE username = ANY($1::text[])',
|
||||
[usernames],
|
||||
);
|
||||
await database.query('COMMIT');
|
||||
} catch (error) {
|
||||
await database.query('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (redis.isOpen) redis.destroy();
|
||||
await database.end();
|
||||
});
|
||||
|
||||
it('rejects /me without X-User-Id', async () => {
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/api/v1/users/me')
|
||||
.expect(401);
|
||||
|
||||
expect(response.body.error.code).toBe('unauthorized');
|
||||
expect(response.headers['x-request-id']).toBe(
|
||||
response.body.error.request_id,
|
||||
it('serves liveness and requires real session authentication', async () => {
|
||||
const live = await http<{ status: string }>('/health/live');
|
||||
expect(live.response.status).toBe(200);
|
||||
expect(live.body).toEqual({ status: 'ok' });
|
||||
const denied = await http<ApiError>('/api/v1/users/me');
|
||||
expectError(denied, 401, 'unauthorized');
|
||||
expect(denied.response.headers.get('www-authenticate')).toBe(
|
||||
bearerChallenge,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects duplicate usernames', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'duplicate_user',
|
||||
display_name: 'Первый',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'duplicate_user',
|
||||
display_name: 'Второй',
|
||||
})
|
||||
.expect(409);
|
||||
|
||||
expect(response.body.error.code).toBe('conflict');
|
||||
it('registers, logs in with Unicode/colon password, and challenges malformed Basic', async () => {
|
||||
const user = await register();
|
||||
const session = await login(user);
|
||||
expect(session.user.id).toBe(user.id);
|
||||
expect(session.token_type).toBe('Bearer');
|
||||
const me = await http<User>('/api/v1/users/me', {
|
||||
headers: bearer(session.token),
|
||||
});
|
||||
expect(me.response.status).toBe(200);
|
||||
expect(me.body.id).toBe(user.id);
|
||||
for (const authorization of [
|
||||
'Basic !!!',
|
||||
'Basic YWJj',
|
||||
'Bearer nope',
|
||||
]) {
|
||||
const result = await http<ApiError>('/api/v1/auth/sessions', {
|
||||
method: 'POST',
|
||||
headers: { authorization },
|
||||
});
|
||||
expectError(result, 401, 'unauthorized');
|
||||
expect(result.response.headers.get('www-authenticate')).toBe(
|
||||
basicChallenge,
|
||||
);
|
||||
}
|
||||
const bodyResult = await http<ApiError>('/api/v1/auth/sessions', {
|
||||
...json({ unexpected: true }),
|
||||
headers: { authorization: basic(user.username, password) },
|
||||
});
|
||||
expectError(bodyResult, 400, 'invalid_request');
|
||||
});
|
||||
|
||||
it('creates a chat and hides it from a non-member', async () => {
|
||||
const aliceResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'alice_chat',
|
||||
display_name: 'Алиса',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const bobResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'bob_chat',
|
||||
display_name: 'Боб',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const aliceId = aliceResponse.body.id;
|
||||
const bobId = bobResponse.body.id;
|
||||
|
||||
const chatResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', aliceId)
|
||||
.send({
|
||||
title: 'Учебный чат',
|
||||
member_ids: [aliceId, bobId],
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
expect(chatResponse.body.member_ids).toEqual([aliceId, bobId]);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/chats/${chatResponse.body.id}`)
|
||||
.set('X-User-Id', bobId)
|
||||
.expect(200);
|
||||
|
||||
const outsiderResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'charlie_chat',
|
||||
display_name: 'Чарли',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get(`/api/v1/chats/${chatResponse.body.id}`)
|
||||
.set('X-User-Id', outsiderResponse.body.id)
|
||||
.expect(404);
|
||||
it('returns conflict for concurrent duplicate registration', async () => {
|
||||
const username = `e2e_${runId}_race`.slice(0, 32);
|
||||
usernames.push(username);
|
||||
const results = await Promise.all([
|
||||
http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: 'Race A', password }),
|
||||
),
|
||||
http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: 'Race B', password }),
|
||||
),
|
||||
]);
|
||||
expect(
|
||||
results.filter((item) => item.response.status === 201),
|
||||
'duplicate registration must create exactly one user',
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
results.filter((item) => item.response.status === 409),
|
||||
'loser of the race must receive 409, not 500',
|
||||
).toHaveLength(1);
|
||||
// The database unique index is the race-proof guard, so verify its effect.
|
||||
const persisted = await database.query<{ count: string }>(
|
||||
'SELECT count(*)::text AS count FROM users WHERE username = $1',
|
||||
[username],
|
||||
);
|
||||
expect(persisted.rows[0]?.count).toBe('1');
|
||||
});
|
||||
|
||||
it('rejects chat when current user is not in member_ids', async () => {
|
||||
const aliceResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'alice_member',
|
||||
display_name: 'Алиса',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const bobResponse = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'bob_member',
|
||||
display_name: 'Боб',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', aliceResponse.body.id)
|
||||
.send({
|
||||
title: 'Неверный чат',
|
||||
member_ids: [bobResponse.body.id],
|
||||
})
|
||||
.expect(400);
|
||||
|
||||
expect(response.body.error.code).toBe('invalid_request');
|
||||
it('uses Bearer only, ignores X-User-Id spoofing, and prevents logout replay', async () => {
|
||||
const alice = await actor('Алиса');
|
||||
const bob = await actor('Боб');
|
||||
const spoof = await http<ApiError>('/api/v1/users/me', {
|
||||
headers: { ...bearer(alice.token), 'x-user-id': bob.user.id },
|
||||
});
|
||||
expect(spoof.response.status).toBe(200);
|
||||
expect((spoof.body as unknown as User).id).toBe(alice.user.id);
|
||||
const basicBusiness = await http<ApiError>('/api/v1/users/me', {
|
||||
headers: { authorization: basic(alice.user.username, password) },
|
||||
});
|
||||
expectError(basicBusiness, 401, 'unauthorized');
|
||||
expect(basicBusiness.response.headers.get('www-authenticate')).toBe(
|
||||
bearerChallenge,
|
||||
);
|
||||
const logout = await http('/api/v1/auth/sessions/current', {
|
||||
method: 'DELETE',
|
||||
headers: bearer(alice.token),
|
||||
});
|
||||
expect(logout.response.status).toBe(204);
|
||||
const replay = await http<ApiError>('/api/v1/users/me', {
|
||||
headers: bearer(alice.token),
|
||||
});
|
||||
expectError(replay, 401, 'unauthorized');
|
||||
});
|
||||
it('paginates chat history without repeating messages', async () => {
|
||||
const alice = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'page_alice', display_name: 'Алиса' })
|
||||
.expect(201);
|
||||
|
||||
const bob = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'page_bob', display_name: 'Боб' })
|
||||
.expect(201);
|
||||
it('rejects unknown and duplicate chat members and hides chats from outsiders', async () => {
|
||||
const alice = await actor();
|
||||
const bob = await actor();
|
||||
const outsider = await actor();
|
||||
const unknown = await http<ApiError>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: 'unknown', member_ids: [alice.user.id, randomUUID()] },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(unknown, 400, 'invalid_request');
|
||||
const leaked = await http<ApiError>(`/api/v1/chats?limit=100`, {
|
||||
headers: bearer(alice.token),
|
||||
});
|
||||
expect(leaked.response.status).toBe(200);
|
||||
expect(
|
||||
(leaked.body as unknown as Page<Chat>).items.some(
|
||||
(item) => item.title === 'unknown',
|
||||
),
|
||||
).toBe(false);
|
||||
const duplicate = await http<ApiError>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{
|
||||
title: 'duplicate',
|
||||
member_ids: [alice.user.id, alice.user.id],
|
||||
},
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(duplicate, 400, 'invalid_request');
|
||||
const created = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{
|
||||
title: `chat-${runId}`,
|
||||
member_ids: [alice.user.id, bob.user.id],
|
||||
},
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expect(created.response.status).toBe(201);
|
||||
const hidden = await http<ApiError>(
|
||||
`/api/v1/chats/${created.body.id}`,
|
||||
{ headers: bearer(outsider.token) },
|
||||
);
|
||||
expectError(hidden, 404, 'not_found');
|
||||
});
|
||||
|
||||
const aliceId = alice.body.id;
|
||||
const bobId = bob.body.id;
|
||||
const chat = await request(app.getHttpServer())
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', aliceId)
|
||||
.send({ title: 'История', member_ids: [aliceId, bobId] })
|
||||
.expect(201);
|
||||
it('keeps sender server-owned and makes writes visible to a second session', async () => {
|
||||
const alice = await actor();
|
||||
const secondSession = (await login(alice.user)).token;
|
||||
const chat = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: `messages-${runId}`, member_ids: [alice.user.id] },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expect(chat.response.status).toBe(201);
|
||||
const blank = await http<ApiError>(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json(
|
||||
{ text: ' \n\t', sender_id: randomUUID() },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(blank, 400, 'invalid_request');
|
||||
const spoof = await http<ApiError>(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json(
|
||||
{ text: 'hello', sender_id: randomUUID() },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(spoof, 400, 'invalid_request');
|
||||
await http(`/api/v1/chats/${chat.body.id}/messages?limit=50`, {
|
||||
headers: bearer(secondSession),
|
||||
});
|
||||
const sent = await http<Message>(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json({ text: 'hello' }, bearer(alice.token)),
|
||||
);
|
||||
expect(sent.response.status).toBe(201);
|
||||
expect(sent.body.sender_id).toBe(alice.user.id);
|
||||
const page = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=50`,
|
||||
{ headers: bearer(secondSession) },
|
||||
);
|
||||
expect(page.response.status).toBe(200);
|
||||
expect(page.body.items.map((item) => item.id)).toContain(sent.body.id);
|
||||
});
|
||||
|
||||
const createdMessages: Array<{ id: string }> = [];
|
||||
for (const text of ['one', 'two', 'three']) {
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.set('X-User-Id', aliceId)
|
||||
.send({ text })
|
||||
.expect(201);
|
||||
|
||||
createdMessages.push(response.body);
|
||||
}
|
||||
|
||||
const firstPage = await request(app.getHttpServer())
|
||||
.get(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.query({ limit: 2 })
|
||||
.set('X-User-Id', bobId)
|
||||
.expect(200);
|
||||
|
||||
expect(firstPage.body.items.map((item: { id: string }) => item.id)).toEqual(
|
||||
createdMessages.slice(0, 2).map((item) => item.id),
|
||||
);
|
||||
expect(firstPage.body.next_cursor).toEqual(expect.any(String));
|
||||
|
||||
const secondPage = await request(app.getHttpServer())
|
||||
.get(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.query({ limit: 2, cursor: firstPage.body.next_cursor })
|
||||
.set('X-User-Id', bobId)
|
||||
.expect(200);
|
||||
|
||||
expect(secondPage.body.items.map((item: { id: string }) => item.id)).toEqual(
|
||||
[createdMessages[2].id],
|
||||
);
|
||||
expect(secondPage.body.next_cursor).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects blank messages and sender spoofing fields', async () => {
|
||||
const alice = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'blank_alice', display_name: 'Алиса' })
|
||||
.expect(201);
|
||||
|
||||
const chat = await request(app.getHttpServer())
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', alice.body.id)
|
||||
.send({ title: 'Проверка', member_ids: [alice.body.id] })
|
||||
.expect(201);
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.post(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.set('X-User-Id', alice.body.id)
|
||||
.send({ text: ' ', sender_id: 'spoofed' })
|
||||
.expect(400);
|
||||
|
||||
expect(response.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('rejects an invalid cursor and an invalid limit', async () => {
|
||||
const alice = await request(app.getHttpServer())
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'cursor_alice', display_name: 'Алиса' })
|
||||
.expect(201);
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/api/v1/chats')
|
||||
.query({ limit: 101, cursor: 'not-a-cursor' })
|
||||
.set('X-User-Id', alice.body.id)
|
||||
.expect(400);
|
||||
|
||||
expect(response.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
it('validates cursor, limits, malformed JSON, and paginates without repeats', async () => {
|
||||
const alice = await actor();
|
||||
const chat = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: `pages-${runId}`, member_ids: [alice.user.id] },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
for (const text of ['one', 'two', 'three']) {
|
||||
const sent = await http(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json({ text }, bearer(alice.token)),
|
||||
);
|
||||
expect(sent.response.status).toBe(201);
|
||||
}
|
||||
const invalidLimit = await http<ApiError>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=101`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expectError(invalidLimit, 400, 'invalid_request');
|
||||
const invalidCursor = await http<ApiError>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?cursor=not-a-cursor`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expectError(invalidCursor, 400, 'invalid_request');
|
||||
const malformed = await http<ApiError>('/api/v1/users', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: '{',
|
||||
});
|
||||
expectError(malformed, 400, 'invalid_request');
|
||||
const first = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=2`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expect(first.body.items).toHaveLength(2);
|
||||
const second = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=2&cursor=${encodeURIComponent(first.body.next_cursor!)}`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expect(second.body.items).toHaveLength(1);
|
||||
expect(
|
||||
new Set(
|
||||
[...first.body.items, ...second.body.items].map(
|
||||
(item) => item.id,
|
||||
),
|
||||
).size,
|
||||
).toBe(3);
|
||||
});
|
||||
|
||||
it.skipIf(process.env.SESSION_TTL_SECONDS !== '2')(
|
||||
'expires sessions with TTL=2',
|
||||
async () => {
|
||||
const user = await register();
|
||||
const session = await login(user);
|
||||
await sleep(2300);
|
||||
const expired = await http<ApiError>('/api/v1/users/me', {
|
||||
headers: bearer(session.token),
|
||||
});
|
||||
expectError(expired, 401, 'unauthorized');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2,10 +2,13 @@ import { defineConfig } from 'vitest/config';
|
||||
import tsconfigPaths from 'vite-tsconfig-paths';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [tsconfigPaths()],
|
||||
test: {
|
||||
globals: true,
|
||||
root: './',
|
||||
include: ['**/*.e2e-spec.ts'],
|
||||
},
|
||||
plugins: [tsconfigPaths()],
|
||||
test: {
|
||||
globals: true,
|
||||
root: './',
|
||||
include: ['test/app.e2e-spec.ts'],
|
||||
testTimeout: 30_000,
|
||||
hookTimeout: 30_000,
|
||||
sequence: { concurrent: false },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# Коллекция Bruno: ручки messenger (lab 2)
|
||||
|
||||
Ручной клиент для API: регистрация, Basic-вход, Bearer-доступ, чаты, сообщения
|
||||
с пагинацией, метрики и негативные проверки. Формат — стандартный Bruno (`.bru`).
|
||||
|
||||
Связанные документы: [`../REPORT.md`](../REPORT.md) (архитектура и решения),
|
||||
[`../evidence/README.md`](../evidence/README.md) (индекс доказательств),
|
||||
[`../.github/pull_request_template.md`](../.github/pull_request_template.md) (сдача).
|
||||
|
||||
## Как открыть и запустить
|
||||
|
||||
```sh
|
||||
# GUI: Collection -> Open -> выбрать папку bruno/ этого репозитория.
|
||||
# baseUrl уже подставлен на уровне коллекции (collection.bru), вводить его
|
||||
# в каждой ручке не нужно. Для реального METRICS_TOKEN выберите окружение
|
||||
# `local` в правом верхнем углу и поправьте metricsToken.
|
||||
|
||||
# CLI (требуется @usebruno/cli; запускать из корня коллекции):
|
||||
npm install -g @usebruno/cli
|
||||
cd bruno
|
||||
bru run -r --env-var metricsToken=$(grep '^METRICS_TOKEN=' ../.env | cut -d= -f2)
|
||||
```
|
||||
|
||||
Проверено на `bru` 4.2.1 против локального стенда: 28 запросов, 56 проверок,
|
||||
все зелёные (см. `../evidence/level3-4-verification.md` §12).
|
||||
|
||||
Стенд должен быть поднят: `docker compose --env-file .env up -d --build`,
|
||||
готовность — `curl -fsS http://localhost:8080/health/ready`.
|
||||
|
||||
## Переменные и приоритет
|
||||
|
||||
| Источник | Что задаёт | Приоритет |
|
||||
|---|---|---|
|
||||
| `collection.bru` → `script:pre-request` | `baseUrl=http://localhost:8080`, `password=demo-password-123`, `metricsToken=change-me-metrics-token` | самый низкий: подставляется только если переменная нигде не задана |
|
||||
| `environments/local.bru` (`--env local`) | те же три переменные для конкретного стенда | выше дефолтов |
|
||||
| `--env-var name=value` (CLI) / runtime-переменные (GUI) | разовое значение | самый высокий |
|
||||
|
||||
Поэтому адрес API больше не нужно вводить в каждой ручке: он берётся из
|
||||
настроек коллекции. Если `metricsToken` оставить заглушкой, два запроса к
|
||||
`/internal/*` вернут 401 — это ожидаемо и описано в их `docs`; остальные 26
|
||||
запросов проходят.
|
||||
|
||||
## Окружение
|
||||
|
||||
`environments/local.bru`:
|
||||
|
||||
| Переменная | Значение по умолчанию | Комментарий |
|
||||
|---|---|---|
|
||||
| `baseUrl` | `http://localhost:8080` | адрес API |
|
||||
| `password` | `demo-password-123` | пароль демо-пользователей (12–128 code points) |
|
||||
| `metricsToken` | `change-me-metrics-token` | возьмите `METRICS_TOKEN` из `.env`, иначе запросы к `/internal/*` вернут 401 |
|
||||
|
||||
## Порядок выполнения
|
||||
|
||||
Папки обходятся по алфавиту, внутри папки — по `seq`:
|
||||
|
||||
```text
|
||||
auth/ регистрация трёх пользователей и три Basic-сессии, /users/me
|
||||
chats/ создание чата (два участника), список чатов, чат по id
|
||||
health/ /health/live и /health/ready
|
||||
internal/ /internal/metrics и /internal/metrics/reset
|
||||
messages/ два сообщения, первая страница истории, страница по курсору
|
||||
negative/ неверный пароль, Basic на бизнес-endpoint, X-User-Id, 404 чужого чата, 400 на limit/cursor и пробельный текст, 409 дубликата
|
||||
zz-cleanup/ logout и проверка, что отозванный токен даёт 401 (выполняется последним)
|
||||
```
|
||||
|
||||
Коллекция сохраняет переменные между запросами: `suffix`, `username`,
|
||||
`secondUsername`, `thirdUsername`, `userId`, `secondUserId`, `thirdUserId`,
|
||||
`token`, `secondToken`, `thirdToken`, `chatId`, `messageId`, `nextCursor`.
|
||||
Повторный запуск не конфликтует с прошлым прогоном: username генерируется
|
||||
из случайного суффикса, а дубликат проверяется отдельной негативной ручкой.
|
||||
|
||||
## Что проверяет каждая ручка
|
||||
|
||||
- `auth/register-user.bru` — 201, ответ без `password`/`password_hash`;
|
||||
- `auth/create-session*.bru` — 201, `token_type: Bearer`, `expires_at` в UTC, `user` совпадает с зарегистрированным;
|
||||
- `auth/me.bru` — Bearer-доступ и совпадение владельца;
|
||||
- `chats/create-chat.bru` — атомарное создание чата с двумя участниками;
|
||||
- `messages/send-message*.bru` — `sender_id` выведен из сессии, `chat_id` верный;
|
||||
- `messages/history-*.bru` — `limit` соблюдён, курсор ведёт на следующую страницу и не повторяет элемент;
|
||||
- `internal/metrics.bru` — счётчики и агрегаты латентности без секретов;
|
||||
- `negative/*` — коды и challenge-заголовки, отсутствие подмены владельца через `X-User-Id`, 404 вместо 403 для чужого чата, 409 при дубликате username, 400 на невалидные limit/cursor и пробельный текст.
|
||||
|
||||
## Проверка истечения сессии
|
||||
|
||||
```sh
|
||||
SESSION_TTL_SECONDS=2 docker compose --env-file .env up -d api
|
||||
# в Bruno: auth/create-session.bru -> создать сессию, подождать ~2.5 с
|
||||
# затем auth/me.bru -> ожидается 401 с Bearer-challenge
|
||||
docker compose --env-file .env up -d api # вернуть штатный TTL из .env
|
||||
```
|
||||
|
||||
## Границы
|
||||
|
||||
Коллекция — удобный ручной клиент, а не замена автоматике: контракт и приёмку
|
||||
проверяют `make test`, набор из `app/test/app.e2e-spec.ts` и бенчмарк трека 1
|
||||
(`scripts/track1_cache_benchmark.py`). Секретов в файлах нет: пароль и токен
|
||||
метрик задаются переменными окружения.
|
||||
@@ -0,0 +1,31 @@
|
||||
meta {
|
||||
name: Create second session (Basic)
|
||||
type: http
|
||||
seq: 5
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/auth/sessions
|
||||
body: none
|
||||
auth: basic
|
||||
}
|
||||
|
||||
auth:basic {
|
||||
username: {{secondUsername}}
|
||||
password: {{password}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Сессия второго участника чата: нужна, чтобы читать историю другой
|
||||
действующей сессией (read-after-write). Сохраняет secondToken.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("201 created", function() {
|
||||
expect(res.status).to.equal(201);
|
||||
});
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
bru.setVar("secondToken", res.body.token);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
meta {
|
||||
name: Create third session (Basic)
|
||||
type: http
|
||||
seq: 6
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/auth/sessions
|
||||
body: none
|
||||
auth: basic
|
||||
}
|
||||
|
||||
auth:basic {
|
||||
username: {{thirdUsername}}
|
||||
password: {{password}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Сессия постороннего пользователя: используется только в негативных
|
||||
проверках доступа к чужому чату. Сохраняет thirdToken.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("201 created", function() {
|
||||
expect(res.status).to.equal(201);
|
||||
});
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
bru.setVar("thirdToken", res.body.token);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
meta {
|
||||
name: Create session (Basic)
|
||||
type: http
|
||||
seq: 4
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/auth/sessions
|
||||
body: none
|
||||
auth: basic
|
||||
}
|
||||
|
||||
auth:basic {
|
||||
username: {{username}}
|
||||
password: {{password}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Вход: Authorization: Basic base64(username:password), тело запроса не передаётся.
|
||||
Пароль кодируется как UTF-8, разделитель — первый символ ":".
|
||||
Сохраняет token и expiresAt. Неверные credentials дают 401 с
|
||||
WWW-Authenticate: Basic realm="messenger", charset="UTF-8".
|
||||
}
|
||||
|
||||
tests {
|
||||
test("201 created", function() {
|
||||
expect(res.status).to.equal(201);
|
||||
});
|
||||
|
||||
test("token_type bearer", function() {
|
||||
expect(res.body.token_type).to.equal("Bearer");
|
||||
});
|
||||
|
||||
test("expires_at в UTC", function() {
|
||||
expect(res.body.expires_at).to.match(/Z$/);
|
||||
});
|
||||
|
||||
test("user совпадает с зарегистрированным", function() {
|
||||
expect(res.body.user.id).to.equal(bru.getVar("userId"));
|
||||
});
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
bru.setVar("token", res.body.token);
|
||||
bru.setVar("expiresAt", res.body.expires_at);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
meta {
|
||||
name: Current user
|
||||
type: http
|
||||
seq: 7
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/api/v1/users/me
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{token}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Бизнес-endpoint требует только Bearer. Basic здесь даёт 401,
|
||||
а заголовок X-User-Id сам по себе доступа не даёт и не подменяет владельца.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("status 200", function() {
|
||||
expect(res.status).to.equal(200);
|
||||
});
|
||||
|
||||
test("это тот же пользователь", function() {
|
||||
expect(res.body.id).to.equal(bru.getVar("userId"));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
meta {
|
||||
name: Register second user
|
||||
type: http
|
||||
seq: 2
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/users
|
||||
body: json
|
||||
auth: none
|
||||
}
|
||||
|
||||
docs {
|
||||
Второй пользователь: нужен для чата с двумя участниками и проверки,
|
||||
что чужой чат отдаёт 404. Сохраняет secondUserId и secondUsername,
|
||||
используя тот же пароль.
|
||||
}
|
||||
|
||||
script:pre-request {
|
||||
if (!bru.getVar("suffix")) {
|
||||
bru.setVar("suffix", Math.random().toString(36).slice(2, 10));
|
||||
}
|
||||
bru.setVar("secondUsername", `demo2_${bru.getVar("suffix")}`);
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"username": "{{secondUsername}}",
|
||||
"display_name": "Второй участник",
|
||||
"password": "{{password}}"
|
||||
}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("201 created", function() {
|
||||
expect(res.status).to.equal(201);
|
||||
});
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
bru.setVar("secondUserId", res.body.id);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
meta {
|
||||
name: Register third user
|
||||
type: http
|
||||
seq: 3
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/users
|
||||
body: json
|
||||
auth: none
|
||||
}
|
||||
|
||||
docs {
|
||||
Третий пользователь не входит в демо-чат: нужен, чтобы показать,
|
||||
что чужой чат отдаёт 404, а не раскрывает факт существования.
|
||||
}
|
||||
|
||||
script:pre-request {
|
||||
if (!bru.getVar("suffix")) {
|
||||
bru.setVar("suffix", Math.random().toString(36).slice(2, 10));
|
||||
}
|
||||
bru.setVar("thirdUsername", `demo3_${bru.getVar("suffix")}`);
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"username": "{{thirdUsername}}",
|
||||
"display_name": "Посторонний",
|
||||
"password": "{{password}}"
|
||||
}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("201 created", function() {
|
||||
expect(res.status).to.equal(201);
|
||||
});
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
bru.setVar("thirdUserId", res.body.id);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
meta {
|
||||
name: Register first user
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/users
|
||||
body: json
|
||||
auth: none
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"username": "{{username}}",
|
||||
"display_name": "Демо-пользователь",
|
||||
"password": "{{password}}"
|
||||
}
|
||||
}
|
||||
|
||||
vars:pre-request {
|
||||
baseUrl: http://localhost:8080
|
||||
}
|
||||
|
||||
script:pre-request {
|
||||
if (!bru.getVar("suffix")) {
|
||||
bru.setVar("suffix", Math.random().toString(36).slice(2, 10));
|
||||
}
|
||||
bru.setVar("username", `demo_${bru.getVar("suffix")}`);
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
bru.setVar("userId", res.body.id);
|
||||
bru.setVar("displayName", res.body.display_name);
|
||||
}
|
||||
|
||||
tests {
|
||||
test("201 created", function() {
|
||||
expect(res.status).to.equal(201);
|
||||
});
|
||||
|
||||
test("пароль и хеш не утекли", function() {
|
||||
expect(res.body).to.not.have.property("password");
|
||||
expect(res.body).to.not.have.property("password_hash");
|
||||
});
|
||||
}
|
||||
|
||||
docs {
|
||||
Регистрация с паролем (12–128 code points).
|
||||
Username генерируется из случайного суффикса, чтобы повторный запуск коллекции
|
||||
не упирался в 409. Сохраняет переменные: username, userId, displayName.
|
||||
Ответ никогда не содержит password или password_hash.
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"version": "1",
|
||||
"name": "mtusi-messenger-lab2",
|
||||
"type": "collection",
|
||||
"ignore": ["node_modules", ".git"]
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
meta {
|
||||
name: Create chat
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/chats
|
||||
body: json
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{token}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Составная операция в одной транзакции: проверка участников, вставка чата
|
||||
и всех chat_members. Текущий пользователь обязан входить в member_ids,
|
||||
неизвестные и дублирующиеся ID дают 400 без частичных данных.
|
||||
Сохраняет chatId.
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"title": "Демо-чат {{suffix}}",
|
||||
"member_ids": ["{{userId}}", "{{secondUserId}}"]
|
||||
}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("201 created", function() {
|
||||
expect(res.status).to.equal(201);
|
||||
});
|
||||
|
||||
test("оба участника в чате", function() {
|
||||
expect(res.body.member_ids).to.have.members([
|
||||
bru.getVar("userId"),
|
||||
bru.getVar("secondUserId")
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
bru.setVar("chatId", res.body.id);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
meta {
|
||||
name: Get chat by id
|
||||
type: http
|
||||
seq: 3
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/api/v1/chats/{{chatId}}
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{token}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Участник получает чат, посторонний — 404 (не 403: существование чужого
|
||||
объекта не раскрывается).
|
||||
}
|
||||
|
||||
tests {
|
||||
test("200 ok", function() {
|
||||
expect(res.status).to.equal(200);
|
||||
});
|
||||
|
||||
test("id совпадает", function() {
|
||||
expect(res.body.id).to.equal(bru.getVar("chatId"));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
meta {
|
||||
name: List my chats
|
||||
type: http
|
||||
seq: 2
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/api/v1/chats?limit=100
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{token}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Список только доступных чатов, сортировка по (created_at, id), keyset-cursor.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("200 ok", function() {
|
||||
expect(res.status).to.equal(200);
|
||||
});
|
||||
|
||||
test("созданный чат виден", function() {
|
||||
const ids = res.body.items.map(function(item) { return item.id; });
|
||||
expect(ids).to.include(bru.getVar("chatId"));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
script:pre-request {
|
||||
// Дефолты уровня коллекции: baseUrl не нужно вводить в каждой ручке.
|
||||
// ВАЖНО: bru.getVar читает только runtime-переменные, значения environment
|
||||
// приходят через bru.getEnvVar — поэтому проверяем оба источника и не
|
||||
// перекрываем то, что задано окружением.
|
||||
const defaults = {
|
||||
baseUrl: "http://localhost:8080",
|
||||
password: "demo-password-123",
|
||||
metricsToken: "GsdgewgDSFkoseGSJGpodsgsdppDS"
|
||||
};
|
||||
for (const name of Object.keys(defaults)) {
|
||||
if (!bru.getEnvVar(name) && !bru.getVar(name)) {
|
||||
bru.setVar(name, defaults[name]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
docs {
|
||||
# Настройки уровня коллекции.
|
||||
|
||||
Скрипт выше подставляет `baseUrl`, `password` и `metricsToken`, только если
|
||||
они не заданы environment-ом или runtime-переменной. Поэтому в GUI достаточно
|
||||
открыть коллекцию — вводить адрес в каждой ручке не требуется, а выбранный
|
||||
environment `local` (environments/local.bru) остаётся приоритетным.
|
||||
|
||||
Для реального токена метрик возьмите `METRICS_TOKEN` из `.env` (в GUI — через
|
||||
environment, в CLI — `--env-var metricsToken=...`). Без него `/internal/*`
|
||||
вернут 401: дефолт-заглушка намеренно не совпадает с рабочим токеном.
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
vars {
|
||||
baseUrl: http://localhost:8080
|
||||
password: demo-password-123
|
||||
metricsToken: change-me-metrics-token
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
meta {
|
||||
name: Health live
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/health/live
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
docs {
|
||||
Liveness процесса. Зависимости не проверяются: если API жив, ответ 200.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("status 200", function() {
|
||||
expect(res.status).to.equal(200);
|
||||
});
|
||||
|
||||
test("X-Request-Id присутствует", function() {
|
||||
expect(res.headers["x-request-id"]).to.be.a("string");
|
||||
expect(res.headers["x-request-id"].length).to.be.greaterThan(0);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
meta {
|
||||
name: Health ready
|
||||
type: http
|
||||
seq: 2
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/health/ready
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
docs {
|
||||
Readiness: 200 только если доступны PostgreSQL и Redis.
|
||||
При остановленном Redis или PostgreSQL вернётся 503 в общем формате ошибки.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("status 200", function() {
|
||||
expect(res.status).to.equal(200);
|
||||
});
|
||||
|
||||
test("status ok", function() {
|
||||
expect(res.body.status).to.equal("ok");
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
meta {
|
||||
name: Metrics reset
|
||||
type: http
|
||||
seq: 2
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/internal/metrics/reset
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{metricsToken}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Обнуляет счётчики процесса API (используется бенчмарком трека 1, чтобы
|
||||
считать дельту по повторности). На PostgreSQL и Redis не влияет.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("200 ok", function() {
|
||||
expect(res.status).to.equal(200);
|
||||
});
|
||||
|
||||
test("status ok", function() {
|
||||
expect(res.body.status).to.equal("ok");
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
meta {
|
||||
name: Metrics snapshot
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/internal/metrics
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{metricsToken}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Внутренний диагностический endpoint (не часть публичного контракта).
|
||||
Требует Authorization: Bearer <METRICS_TOKEN>; без него — 401.
|
||||
Возвращает счётчики SQL/Redis/cache/session и агрегаты латентности,
|
||||
без токенов, паролей и SQL-текста. Токен возьмите из .env (METRICS_TOKEN).
|
||||
}
|
||||
|
||||
tests {
|
||||
test("200 ok", function() {
|
||||
expect(res.status).to.equal(200);
|
||||
});
|
||||
|
||||
test("есть счётчики и латентность", function() {
|
||||
expect(res.body.counters).to.be.an("object");
|
||||
expect(res.body.latency_ms).to.have.property("p50");
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
meta {
|
||||
name: History first page
|
||||
type: http
|
||||
seq: 3
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/api/v1/chats/{{chatId}}/messages?limit=1
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{secondToken}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Keyset-пагинация по (created_at, id) по возрастанию. История читается
|
||||
любой действующей сессией участника — здесь второй сессией, что заодно
|
||||
показывает read-after-write для ранее отправленного сообщения.
|
||||
Сохраняет nextCursor.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("200 ok", function() {
|
||||
expect(res.status).to.equal(200);
|
||||
});
|
||||
|
||||
test("страница ограничена limit", function() {
|
||||
expect(res.body.items.length).to.equal(1);
|
||||
});
|
||||
|
||||
test("есть курсор на следующую страницу", function() {
|
||||
expect(res.body.next_cursor).to.be.a("string");
|
||||
});
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
bru.setVar("nextCursor", res.body.next_cursor);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
meta {
|
||||
name: History next page by cursor
|
||||
type: http
|
||||
seq: 4
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/api/v1/chats/{{chatId}}/messages?limit=1&cursor={{nextCursor}}
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{secondToken}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Продолжение по курсору. Курсор привязан к чату: значение от другого
|
||||
чата вернёт 400. Последний элемент предыдущей страницы не повторяется.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("200 ok", function() {
|
||||
expect(res.status).to.equal(200);
|
||||
});
|
||||
|
||||
test("второй элемент не дублирует первый", function() {
|
||||
expect(res.body.items.length).to.equal(1);
|
||||
expect(res.body.items[0].id).to.not.equal(bru.getVar("messageId"));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
meta {
|
||||
name: Send message as second user
|
||||
type: http
|
||||
seq: 2
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/chats/{{chatId}}/messages
|
||||
body: json
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{secondToken}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Любой участник чата может писать. Второе сообщение нужно, чтобы
|
||||
страница с limit=1 вернула next_cursor и пагинацию можно было проверить.
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"text": "Ответ второго участника"
|
||||
}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("201 created", function() {
|
||||
expect(res.status).to.equal(201);
|
||||
});
|
||||
|
||||
test("sender — второй пользователь", function() {
|
||||
expect(res.body.sender_id).to.equal(bru.getVar("secondUserId"));
|
||||
});
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
bru.setVar("secondMessageId", res.body.id);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
meta {
|
||||
name: Send message
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/chats/{{chatId}}/messages
|
||||
body: json
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{token}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Отправитель берётся из Bearer-идентичности; поле sender_id в теле
|
||||
не принимается (лишние поля — 400). Пустой или пробельный текст — 400.
|
||||
Запись коммитит сообщение и увеличивает chats.message_version в одной
|
||||
транзакции. Сохраняет messageId.
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"text": "Привет из Bruno 👋"
|
||||
}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("201 created", function() {
|
||||
expect(res.status).to.equal(201);
|
||||
});
|
||||
|
||||
test("sender выведен из сессии", function() {
|
||||
expect(res.body.sender_id).to.equal(bru.getVar("userId"));
|
||||
});
|
||||
|
||||
test("сообщение в нужном чате", function() {
|
||||
expect(res.body.chat_id).to.equal(bru.getVar("chatId"));
|
||||
});
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
bru.setVar("messageId", res.body.id);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
meta {
|
||||
name: Basic on business endpoint
|
||||
type: http
|
||||
seq: 2
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/api/v1/users/me
|
||||
body: none
|
||||
auth: basic
|
||||
}
|
||||
|
||||
auth:basic {
|
||||
username: {{username}}
|
||||
password: {{password}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Basic принимается только на POST /auth/sessions. На бизнес-endpoint
|
||||
он даёт 401 с Bearer-challenge, даже если credentials верные.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("401 unauthorized", function() {
|
||||
expect(res.status).to.equal(401);
|
||||
});
|
||||
|
||||
test("Bearer challenge", function() {
|
||||
expect(res.headers["www-authenticate"]).to.equal('Bearer realm="messenger"');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
meta {
|
||||
name: Blank message and extra field
|
||||
type: http
|
||||
seq: 7
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/chats/{{chatId}}/messages
|
||||
body: json
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{token}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Пробельный текст запрещён, а поле sender_id не принимается:
|
||||
strict validation отвечает 400 (лишние поля отклоняются, а не игнорируются).
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"text": " ",
|
||||
"sender_id": "{{secondUserId}}"
|
||||
}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("400 invalid_request", function() {
|
||||
expect(res.status).to.equal(400);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
meta {
|
||||
name: Duplicate username returns 409
|
||||
type: http
|
||||
seq: 8
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/users
|
||||
body: json
|
||||
auth: none
|
||||
}
|
||||
|
||||
docs {
|
||||
Повторная регистрация того же username. Уникальность обеспечивает
|
||||
unique-индекс PostgreSQL, ошибка 23505 маппится в 409 (не 500).
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"username": "{{username}}",
|
||||
"display_name": "Дубликат",
|
||||
"password": "{{password}}"
|
||||
}
|
||||
}
|
||||
|
||||
tests {
|
||||
test("409 conflict", function() {
|
||||
expect(res.status).to.equal(409);
|
||||
});
|
||||
|
||||
test("код ошибки conflict", function() {
|
||||
expect(res.body.error.code).to.equal("conflict");
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
meta {
|
||||
name: Invalid limit and cursor
|
||||
type: http
|
||||
seq: 6
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/api/v1/chats/{{chatId}}/messages?limit=101&cursor=not-a-cursor
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{token}}
|
||||
}
|
||||
|
||||
docs {
|
||||
limit вне 1..100 и неизвестный cursor — 400 invalid_request,
|
||||
в одном формате ошибки с request_id, совпадающим с заголовком.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("400 invalid_request", function() {
|
||||
expect(res.status).to.equal(400);
|
||||
});
|
||||
|
||||
test("формат ошибки по контракту", function() {
|
||||
expect(res.body.error.code).to.equal("invalid_request");
|
||||
expect(res.body.error.request_id).to.equal(res.headers["x-request-id"]);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
meta {
|
||||
name: Non-member receives 404
|
||||
type: http
|
||||
seq: 5
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/api/v1/chats/{{chatId}}
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{thirdToken}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Аутентификация прошла, но доступа к ресурсу нет. Контракт требует 404,
|
||||
а не 403: существование чужого чата не раскрывается.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("404 not_found", function() {
|
||||
expect(res.status).to.equal(404);
|
||||
});
|
||||
|
||||
test("код ошибки not_found", function() {
|
||||
expect(res.body.error.code).to.equal("not_found");
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
meta {
|
||||
name: Wrong password
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{baseUrl}}/api/v1/auth/sessions
|
||||
body: none
|
||||
auth: basic
|
||||
}
|
||||
|
||||
auth:basic {
|
||||
username: {{username}}
|
||||
password: definitely-wrong-password
|
||||
}
|
||||
|
||||
docs {
|
||||
Неверный пароль: 401 без раскрытия, существует ли пользователь,
|
||||
и с тем же Basic-challenge, что и при неизвестном пользователе.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("401 unauthorized", function() {
|
||||
expect(res.status).to.equal(401);
|
||||
});
|
||||
|
||||
test("Basic challenge", function() {
|
||||
expect(res.headers["www-authenticate"]).to.equal('Basic realm="messenger", charset="UTF-8"');
|
||||
});
|
||||
|
||||
test("request_id совпадает с заголовком", function() {
|
||||
expect(res.body.error.request_id).to.equal(res.headers["x-request-id"]);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
meta {
|
||||
name: X-User-Id alone does not authenticate
|
||||
type: http
|
||||
seq: 3
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/api/v1/users/me
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
X-User-Id: {{userId}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Заголовок X-User-Id остался от lab1 и с lab2 не даёт доступа:
|
||||
без действующей Bearer-сессии ответ 401.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("401 unauthorized", function() {
|
||||
expect(res.status).to.equal(401);
|
||||
});
|
||||
|
||||
test("Bearer challenge", function() {
|
||||
expect(res.headers["www-authenticate"]).to.equal('Bearer realm="messenger"');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
meta {
|
||||
name: X-User-Id cannot spoof the session owner
|
||||
type: http
|
||||
seq: 4
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/api/v1/users/me
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{token}}
|
||||
X-User-Id: {{secondUserId}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Владелец запроса определяется только токеном: X-User-Id с ID другого
|
||||
пользователя игнорируется, ответ содержит владельца сессии.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("200 ok", function() {
|
||||
expect(res.status).to.equal(200);
|
||||
});
|
||||
|
||||
test("вернулся владелец сессии, а не подставленный ID", function() {
|
||||
expect(res.body.id).to.equal(bru.getVar("userId"));
|
||||
expect(res.body.id).to.not.equal(bru.getVar("secondUserId"));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
meta {
|
||||
name: Logout current session (run last)
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
|
||||
delete {
|
||||
url: {{baseUrl}}/api/v1/auth/sessions/current
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{token}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Папка zz-cleanup выполняется последней: отзываем основную сессию и
|
||||
проверяем, что тот же токен больше не принимается. Ответ 204 без тела.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("204 no content", function() {
|
||||
expect(res.status).to.equal(204);
|
||||
});
|
||||
|
||||
test("тела нет", function() {
|
||||
expect(res.body === "" || res.body === undefined).to.be.true;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
meta {
|
||||
name: Revoked token is rejected
|
||||
type: http
|
||||
seq: 2
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{baseUrl}}/api/v1/users/me
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Authorization: Bearer {{token}}
|
||||
}
|
||||
|
||||
docs {
|
||||
Повторное использование отозванного токена: 401 с Bearer-challenge.
|
||||
Ожидаемый результат после logout-current-session.
|
||||
}
|
||||
|
||||
tests {
|
||||
test("401 unauthorized", function() {
|
||||
expect(res.status).to.equal(401);
|
||||
});
|
||||
|
||||
test("Bearer challenge", function() {
|
||||
expect(res.headers["www-authenticate"]).to.equal('Bearer realm="messenger"');
|
||||
});
|
||||
}
|
||||
+66
-12
@@ -1,13 +1,67 @@
|
||||
services:
|
||||
nest-app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: mtusi-messenger:lab2
|
||||
ports:
|
||||
- ${APP_PUBLIC_PORT:-8080}:${APP_PORT:-8080}
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
BENCHMARK_CURSOR_SEARCH: ${BENCHMARK_CURSOR_SEARCH:-binary}
|
||||
stop_grace_period: 30s
|
||||
postgres:
|
||||
image: postgres:16.4-alpine
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
|
||||
redis:
|
||||
image: redis:7.4.2-alpine
|
||||
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"]
|
||||
volumes:
|
||||
- redis-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
|
||||
migrate:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: mtusi-messenger:lab2
|
||||
command: ["node", "dist/database/migration.runner.js"]
|
||||
env_file: [.env]
|
||||
depends_on:
|
||||
postgres: { condition: service_healthy }
|
||||
redis: { condition: service_healthy }
|
||||
restart: "no"
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: mtusi-messenger:lab2
|
||||
ports:
|
||||
- "${APP_PUBLIC_PORT:-8080}:${APP_PORT:-8080}"
|
||||
env_file: [.env]
|
||||
# Declared here so a one-off experiment can override them from the shell
|
||||
# (shell env wins over env_file), e.g.:
|
||||
# CACHE_MODE=naive CACHE_MISS_DELAY_MS=75 docker compose up -d api
|
||||
# SESSION_TTL_SECONDS=2 docker compose up -d api
|
||||
environment:
|
||||
CACHE_MODE: ${CACHE_MODE:-protected}
|
||||
CACHE_MISS_DELAY_MS: ${CACHE_MISS_DELAY_MS:-0}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
depends_on:
|
||||
migrate: { condition: service_completed_successfully }
|
||||
postgres: { condition: service_healthy }
|
||||
redis: { condition: service_healthy }
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:'+ (process.env.APP_PORT||8080) + '/health/ready').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
redis-data:
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# Граф модулей NestJS
|
||||
|
||||
Артефакты в этой папке генерируются командой `npm run graph` из `app/`
|
||||
и описывают реальный граф зависимостей приложения:
|
||||
|
||||
| Файл | Содержимое |
|
||||
|---|---|
|
||||
| `nest-module-details.json` | Модули, imports, providers, controllers, exports и constructor-зависимости (из compiled metadata). |
|
||||
| `nest-module-graph.mmd` | Mermaid-граф: сплошные стрелки — imports модулей, пунктирные — внедрения провайдеров. |
|
||||
| `nest-dependency-graph.md` | Тот же граф плюс таблицы по каждому модулю (удобно смотреть в Markdown-preview). |
|
||||
|
||||
Генератор: `app/scripts/graph-modules.ts` (использует `nestjs-spelunker`).
|
||||
Команда не подключается к PostgreSQL или Redis: для неё подставляются фиктивные
|
||||
`DATABASE_URL`/`REDIS_URL`, поэтому стенд поднимать не нужно.
|
||||
|
||||
Перегенерация:
|
||||
|
||||
```sh
|
||||
cd app && npm run graph
|
||||
```
|
||||
|
||||
Зачем это в отчёте: граф показал, где зависимости держались на глобальном scope
|
||||
и где объявления модулей не отражали реальное устройство DI — именно это привело
|
||||
к падению API с `UnknownDependenciesException` (см. `evidence/level3-4-verification.md`
|
||||
§13). Ссылки на разбор: [`../../REPORT.md`](../../REPORT.md),
|
||||
[`../../evidence/README.md`](../../evidence/README.md).
|
||||
@@ -0,0 +1,247 @@
|
||||
# NestJS dependency graph
|
||||
|
||||
Generated from `AppModule` with `nestjs-spelunker` static module debugging.
|
||||
|
||||
- Solid arrows: module imports.
|
||||
- Dotted arrows: constructor dependencies.
|
||||
- The generator does not boot PostgreSQL or Redis.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
%% Generated by scripts/graph-modules.ts
|
||||
%% Solid arrows: module imports; dotted arrows: constructor dependencies
|
||||
subgraph AppModule["AppModule"]
|
||||
AppModule_APP_FILTER["provider: APP_FILTER"]
|
||||
end
|
||||
subgraph AppConfigModule["AppConfigModule"]
|
||||
end
|
||||
subgraph ConfigModule["ConfigModule"]
|
||||
ConfigModule_ConfigService["provider: ConfigService"]
|
||||
ConfigModule_VALIDATED_ENV_LOADER["provider: VALIDATED_ENV_LOADER"]
|
||||
end
|
||||
subgraph DatabaseModule["DatabaseModule"]
|
||||
DatabaseModule_DatabaseClient["provider: DatabaseClient"]
|
||||
end
|
||||
subgraph MetricsModule["MetricsModule"]
|
||||
MetricsModule_MetricsService["provider: MetricsService"]
|
||||
MetricsModule_MetricsController["controller: MetricsController"]
|
||||
end
|
||||
subgraph RedisModule["RedisModule"]
|
||||
RedisModule_RedisClient["provider: RedisClient"]
|
||||
end
|
||||
subgraph UsersModule["UsersModule"]
|
||||
UsersModule_UsersRepository["provider: UsersRepository"]
|
||||
UsersModule_UsersService["provider: UsersService"]
|
||||
UsersModule_CurrentUserGuard["provider: CurrentUserGuard"]
|
||||
UsersModule_UsersController["controller: UsersController"]
|
||||
end
|
||||
subgraph AuthModule["AuthModule"]
|
||||
AuthModule_AuthService["provider: AuthService"]
|
||||
AuthModule_SessionRepository["provider: SessionRepository"]
|
||||
AuthModule_AuthController["controller: AuthController"]
|
||||
end
|
||||
subgraph HealthModule["HealthModule"]
|
||||
HealthModule_HealthService["provider: HealthService"]
|
||||
HealthModule_HealthController["controller: HealthController"]
|
||||
end
|
||||
subgraph ChatsModule["ChatsModule"]
|
||||
ChatsModule_ChatsRepository["provider: ChatsRepository"]
|
||||
ChatsModule_ChatsService["provider: ChatsService"]
|
||||
ChatsModule_ChatsController["controller: ChatsController"]
|
||||
end
|
||||
subgraph MessagesModule["MessagesModule"]
|
||||
MessagesModule_MessagesRepository["provider: MessagesRepository"]
|
||||
MessagesModule_MessagesService["provider: MessagesService"]
|
||||
MessagesModule_MessagesController["controller: MessagesController"]
|
||||
end
|
||||
subgraph MessagesCacheModule["MessagesCacheModule"]
|
||||
MessagesCacheModule_MessagesCacheService["provider: MessagesCacheService"]
|
||||
end
|
||||
AppModule -->|imports| AppConfigModule
|
||||
AppModule -->|imports| DatabaseModule
|
||||
AppModule -->|imports| RedisModule
|
||||
AppModule -->|imports| UsersModule
|
||||
AppModule -->|imports| AuthModule
|
||||
AppModule -->|imports| HealthModule
|
||||
AppModule -->|imports| ChatsModule
|
||||
AppModule -->|imports| MessagesModule
|
||||
AppModule -->|imports| MetricsModule
|
||||
AppConfigModule -->|imports| ConfigModule
|
||||
DatabaseModule -->|imports| MetricsModule
|
||||
DatabaseModule_DatabaseClient -.->|injects| ConfigModule_ConfigService
|
||||
DatabaseModule_DatabaseClient -.->|injects| MetricsModule_MetricsService
|
||||
MetricsModule_MetricsController -.->|injects| ConfigModule_ConfigService
|
||||
MetricsModule_MetricsController -.->|injects| MetricsModule_MetricsService
|
||||
RedisModule -->|imports| MetricsModule
|
||||
RedisModule_RedisClient -.->|injects| ConfigModule_ConfigService
|
||||
RedisModule_RedisClient -.->|injects| MetricsModule_MetricsService
|
||||
UsersModule -->|imports| DatabaseModule
|
||||
UsersModule -->|imports| RedisModule
|
||||
UsersModule -->|imports| MetricsModule
|
||||
UsersModule_UsersRepository -.->|injects| DatabaseModule_DatabaseClient
|
||||
UsersModule_UsersService -.->|injects| UsersModule_UsersRepository
|
||||
UsersModule_CurrentUserGuard -.->|injects| RedisModule_RedisClient
|
||||
UsersModule_CurrentUserGuard -.->|injects| UsersModule_UsersService
|
||||
UsersModule_CurrentUserGuard -.->|injects| MetricsModule_MetricsService
|
||||
UsersModule_UsersController -.->|injects| UsersModule_UsersService
|
||||
AuthModule -->|imports| UsersModule
|
||||
AuthModule -->|imports| DatabaseModule
|
||||
AuthModule -->|imports| RedisModule
|
||||
AuthModule -->|imports| MetricsModule
|
||||
AuthModule_AuthService -.->|injects| UsersModule_UsersService
|
||||
AuthModule_AuthService -.->|injects| AuthModule_SessionRepository
|
||||
AuthModule_SessionRepository -.->|injects| RedisModule_RedisClient
|
||||
AuthModule_SessionRepository -.->|injects| ConfigModule_ConfigService
|
||||
AuthModule_SessionRepository -.->|injects| MetricsModule_MetricsService
|
||||
AuthModule_AuthController -.->|injects| AuthModule_AuthService
|
||||
HealthModule -->|imports| DatabaseModule
|
||||
HealthModule -->|imports| RedisModule
|
||||
HealthModule_HealthService -.->|injects| DatabaseModule_DatabaseClient
|
||||
HealthModule_HealthService -.->|injects| RedisModule_RedisClient
|
||||
HealthModule_HealthService -.->|injects| ConfigModule_ConfigService
|
||||
HealthModule_HealthController -.->|injects| HealthModule_HealthService
|
||||
ChatsModule -->|imports| UsersModule
|
||||
ChatsModule -->|imports| DatabaseModule
|
||||
ChatsModule -->|imports| RedisModule
|
||||
ChatsModule -->|imports| MetricsModule
|
||||
ChatsModule_ChatsRepository -.->|injects| DatabaseModule_DatabaseClient
|
||||
ChatsModule_ChatsService -.->|injects| ChatsModule_ChatsRepository
|
||||
ChatsModule_ChatsController -.->|injects| ChatsModule_ChatsService
|
||||
MessagesModule -->|imports| ChatsModule
|
||||
MessagesModule -->|imports| MessagesCacheModule
|
||||
MessagesModule -->|imports| DatabaseModule
|
||||
MessagesModule -->|imports| UsersModule
|
||||
MessagesModule -->|imports| RedisModule
|
||||
MessagesModule -->|imports| MetricsModule
|
||||
MessagesModule_MessagesRepository -.->|injects| DatabaseModule_DatabaseClient
|
||||
MessagesModule_MessagesService -.->|injects| MessagesModule_MessagesRepository
|
||||
MessagesModule_MessagesService -.->|injects| ChatsModule_ChatsService
|
||||
MessagesModule_MessagesService -.->|injects| MessagesCacheModule_MessagesCacheService
|
||||
MessagesModule_MessagesController -.->|injects| MessagesModule_MessagesService
|
||||
MessagesCacheModule -->|imports| RedisModule
|
||||
MessagesCacheModule -->|imports| MetricsModule
|
||||
MessagesCacheModule_MessagesCacheService -.->|injects| RedisModule_RedisClient
|
||||
MessagesCacheModule_MessagesCacheService -.->|injects| ConfigModule_ConfigService
|
||||
MessagesCacheModule_MessagesCacheService -.->|injects| MetricsModule_MetricsService
|
||||
```
|
||||
|
||||
## Module details
|
||||
|
||||
### AppModule
|
||||
|
||||
- Imports: AppConfigModule, DatabaseModule, RedisModule, UsersModule, AuthModule, HealthModule, ChatsModule, MessagesModule, MetricsModule
|
||||
- Exports: none
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
| provider | APP_FILTER | HttpAdapterHost |
|
||||
|
||||
### AppConfigModule
|
||||
|
||||
- Imports: ConfigModule
|
||||
- Exports: ConfigModule (module)
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
|
||||
### ConfigModule
|
||||
|
||||
- Imports: none
|
||||
- Exports: ConfigService (provider)
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
| provider | ConfigService | Symbol(CONFIG_SERVICE) |
|
||||
| provider | VALIDATED_ENV_LOADER | CONFIGURATION_TOKEN |
|
||||
|
||||
### DatabaseModule
|
||||
|
||||
- Imports: MetricsModule
|
||||
- Exports: DatabaseClient (provider)
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
| provider | DatabaseClient | ConfigService, MetricsService |
|
||||
|
||||
### MetricsModule
|
||||
|
||||
- Imports: none
|
||||
- Exports: MetricsService (provider)
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
| provider | MetricsService | none |
|
||||
| controller | MetricsController | ConfigService, MetricsService |
|
||||
|
||||
### RedisModule
|
||||
|
||||
- Imports: MetricsModule
|
||||
- Exports: RedisClient (provider)
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
| provider | RedisClient | ConfigService, MetricsService |
|
||||
|
||||
### UsersModule
|
||||
|
||||
- Imports: DatabaseModule, RedisModule, MetricsModule
|
||||
- Exports: UsersService (provider), CurrentUserGuard (provider), RedisModule (module), MetricsModule (module)
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
| provider | UsersRepository | DatabaseClient |
|
||||
| provider | UsersService | UsersRepository |
|
||||
| provider | CurrentUserGuard | RedisClient, UsersService, MetricsService |
|
||||
| controller | UsersController | UsersService |
|
||||
|
||||
### AuthModule
|
||||
|
||||
- Imports: UsersModule, DatabaseModule, RedisModule, MetricsModule
|
||||
- Exports: AuthService (provider), SessionRepository (provider)
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
| provider | AuthService | UsersService, SessionRepository |
|
||||
| provider | SessionRepository | RedisClient, ConfigService, MetricsService |
|
||||
| controller | AuthController | AuthService |
|
||||
|
||||
### HealthModule
|
||||
|
||||
- Imports: DatabaseModule, RedisModule
|
||||
- Exports: none
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
| provider | HealthService | DatabaseClient, RedisClient, ConfigService |
|
||||
| controller | HealthController | HealthService |
|
||||
|
||||
### ChatsModule
|
||||
|
||||
- Imports: UsersModule, DatabaseModule, RedisModule, MetricsModule
|
||||
- Exports: ChatsService (provider)
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
| provider | ChatsRepository | DatabaseClient |
|
||||
| provider | ChatsService | ChatsRepository |
|
||||
| controller | ChatsController | ChatsService |
|
||||
|
||||
### MessagesModule
|
||||
|
||||
- Imports: ChatsModule, MessagesCacheModule, DatabaseModule, UsersModule, RedisModule, MetricsModule
|
||||
- Exports: none
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
| provider | MessagesRepository | DatabaseClient |
|
||||
| provider | MessagesService | MessagesRepository, ChatsService, MessagesCacheService |
|
||||
| controller | MessagesController | MessagesService |
|
||||
|
||||
### MessagesCacheModule
|
||||
|
||||
- Imports: RedisModule, MetricsModule
|
||||
- Exports: MessagesCacheService (provider)
|
||||
|
||||
| Kind | Name | Dependencies |
|
||||
| --- | --- | --- |
|
||||
| provider | MessagesCacheService | RedisClient, ConfigService, MetricsService |
|
||||
@@ -0,0 +1,374 @@
|
||||
[
|
||||
{
|
||||
"name": "AppModule",
|
||||
"imports": [
|
||||
"AppConfigModule",
|
||||
"DatabaseModule",
|
||||
"RedisModule",
|
||||
"UsersModule",
|
||||
"AuthModule",
|
||||
"HealthModule",
|
||||
"ChatsModule",
|
||||
"MessagesModule",
|
||||
"MetricsModule"
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "APP_FILTER",
|
||||
"dependencies": [
|
||||
"HttpAdapterHost"
|
||||
],
|
||||
"type": "class"
|
||||
}
|
||||
],
|
||||
"controllers": [],
|
||||
"exports": []
|
||||
},
|
||||
{
|
||||
"name": "AppConfigModule",
|
||||
"imports": [
|
||||
"ConfigModule"
|
||||
],
|
||||
"providers": [],
|
||||
"controllers": [],
|
||||
"exports": [
|
||||
{
|
||||
"name": "ConfigModule",
|
||||
"type": "module"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "ConfigModule",
|
||||
"imports": [],
|
||||
"providers": [
|
||||
{
|
||||
"name": "ConfigService",
|
||||
"dependencies": [
|
||||
"Symbol(CONFIG_SERVICE)"
|
||||
],
|
||||
"type": "factory"
|
||||
},
|
||||
{
|
||||
"name": "VALIDATED_ENV_LOADER",
|
||||
"dependencies": [
|
||||
"CONFIGURATION_TOKEN"
|
||||
],
|
||||
"type": "factory"
|
||||
}
|
||||
],
|
||||
"controllers": [],
|
||||
"exports": [
|
||||
{
|
||||
"name": "ConfigService",
|
||||
"type": "provider"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "DatabaseModule",
|
||||
"imports": [
|
||||
"MetricsModule"
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "DatabaseClient",
|
||||
"dependencies": [
|
||||
"ConfigService",
|
||||
"MetricsService"
|
||||
],
|
||||
"type": "class"
|
||||
}
|
||||
],
|
||||
"controllers": [],
|
||||
"exports": [
|
||||
{
|
||||
"name": "DatabaseClient",
|
||||
"type": "provider"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "MetricsModule",
|
||||
"imports": [],
|
||||
"providers": [
|
||||
{
|
||||
"name": "MetricsService",
|
||||
"dependencies": [],
|
||||
"type": "class"
|
||||
}
|
||||
],
|
||||
"controllers": [
|
||||
{
|
||||
"name": "MetricsController",
|
||||
"dependencies": [
|
||||
"ConfigService",
|
||||
"MetricsService"
|
||||
]
|
||||
}
|
||||
],
|
||||
"exports": [
|
||||
{
|
||||
"name": "MetricsService",
|
||||
"type": "provider"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "RedisModule",
|
||||
"imports": [
|
||||
"MetricsModule"
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "RedisClient",
|
||||
"dependencies": [
|
||||
"ConfigService",
|
||||
"MetricsService"
|
||||
],
|
||||
"type": "class"
|
||||
}
|
||||
],
|
||||
"controllers": [],
|
||||
"exports": [
|
||||
{
|
||||
"name": "RedisClient",
|
||||
"type": "provider"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "UsersModule",
|
||||
"imports": [
|
||||
"DatabaseModule",
|
||||
"RedisModule",
|
||||
"MetricsModule"
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "UsersRepository",
|
||||
"dependencies": [
|
||||
"DatabaseClient"
|
||||
],
|
||||
"type": "class"
|
||||
},
|
||||
{
|
||||
"name": "UsersService",
|
||||
"dependencies": [
|
||||
"UsersRepository"
|
||||
],
|
||||
"type": "class"
|
||||
},
|
||||
{
|
||||
"name": "CurrentUserGuard",
|
||||
"dependencies": [
|
||||
"RedisClient",
|
||||
"UsersService",
|
||||
"MetricsService"
|
||||
],
|
||||
"type": "class"
|
||||
}
|
||||
],
|
||||
"controllers": [
|
||||
{
|
||||
"name": "UsersController",
|
||||
"dependencies": [
|
||||
"UsersService"
|
||||
]
|
||||
}
|
||||
],
|
||||
"exports": [
|
||||
{
|
||||
"name": "UsersService",
|
||||
"type": "provider"
|
||||
},
|
||||
{
|
||||
"name": "CurrentUserGuard",
|
||||
"type": "provider"
|
||||
},
|
||||
{
|
||||
"name": "RedisModule",
|
||||
"type": "module"
|
||||
},
|
||||
{
|
||||
"name": "MetricsModule",
|
||||
"type": "module"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "AuthModule",
|
||||
"imports": [
|
||||
"UsersModule",
|
||||
"DatabaseModule",
|
||||
"RedisModule",
|
||||
"MetricsModule"
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "AuthService",
|
||||
"dependencies": [
|
||||
"UsersService",
|
||||
"SessionRepository"
|
||||
],
|
||||
"type": "class"
|
||||
},
|
||||
{
|
||||
"name": "SessionRepository",
|
||||
"dependencies": [
|
||||
"RedisClient",
|
||||
"ConfigService",
|
||||
"MetricsService"
|
||||
],
|
||||
"type": "class"
|
||||
}
|
||||
],
|
||||
"controllers": [
|
||||
{
|
||||
"name": "AuthController",
|
||||
"dependencies": [
|
||||
"AuthService"
|
||||
]
|
||||
}
|
||||
],
|
||||
"exports": [
|
||||
{
|
||||
"name": "AuthService",
|
||||
"type": "provider"
|
||||
},
|
||||
{
|
||||
"name": "SessionRepository",
|
||||
"type": "provider"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "HealthModule",
|
||||
"imports": [
|
||||
"DatabaseModule",
|
||||
"RedisModule"
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "HealthService",
|
||||
"dependencies": [
|
||||
"DatabaseClient",
|
||||
"RedisClient",
|
||||
"ConfigService"
|
||||
],
|
||||
"type": "class"
|
||||
}
|
||||
],
|
||||
"controllers": [
|
||||
{
|
||||
"name": "HealthController",
|
||||
"dependencies": [
|
||||
"HealthService"
|
||||
]
|
||||
}
|
||||
],
|
||||
"exports": []
|
||||
},
|
||||
{
|
||||
"name": "ChatsModule",
|
||||
"imports": [
|
||||
"UsersModule",
|
||||
"DatabaseModule",
|
||||
"RedisModule",
|
||||
"MetricsModule"
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "ChatsRepository",
|
||||
"dependencies": [
|
||||
"DatabaseClient"
|
||||
],
|
||||
"type": "class"
|
||||
},
|
||||
{
|
||||
"name": "ChatsService",
|
||||
"dependencies": [
|
||||
"ChatsRepository"
|
||||
],
|
||||
"type": "class"
|
||||
}
|
||||
],
|
||||
"controllers": [
|
||||
{
|
||||
"name": "ChatsController",
|
||||
"dependencies": [
|
||||
"ChatsService"
|
||||
]
|
||||
}
|
||||
],
|
||||
"exports": [
|
||||
{
|
||||
"name": "ChatsService",
|
||||
"type": "provider"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "MessagesModule",
|
||||
"imports": [
|
||||
"ChatsModule",
|
||||
"MessagesCacheModule",
|
||||
"DatabaseModule",
|
||||
"UsersModule",
|
||||
"RedisModule",
|
||||
"MetricsModule"
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "MessagesRepository",
|
||||
"dependencies": [
|
||||
"DatabaseClient"
|
||||
],
|
||||
"type": "class"
|
||||
},
|
||||
{
|
||||
"name": "MessagesService",
|
||||
"dependencies": [
|
||||
"MessagesRepository",
|
||||
"ChatsService",
|
||||
"MessagesCacheService"
|
||||
],
|
||||
"type": "class"
|
||||
}
|
||||
],
|
||||
"controllers": [
|
||||
{
|
||||
"name": "MessagesController",
|
||||
"dependencies": [
|
||||
"MessagesService"
|
||||
]
|
||||
}
|
||||
],
|
||||
"exports": []
|
||||
},
|
||||
{
|
||||
"name": "MessagesCacheModule",
|
||||
"imports": [
|
||||
"RedisModule",
|
||||
"MetricsModule"
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "MessagesCacheService",
|
||||
"dependencies": [
|
||||
"RedisClient",
|
||||
"ConfigService",
|
||||
"MetricsService"
|
||||
],
|
||||
"type": "class"
|
||||
}
|
||||
],
|
||||
"controllers": [],
|
||||
"exports": [
|
||||
{
|
||||
"name": "MessagesCacheService",
|
||||
"type": "provider"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,116 @@
|
||||
flowchart LR
|
||||
%% Generated by scripts/graph-modules.ts
|
||||
%% Solid arrows: module imports; dotted arrows: constructor dependencies
|
||||
subgraph AppModule["AppModule"]
|
||||
AppModule_APP_FILTER["provider: APP_FILTER"]
|
||||
end
|
||||
subgraph AppConfigModule["AppConfigModule"]
|
||||
end
|
||||
subgraph ConfigModule["ConfigModule"]
|
||||
ConfigModule_ConfigService["provider: ConfigService"]
|
||||
ConfigModule_VALIDATED_ENV_LOADER["provider: VALIDATED_ENV_LOADER"]
|
||||
end
|
||||
subgraph DatabaseModule["DatabaseModule"]
|
||||
DatabaseModule_DatabaseClient["provider: DatabaseClient"]
|
||||
end
|
||||
subgraph MetricsModule["MetricsModule"]
|
||||
MetricsModule_MetricsService["provider: MetricsService"]
|
||||
MetricsModule_MetricsController["controller: MetricsController"]
|
||||
end
|
||||
subgraph RedisModule["RedisModule"]
|
||||
RedisModule_RedisClient["provider: RedisClient"]
|
||||
end
|
||||
subgraph UsersModule["UsersModule"]
|
||||
UsersModule_UsersRepository["provider: UsersRepository"]
|
||||
UsersModule_UsersService["provider: UsersService"]
|
||||
UsersModule_CurrentUserGuard["provider: CurrentUserGuard"]
|
||||
UsersModule_UsersController["controller: UsersController"]
|
||||
end
|
||||
subgraph AuthModule["AuthModule"]
|
||||
AuthModule_AuthService["provider: AuthService"]
|
||||
AuthModule_SessionRepository["provider: SessionRepository"]
|
||||
AuthModule_AuthController["controller: AuthController"]
|
||||
end
|
||||
subgraph HealthModule["HealthModule"]
|
||||
HealthModule_HealthService["provider: HealthService"]
|
||||
HealthModule_HealthController["controller: HealthController"]
|
||||
end
|
||||
subgraph ChatsModule["ChatsModule"]
|
||||
ChatsModule_ChatsRepository["provider: ChatsRepository"]
|
||||
ChatsModule_ChatsService["provider: ChatsService"]
|
||||
ChatsModule_ChatsController["controller: ChatsController"]
|
||||
end
|
||||
subgraph MessagesModule["MessagesModule"]
|
||||
MessagesModule_MessagesRepository["provider: MessagesRepository"]
|
||||
MessagesModule_MessagesService["provider: MessagesService"]
|
||||
MessagesModule_MessagesController["controller: MessagesController"]
|
||||
end
|
||||
subgraph MessagesCacheModule["MessagesCacheModule"]
|
||||
MessagesCacheModule_MessagesCacheService["provider: MessagesCacheService"]
|
||||
end
|
||||
AppModule -->|imports| AppConfigModule
|
||||
AppModule -->|imports| DatabaseModule
|
||||
AppModule -->|imports| RedisModule
|
||||
AppModule -->|imports| UsersModule
|
||||
AppModule -->|imports| AuthModule
|
||||
AppModule -->|imports| HealthModule
|
||||
AppModule -->|imports| ChatsModule
|
||||
AppModule -->|imports| MessagesModule
|
||||
AppModule -->|imports| MetricsModule
|
||||
AppConfigModule -->|imports| ConfigModule
|
||||
DatabaseModule -->|imports| MetricsModule
|
||||
DatabaseModule_DatabaseClient -.->|injects| ConfigModule_ConfigService
|
||||
DatabaseModule_DatabaseClient -.->|injects| MetricsModule_MetricsService
|
||||
MetricsModule_MetricsController -.->|injects| ConfigModule_ConfigService
|
||||
MetricsModule_MetricsController -.->|injects| MetricsModule_MetricsService
|
||||
RedisModule -->|imports| MetricsModule
|
||||
RedisModule_RedisClient -.->|injects| ConfigModule_ConfigService
|
||||
RedisModule_RedisClient -.->|injects| MetricsModule_MetricsService
|
||||
UsersModule -->|imports| DatabaseModule
|
||||
UsersModule -->|imports| RedisModule
|
||||
UsersModule -->|imports| MetricsModule
|
||||
UsersModule_UsersRepository -.->|injects| DatabaseModule_DatabaseClient
|
||||
UsersModule_UsersService -.->|injects| UsersModule_UsersRepository
|
||||
UsersModule_CurrentUserGuard -.->|injects| RedisModule_RedisClient
|
||||
UsersModule_CurrentUserGuard -.->|injects| UsersModule_UsersService
|
||||
UsersModule_CurrentUserGuard -.->|injects| MetricsModule_MetricsService
|
||||
UsersModule_UsersController -.->|injects| UsersModule_UsersService
|
||||
AuthModule -->|imports| UsersModule
|
||||
AuthModule -->|imports| DatabaseModule
|
||||
AuthModule -->|imports| RedisModule
|
||||
AuthModule -->|imports| MetricsModule
|
||||
AuthModule_AuthService -.->|injects| UsersModule_UsersService
|
||||
AuthModule_AuthService -.->|injects| AuthModule_SessionRepository
|
||||
AuthModule_SessionRepository -.->|injects| RedisModule_RedisClient
|
||||
AuthModule_SessionRepository -.->|injects| ConfigModule_ConfigService
|
||||
AuthModule_SessionRepository -.->|injects| MetricsModule_MetricsService
|
||||
AuthModule_AuthController -.->|injects| AuthModule_AuthService
|
||||
HealthModule -->|imports| DatabaseModule
|
||||
HealthModule -->|imports| RedisModule
|
||||
HealthModule_HealthService -.->|injects| DatabaseModule_DatabaseClient
|
||||
HealthModule_HealthService -.->|injects| RedisModule_RedisClient
|
||||
HealthModule_HealthService -.->|injects| ConfigModule_ConfigService
|
||||
HealthModule_HealthController -.->|injects| HealthModule_HealthService
|
||||
ChatsModule -->|imports| UsersModule
|
||||
ChatsModule -->|imports| DatabaseModule
|
||||
ChatsModule -->|imports| RedisModule
|
||||
ChatsModule -->|imports| MetricsModule
|
||||
ChatsModule_ChatsRepository -.->|injects| DatabaseModule_DatabaseClient
|
||||
ChatsModule_ChatsService -.->|injects| ChatsModule_ChatsRepository
|
||||
ChatsModule_ChatsController -.->|injects| ChatsModule_ChatsService
|
||||
MessagesModule -->|imports| ChatsModule
|
||||
MessagesModule -->|imports| MessagesCacheModule
|
||||
MessagesModule -->|imports| DatabaseModule
|
||||
MessagesModule -->|imports| UsersModule
|
||||
MessagesModule -->|imports| RedisModule
|
||||
MessagesModule -->|imports| MetricsModule
|
||||
MessagesModule_MessagesRepository -.->|injects| DatabaseModule_DatabaseClient
|
||||
MessagesModule_MessagesService -.->|injects| MessagesModule_MessagesRepository
|
||||
MessagesModule_MessagesService -.->|injects| ChatsModule_ChatsService
|
||||
MessagesModule_MessagesService -.->|injects| MessagesCacheModule_MessagesCacheService
|
||||
MessagesModule_MessagesController -.->|injects| MessagesModule_MessagesService
|
||||
MessagesCacheModule -->|imports| RedisModule
|
||||
MessagesCacheModule -->|imports| MetricsModule
|
||||
MessagesCacheModule_MessagesCacheService -.->|injects| RedisModule_RedisClient
|
||||
MessagesCacheModule_MessagesCacheService -.->|injects| ConfigModule_ConfigService
|
||||
MessagesCacheModule_MessagesCacheService -.->|injects| MetricsModule_MetricsService
|
||||
+54
-3
@@ -1,5 +1,56 @@
|
||||
# Доказательства
|
||||
# Индекс доказательств
|
||||
|
||||
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
|
||||
Санитизированные доказательства по лабораторной 2 (трек 1, оценка 5).
|
||||
|
||||
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
|
||||
| Файл | Что доказывает |
|
||||
| ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| [`track1-cache-consistency.md`](track1-cache-consistency.md) | Трек 1: окружение, методика, счётчики и латентность по каждой повторности для naive и protected, сравнение, read-after-write, восстановление после рестарта Redis, план запроса, хеши артефактов, ограничения. |
|
||||
| [`level3-4-verification.md`](level3-4-verification.md) | Проверки уровня 3/4 с наблюдаемым выводом команд: контракт, сборка и тесты, миграции, публичный smoke, persistence-перезапуск, чёрно-белый интеграционный набор, истечение TTL, гонка username, rollback, отказы зависимостей, `EXPLAIN`, endpoint метрик, а также дефекты, найденные этим аудитом. |
|
||||
| [`track1-explain.md`](track1-explain.md) | Тексты анализируемых SQL-запросов, подготовка 10 000 синтетических строк и сырой `EXPLAIN (ANALYZE, BUFFERS)`: `Index Scan using messages_chat_created_id_idx` для первой страницы и для продолжения по keyset-cursor. |
|
||||
| [`../bruno/README.md`](../bruno/README.md) | Коллекция ручных запросов Bruno ко всем эндпоинтам (28 запросов / 56 проверок, все зелёные) — удобно для разбора API вручную. |
|
||||
| `track1-raw/naive.json` (в Git не попадает) | Сырой вывод бенчмарка для `CACHE_MODE=naive`. |
|
||||
| `track1-raw/protected.json` (в Git не попадает) | Сырой вывод бенчмарка для `CACHE_MODE=protected`. |
|
||||
| `track1-raw/redis-restart.json` (в Git не попадает) | Сырой вывод проверки рестарта Redis. |
|
||||
|
||||
## Полная регенерация
|
||||
|
||||
```sh
|
||||
# 1. Стенд
|
||||
cp .env.example .env
|
||||
password=$(openssl rand -hex 32)
|
||||
sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$password/" .env
|
||||
sed -i "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://messenger:$password@postgres:5432/messenger|" .env
|
||||
sed -i "s/^METRICS_TOKEN=.*/METRICS_TOKEN=$(openssl rand -hex 16)/" .env
|
||||
docker compose --env-file .env up -d --build
|
||||
curl -fsS http://localhost:8080/health/ready
|
||||
|
||||
# 2. Приёмка и сохранность
|
||||
make check && make validate
|
||||
make test BASE_URL=http://localhost:8080
|
||||
chmod +x scripts/restart.sh
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
|
||||
# 3. Тесты приложения
|
||||
(cd app && npm run build && npm test && npx tsc --noEmit)
|
||||
|
||||
# 4. Интеграционный набор (реальные PostgreSQL/Redis; порты наружу не публикуются)
|
||||
docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' mtusi2026lab2-postgres-1 mtusi2026lab2-redis-1
|
||||
(cd app && API_BASE_URL=http://localhost:8080 \
|
||||
DATABASE_URL=postgresql://messenger:$password@<pg-ip>:5432/messenger \
|
||||
REDIS_URL=redis://<redis-ip>:6379 npx vitest run --config ./vitest.config.e2e.ts)
|
||||
|
||||
# 5. Трек 1
|
||||
printf '%s' "$METRICS_TOKEN" > /tmp/track1-metrics-token # METRICS_TOKEN из .env
|
||||
CACHE_MODE=naive CACHE_MISS_DELAY_MS=75 docker compose --env-file .env up -d api
|
||||
python3 scripts/track1_cache_benchmark.py --base-url http://localhost:8080 --mode naive \
|
||||
--concurrency 32 --repetitions 5 --metrics-token-file /tmp/track1-metrics-token \
|
||||
--output evidence/track1-raw/naive.json
|
||||
CACHE_MODE=protected docker compose --env-file .env up -d api
|
||||
python3 scripts/track1_cache_benchmark.py --base-url http://localhost:8080 --mode protected \
|
||||
--concurrency 32 --repetitions 5 --metrics-token-file /tmp/track1-metrics-token \
|
||||
--output evidence/track1-raw/protected.json
|
||||
python3 scripts/track1_verify.py --restart-redis --evict-cache \
|
||||
--output evidence/track1-raw/redis-restart.json
|
||||
```
|
||||
|
||||
Точки входа для ревьюера: `README.md` (задание), `REPORT.md` (решение), этот индекс. Публичные `contracts/` и `tests/` не изменялись.
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
# Журнал проверок уровня 3/4
|
||||
|
||||
Индекс всех доказательств — [`README.md`](README.md); сводка решения — [`../REPORT.md`](../REPORT.md); методика и числа трека 1 — [`track1-cache-consistency.md`](track1-cache-consistency.md).
|
||||
|
||||
Запись по командам, на которых основано заявление об оценке 5 (уровень 4 плюс трек 1). Все пункты выполнены на локальном Compose-стенде; значения ниже скопированы из наблюдавшегося вывода, а не выведены из кода.
|
||||
|
||||
Окружение: Node 25.7.0 (`node:25.7.0-slim`), `postgres:16.4-alpine`, `redis:7.4.2-alpine`, Python 3.14.7, Linux x86_64. Тома `postgres-data` и `redis-data` между проверками сохраняются.
|
||||
|
||||
## 1. Структура репозитория и контракт
|
||||
|
||||
```text
|
||||
$ make check
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
|
||||
$ make validate
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
```
|
||||
|
||||
## 2. Сборка приложения и unit-тесты
|
||||
|
||||
```text
|
||||
$ (cd app && npm run build)
|
||||
nest build -> PASS
|
||||
|
||||
$ (cd app && npm test)
|
||||
Test Files 5 passed (5)
|
||||
Tests 13 passed (13)
|
||||
|
||||
$ (cd app && npx tsc --noEmit)
|
||||
PASS (диагностик нет)
|
||||
```
|
||||
|
||||
Что покрыто unit-тестами: снапшот метрик/процентили/ограничение буфера, изоляция страниц кэша, cursor-scope lock, деградация кэша при недоступности Redis, дельты счётчиков.
|
||||
|
||||
## 3. Compose-стенд и миграции
|
||||
|
||||
```text
|
||||
$ docker compose --env-file .env config --quiet
|
||||
PASS
|
||||
|
||||
$ docker compose --env-file .env up -d --build
|
||||
postgres Up (healthy)
|
||||
redis Up (healthy)
|
||||
migrate Exited (0)
|
||||
api Up (healthy)
|
||||
|
||||
$ curl -fsS http://localhost:8080/health/ready
|
||||
{"status":"ok"}
|
||||
|
||||
$ docker compose exec -T postgres psql -U messenger -d messenger -c 'SELECT version FROM schema_migrations ORDER BY version;'
|
||||
001_initial.sql
|
||||
002_timestamp_precision.sql
|
||||
```
|
||||
|
||||
Повторные `up`/`restart` снова запускают сервис миграций, но без дублирования данных и без сидов: применённые версии записаны в `schema_migrations` и пропускаются, а сам SQL миграций идемпотентен (`CREATE TABLE IF NOT EXISTS`, `ALTER COLUMN TYPE`).
|
||||
|
||||
## 4. Публичный приёмочный сценарий
|
||||
|
||||
```text
|
||||
$ make test BASE_URL=http://localhost:8080
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
```
|
||||
|
||||
Сценарий покрывает health, регистрацию с паролем, Basic-вход, Bearer-идентичность, видимость чатов, пагинацию сообщений, 401 без сессии, 401 для Basic на бизнес-endpoint, отсутствие подмены владельца через `X-User-Id`, а также logout и повторное использование токена.
|
||||
|
||||
## 5. Сохранность после полного перезапуска
|
||||
|
||||
```text
|
||||
$ chmod +x scripts/restart.sh
|
||||
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
```
|
||||
|
||||
Хук — это `docker compose --env-file .env restart postgres redis api` и затем `up -d --no-recreate --no-deps --wait`; он не удаляет тома, не выполняет сиды и не вызывает `FLUSHALL`. Тест держит токен только в памяти и после перезапуска читает им то же сообщение.
|
||||
|
||||
## 6. Чёрно-белый интеграционный набор против реальных PostgreSQL и Redis
|
||||
|
||||
```text
|
||||
$ (cd app && API_BASE_URL=http://localhost:8080 \
|
||||
DATABASE_URL=postgresql://messenger:<password>@<pg-container>:5432/messenger \
|
||||
REDIS_URL=redis://<redis-container>:6379 \
|
||||
npx vitest run --config ./vitest.config.e2e.ts)
|
||||
Test Files 1 passed (1)
|
||||
Tests 7 passed | 1 skipped (8)
|
||||
```
|
||||
|
||||
Покрыто: challenge для Basic/Bearer с точными значениями `WWW-Authenticate`, некорректный Basic, запрет тела при создании сессии, пароль с Unicode и двоеточием, гонка дублирующейся регистрации, подмена `X-User-Id`, повторное использование токена после logout, чужой чат скрыт (404), неизвестные и дублирующиеся участники, пробельный текст и подмена отправителя, read-after-write через вторую сессию, сломанный JSON, некорректные cursor/limit, keyset-пагинация без повторов.
|
||||
|
||||
Набор читает `API_BASE_URL`, потому что Vitest сам устанавливает `process.env.BASE_URL` в значение Vite base (`/`). Порты PostgreSQL и Redis наружу не публикуются, поэтому оператор передаёт адреса контейнеров.
|
||||
|
||||
## 7. Истечение сессии при коротком TTL
|
||||
|
||||
```text
|
||||
$ sed -i 's/^SESSION_TTL_SECONDS=.*/SESSION_TTL_SECONDS=2/' .env
|
||||
$ docker compose up -d api
|
||||
$ (cd app && API_BASE_URL=http://localhost:8080 ... SESSION_TTL_SECONDS=2 npx vitest run --config ./vitest.config.e2e.ts)
|
||||
Test Files 1 passed (1)
|
||||
Tests 8 passed (8)
|
||||
```
|
||||
|
||||
Кейс истечения: регистрация, вход, ожидание 2,3 с, ожидание `401 unauthorized` с Bearer-challenge. Работают и TTL Redis, и сериализованный `expires_at`. После проверки TTL возвращён в 3600.
|
||||
|
||||
## 8. Гонка одинакового username
|
||||
|
||||
```text
|
||||
statuses: [201, 409]
|
||||
rows in users for that username: 1
|
||||
constraint: CREATE UNIQUE INDEX users_username_key ON public.users USING btree (username)
|
||||
```
|
||||
|
||||
Два одновременных `POST /api/v1/users` с одинаковым username: ровно один `201`, проигравший получает `409` (ошибка PostgreSQL `23505` маппится в `ConflictException`), а не `500`. Уникальность обеспечивает unique-индекс базы, а не предварительный `SELECT`, который был бы подвержен гонке. Интеграционный тест дополнительно проверяет, что в таблице ровно одна строка.
|
||||
|
||||
## 9. Атомарность создания чата (rollback)
|
||||
|
||||
```text
|
||||
chat with unknown member -> 400
|
||||
rows left after rollback -> 0
|
||||
```
|
||||
|
||||
`POST /api/v1/chats` с неизвестным участником падает на валидации внутри транзакции: ни строки в `chats`, ни строк в `chat_members` не остаётся.
|
||||
|
||||
## 10. Отказы зависимостей
|
||||
|
||||
Остановлен Redis (`docker compose stop redis`):
|
||||
|
||||
```text
|
||||
/health/ready -> 503
|
||||
GET /users/me (валидный токен) -> 503 # анонимный доступ не выдаётся
|
||||
после `docker compose start redis` -> /health/ready 200
|
||||
```
|
||||
|
||||
Остановлен PostgreSQL (`docker compose stop postgres`):
|
||||
|
||||
```text
|
||||
/health/ready -> 503
|
||||
GET /users/me (валидный токен) -> 503
|
||||
состояние процесса -> контейнер api остался Up (падения нет)
|
||||
после `docker compose start postgres` -> /health/ready 200, тот же токен -> 200
|
||||
```
|
||||
|
||||
Здесь найден и исправлен реальный дефект: idle-клиент пула эмитил `error` на пул, Node считал это необработанным исключением, и процесс API завершался. Теперь `DatabaseClient` регистрирует `pool.on('error')` (счётчик `database.pool_error` + `warn` в лог), а ошибки доступности БД маппятся в ограниченную `503` в `ApiExceptionFilter` вместо `500`.
|
||||
|
||||
Путь деградации кэша (Redis недоступен → ответ из PostgreSQL, счётчик `cache_fallback`) подтверждён unit-тестами, а не этим экспериментом: при остановленном Redis бизнес-запрос останавливается раньше, на session guard, и по дизайну получает `503`, поэтому до слоя кэша не доходит.
|
||||
|
||||
## 11. План запроса истории
|
||||
|
||||
```text
|
||||
$ docker compose exec -T postgres psql -U messenger -d messenger -f - < /tmp/track1-explain.sql
|
||||
=== Запрос A: первая страница истории ===
|
||||
Limit (cost=0.28..112.30 rows=51 width=77) (actual time=0.020..0.028 rows=51 loops=1)
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (actual rows=51)
|
||||
Execution Time: 0.040 ms
|
||||
=== Запрос B: продолжение по keyset-cursor ===
|
||||
Limit (cost=0.28..8.30 rows=1 width=77) (actual time=0.008..0.014 rows=51 loops=1)
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (actual rows=51)
|
||||
Index Cond: ((chat_id = ...) AND (ROW(created_at, id) > ROW(...)))
|
||||
Execution Time: 0.048 ms
|
||||
```
|
||||
|
||||
Для снятия планов в один чат вставлено 10 000 синтетических сообщений, после захвата они удалены (`DELETE 10000`). Полный файл с текстом анализируемых запросов и подготовкой данных: `evidence/track1-explain.md`.
|
||||
|
||||
## 12. Endpoint метрик
|
||||
|
||||
```text
|
||||
$ curl -H "Authorization: Bearer $METRICS_TOKEN" http://localhost:8080/internal/metrics
|
||||
observed counters: cache_miss, chats.findForUser, chats.listForUser, health.database,
|
||||
messages.history, messages.version, redis.del, redis.get, redis.ping, redis.set,
|
||||
redis.unlock, request_count, session_del, session_get, session_set,
|
||||
users.findById, users.findByUsername, users.insert
|
||||
latency: {count: 25, sample_count: 25, p50: 2.82, p95: 50.71, p99: 52.74, max: 52.74}
|
||||
```
|
||||
|
||||
Без корректного `METRICS_TOKEN` endpoint отдаёт `401`; в ответе нет токенов, кредов, тел запросов и SQL-текста.
|
||||
|
||||
Тот же путь проверен ручным клиентом Bruno (`bruno/README.md`): из корня коллекции
|
||||
`bru run -r --env-var metricsToken=<METRICS_TOKEN>` дал 28 запросов и
|
||||
56 проверок без падений (регистрация трёх пользователей, три Basic-сессии, чат,
|
||||
сообщения с пагинацией, метрики и негативные сценарии). `baseUrl` и пароль
|
||||
подставляются на уровне коллекции (`bruno/collection.bru`), поэтому вводить адрес
|
||||
в каждой ручке не требуется; без реального токена метрик два запроса к
|
||||
`/internal/*` возвращают 401 — это ожидаемо. Прогон вскрыл расхождение:
|
||||
`POST /internal/metrics/reset` отвечал `201` (дефолт Nest для POST), хотя это действие,
|
||||
а не создание ресурса; добавлен `@HttpCode(HttpStatus.OK)`, теперь `200`.
|
||||
|
||||
## 13. Дефекты, найденные этим аудитом и исправленные
|
||||
|
||||
| Дефект | Симптом | Исправление |
|
||||
|---|---|---|
|
||||
| Отсутствовали DI-импорты зависимостей `CurrentUserGuard` | контейнер API `Exited (1)` с `UnknownDependenciesException` | `ChatsModule`/`MessagesModule` импортируют `RedisModule`, `MetricsModule`; `UsersModule` их реэкспортирует |
|
||||
| Микросекунды PostgreSQL против миллисекунд JavaScript | вторая страница истории повторяла последнее сообщение (`make test` падал) | миграция `002_timestamp_precision.sql` → `timestamptz(3)` |
|
||||
| Regex курсора требовал строго version 4 | валидные курсоры отклонялись как `400 invalid_request` | regex принимает любую корректную форму UUID плюс строгий RFC 3339 UTC timestamp |
|
||||
| Необработанное событие `error` пула | процесс API умирал при недоступности PostgreSQL | обработчик `pool.on('error')` (счётчик `database.pool_error` + `warn`), отказ маппится в `503` |
|
||||
| «Тихие» блоки `catch` | деградация кэша и зависимостей была невидима | счётчики (`cache_fallback`, `cache_write_error`, `cache_unlock_error`, `cache_lock_timeout`, `cache_corrupt_entry`, `database.pool_error`, `database.rollback_error`, `redis.error`) + `warn`-логи |
|
||||
| Мёртвое состояние `lastError`, `getLastError()`, `isReady()` | заполнялось и нигде не читалось | удалено; листенеры пишут лог и счётчик |
|
||||
| `POST /internal/metrics/reset` отвечал `201` | действие возвращало статус создания ресурса (нашлось прогоном коллекции Bruno) | добавлен `@HttpCode(HttpStatus.OK)`, теперь `200` |
|
||||
| `nest build` не копировал `.sql`-миграции в `dist/` | локальный запуск `node dist/database/migration.runner.js` упал бы: каталога миграций в `dist/` нет, работал только Docker за счёт отдельного `COPY` | в `nest-cli.json` добавлен `assets: database/migrations/*.sql → dist`, лишний `COPY` из `Dockerfile` убран; проверено `docker run --rm --entrypoint ls mtusi-messenger:lab2 dist/database/migrations` и повторным запуском runner (exit 0) |
|
||||
|
||||
## 14. Инвентарь артефактов
|
||||
|
||||
| Артефакт | Назначение |
|
||||
| ---------------------------------------- | --------------------------------------------------------- |
|
||||
| `evidence/track1-cache-consistency.md` | подробный отчёт по треку 1 с таблицами по повторностям |
|
||||
| `evidence/track1-raw/naive.json` | сырой прогон naive (в Git не попадает) |
|
||||
| `evidence/track1-raw/protected.json` | сырой прогон protected (в Git не попадает) |
|
||||
| `evidence/track1-raw/redis-restart.json` | сырая проверка рестарта Redis (в Git не попадает) |
|
||||
| `evidence/track1-explain.md` | запросы и `EXPLAIN (ANALYZE, BUFFERS)` |
|
||||
| `bruno/README.md` | коллекция ручных запросов (Bruno) ко всем эндпоинтам |
|
||||
| `REPORT.md` | основной отчёт: архитектура, решения, команды, результаты |
|
||||
|
||||
Хеши сырых артефактов перечислены в `evidence/track1-cache-consistency.md` §8.
|
||||
@@ -0,0 +1,181 @@
|
||||
# Трек 1: согласованность кэша (подробные доказательства)
|
||||
|
||||
Индекс всех доказательств — [`README.md`](README.md); сводка решения и критериев — [`../REPORT.md`](../REPORT.md); чек-лист сдачи — [`../.github/pull_request_template.md`](../.github/pull_request_template.md).
|
||||
|
||||
Санитизированные результаты локального Compose-стенда.
|
||||
|
||||
## 1. Окружение
|
||||
|
||||
| Параметр | Значение |
|
||||
| ----------------------------- | ------------------------------------------------------------------------------------ |
|
||||
| Хост | Linux x86_64, ядро 7.2.7-100.fc43 |
|
||||
| Python (клиент бенчмарка) | 3.14.7 |
|
||||
| Runtime API | Node.js 25.7.0 (`node:25.7.0-slim`), NestJS 12 + Fastify |
|
||||
| PostgreSQL | `postgres:16.4-alpine`, именованный том `postgres-data` |
|
||||
| Redis | `redis:7.4.2-alpine`, AOF `appendonly yes`, `appendfsync everysec`, том `redis-data` |
|
||||
| Задержка промаха | `CACHE_MISS_DELAY_MS=75` — действует **только в naive-пути** (пауза между промахом и запросом в PostgreSQL); protected-путь её не использует |
|
||||
| TTL кэша | `CACHE_TTL_SECONDS=30` |
|
||||
| TTL lock | `CACHE_LOCK_TTL_MS=1000` |
|
||||
| TTL сессии | `SESSION_TTL_SECONDS=3600` |
|
||||
|
||||
Оба режима измерялись на одном стенде и одной базе; переключался только `CACHE_MODE` (переменная окружения при пересоздании контейнера `api`), отдельного compose-профиля нет.
|
||||
|
||||
## 2. Методика
|
||||
|
||||
1. Два пользователя регистрируются со случайным паролем и логинятся через Basic (`track1_cache_benchmark.py`).
|
||||
2. Создаётся чат, содержащий оба ID; до измерений прогревается отдельная страница истории.
|
||||
3. Повторности: 5. Каждая повторность создаёт **новый чат** с 1 сообщением, поэтому измеряемый ключ холодный без `FLUSHALL` и без ручной эвикции кэша.
|
||||
4. `POST /internal/metrics/reset` обнуляет счётчики; `GET /internal/metrics` читается до и после всплеска.
|
||||
5. 32 конкурентных `GET /api/v1/chats/{id}/messages?limit=50` освобождаются `threading.Barrier`, то есть все читатели бьют в один холодный ключ одновременно.
|
||||
6. По каждой повторности фиксируются латентности успешных запросов и ошибки.
|
||||
7. В том же прогоне проверяется read-after-write: греется старая страница, публикуется новое сообщение, затем страница сразу перечитывается **второй действующей сессией**.
|
||||
|
||||
Примечание о воспроизводимости: записанные ниже прогоны запускались с overlay-файлом, который выставлял ровно две переменные контейнера `api` — `CACHE_MODE` и `CACHE_MISS_DELAY_MS=75`. Сейчас тот же результат даёт переопределение из shell без отдельного файла (команды в §9); поведение контейнера идентично.
|
||||
|
||||
Счётчики локальны процессу и сбрасываются перед каждой повторностью; дельты ниже не включают сам вызов сброса.
|
||||
|
||||
## 3. Результаты по повторностям
|
||||
|
||||
### naive (без блокировки, чистый cache-aside)
|
||||
|
||||
| Повтор | Успешных | Ошибок | `messages.history` | `cache_miss` | `cache_hit` | `cache_lock_wait` | p50, мс | p95, мс | p99, мс |
|
||||
| -----: | -------: | -----: | -----------------: | -----------: | ----------: | ----------------: | ------: | ------: | ------: |
|
||||
| 1 | 32 | 0 | 32 | 32 | 0 | 0 | 116.862 | 120.132 | 120.575 |
|
||||
| 2 | 32 | 0 | 32 | 32 | 0 | 0 | 89.730 | 98.924 | 99.283 |
|
||||
| 3 | 32 | 0 | 32 | 32 | 0 | 0 | 88.007 | 96.125 | 96.450 |
|
||||
| 4 | 32 | 0 | 32 | 32 | 0 | 0 | 89.418 | 96.318 | 96.781 |
|
||||
| 5 | 32 | 0 | 32 | 32 | 0 | 0 | 87.892 | 94.654 | 95.192 |
|
||||
| **Σ** | **160** | **0** | **160** | **160** | **0** | **0** | — | — | — |
|
||||
|
||||
Каждый холодный читатель промахивался и выполнял свой SQL-запрос истории: число запросов равно числу конкурентных читателей.
|
||||
|
||||
### protected (версионированный ключ + lock на конкретную страницу, NX/PX)
|
||||
|
||||
| Повтор | Успешных | Ошибок | `messages.history` | `cache_miss` | `cache_hit` | `cache_lock_wait` | p50, мс | p95, мс | p99, мс |
|
||||
| -----: | -------: | -----: | -----------------: | -----------: | ----------: | ----------------: | ------: | ------: | ------: |
|
||||
| 1 | 32 | 0 | 1 | 2 | 31 | 1 | 35.607 | 38.285 | 52.027 |
|
||||
| 2 | 32 | 0 | 1 | 11 | 31 | 10 | 20.404 | 37.166 | 37.178 |
|
||||
| 3 | 32 | 0 | 1 | 10 | 31 | 9 | 18.170 | 35.897 | 36.559 |
|
||||
| 4 | 32 | 0 | 1 | 12 | 31 | 11 | 20.513 | 37.058 | 37.455 |
|
||||
| 5 | 32 | 0 | 1 | 11 | 31 | 10 | 19.435 | 35.451 | 36.281 |
|
||||
| **Σ** | **160** | **0** | **5** | **46** | **155** | **41** | — | — | — |
|
||||
|
||||
Как читать счётчики:
|
||||
|
||||
- `messages.history = 1` на повторность: страницу из PostgreSQL заполнил ровно один владелец lock.
|
||||
- `cache_hit = 31` на повторность: остальные 31 читателя получили страницу владельца (повторное чтение под lock или ожидание).
|
||||
- `cache_miss` (10–12) и `cache_lock_wait` (9–11) больше единицы потому, что ожидающий считает промах на своём первом `GET` и ожидание на первой неудачной попытке `SET NX`; ни то, ни другое не означает дополнительный SQL-запрос.
|
||||
- `cache_lock_timeout` и `cache_fallback` остались нулевыми: никто не ушёл в PostgreSQL напрямую, владелец успел опубликовать страницу за отведённые повторы.
|
||||
|
||||
## 4. Сравнение
|
||||
|
||||
| Метрика | naive | protected | Изменение |
|
||||
| ------------------------------- | --------: | --------: | ----------- |
|
||||
| SQL-запросов `messages.history` | 160 | 5 | **−96,9 %** |
|
||||
| Попаданий в кэш | 0 | 155 | — |
|
||||
| Промахов | 160 | 46 | −71,3 % |
|
||||
| Ожиданий lock | 0 | 41 | — |
|
||||
| Успешных запросов | 160 | 160 | — |
|
||||
| Ошибок | 0 | 0 | — |
|
||||
| p50 (медиана по повторностям) | ≈ 89,4 мс | ≈ 20,4 мс | −77 % |
|
||||
| p95 (медиана по повторностям) | ≈ 96,3 мс | ≈ 37,1 мс | −61 % |
|
||||
|
||||
Гипотеза для этой нагрузки подтверждена: без защиты каждый конкурентный холодный читатель выполняет собственный SQL-запрос истории; с lock на конкретную страницу запрос к PostgreSQL делает только владелец, остальные обслуживаются из Redis.
|
||||
|
||||
Про латентность: разница p50/p95 между режимами **включает** искусственную паузу `CACHE_MISS_DELAY_MS=75`, которая применяется только в naive-пути (protected её не использует). Поэтому латентность здесь — иллюстрация эффекта stampede, а не сравнение скорости реализации; независимое от этой настройки наблюдение — число SQL-запросов истории (160 против 5).
|
||||
|
||||
## 5. Read-after-write
|
||||
|
||||
```json
|
||||
{ "asserted": true, "stale_observed": false }
|
||||
```
|
||||
|
||||
Наблюдалось в обоих прогонах (naive и protected). Путь записи коммитит сообщение и увеличивает `chats.message_version` в одной транзакции; путь чтения строит ключ кэша из текущей версии, поэтому страница, закэшированная до записи, становится недостижимой. Конкурентный GET, начавшийся до коммита, может вернуть прежний снимок — это допустимо контрактом.
|
||||
|
||||
## 6. Рестарт Redis и восстановление кэша
|
||||
|
||||
`python3 scripts/track1_verify.py --restart-redis --evict-cache --output evidence/track1-raw/redis-restart.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"restart_redis": true,
|
||||
"cache_eviction": { "requested": true, "message_keys_deleted": 9 },
|
||||
"same_token_users_me": true,
|
||||
"history_equal": true,
|
||||
"history_item_count": 1
|
||||
}
|
||||
```
|
||||
|
||||
Последовательность: вход → отправка сообщения → чтение истории → `docker compose restart redis` → ожидание готовности → удаление только ключей `messages:*` через `redis-cli --scan` → повторное чтение `/api/v1/users/me` и истории **тем же bearer-токеном**. Сессия выжила благодаря AOF и сохранённому тому; производный кэш истории перезагрузился из PostgreSQL, вернувшаяся страница идентична. `FLUSHALL` и удаление томов не используются.
|
||||
|
||||
## 7. План запроса истории
|
||||
|
||||
`EXPLAIN (ANALYZE, BUFFERS)` на чате с 10 002 сообщениями (полностью — `evidence/track1-explain.md`, текст анализируемых запросов и подготовка данных там же):
|
||||
|
||||
```text
|
||||
=== Запрос A: первая страница истории ===
|
||||
Limit (cost=0.28..112.30 rows=51 width=77) (actual time=0.020..0.028 rows=51 loops=1)
|
||||
Buffers: shared hit=5
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (actual time=0.020..0.025 rows=51)
|
||||
Index Cond: (chat_id = '...'::uuid)
|
||||
Buffers: shared hit=5
|
||||
Execution Time: 0.040 ms
|
||||
|
||||
=== Запрос B: продолжение по keyset-cursor ===
|
||||
Limit (cost=0.28..8.30 rows=1 width=77) (actual time=0.008..0.014 rows=51 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (actual time=0.008..0.012 rows=51)
|
||||
Index Cond: ((chat_id = '...'::uuid) AND (ROW(created_at, id) > ROW('...'::timestamptz, '...'::uuid)))
|
||||
Buffers: shared hit=4
|
||||
Execution Time: 0.048 ms
|
||||
```
|
||||
|
||||
Оба запроса идут по композитному индексу `(chat_id, created_at, id)`; keyset-предикат продолжения попадает в `Index Cond`, поэтому следующая страница не пересканирует уже прочитанное. Страница ограничена 51 строкой (limit + 1), полной материализации истории нет. Синтетические строки удалены после снятия планов (`DELETE 10000`).
|
||||
|
||||
## 8. Артефакты и происхождение данных
|
||||
|
||||
| Артефакт | sha256 | Примечание |
|
||||
| ---------------------------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------------- |
|
||||
| `evidence/track1-raw/naive.json` | `afc08f21d877952fd527675a08d4192b5143841e7833a56f1b922d836b74ba64` | сырой прогон naive, в Git не попадает |
|
||||
| `evidence/track1-raw/protected.json` | `d5cdb39802414cb3f04289d04167c6177081a79011a919ab40349c5b280ab303` | сырой прогон protected, в Git не попадает |
|
||||
| `evidence/track1-raw/redis-restart.json` | `09e8e8539d148cc6175131dea80c21a7d38d8fed370507a01eeff6a01c93c56f` | сырая проверка рестарта Redis, в Git не попадает |
|
||||
| `evidence/track1-explain.md` | `7e7f9f4ba45de05bf356696f538a346ca1c59c8913bf81bff4204bbd84c33b60` | запросы + `EXPLAIN (ANALYZE, BUFFERS)` + подготовка 10 000 строк |
|
||||
|
||||
Сырые JSON не коммитятся, потому что содержат локальные идентификаторы (строка платформы, тайминговые отпечатки, пути контейнеров). Хеши выше позволяют убедиться, что сводка соответствует именно тому прогону, который её породил.
|
||||
|
||||
## 9. Воспроизведение
|
||||
|
||||
```sh
|
||||
mkdir -p evidence/track1-raw
|
||||
printf '%s' "$METRICS_TOKEN" > /tmp/track1-metrics-token # METRICS_TOKEN из .env
|
||||
|
||||
CACHE_MODE=naive CACHE_MISS_DELAY_MS=75 docker compose --env-file .env up -d api
|
||||
python3 scripts/track1_cache_benchmark.py --base-url http://localhost:8080 --mode naive \
|
||||
--concurrency 32 --repetitions 5 --metrics-token-file /tmp/track1-metrics-token \
|
||||
--runtime-version node=25.7.0 --runtime-version postgres=16.4 --runtime-version redis=7.4.2 \
|
||||
--output evidence/track1-raw/naive.json
|
||||
|
||||
CACHE_MODE=protected docker compose --env-file .env up -d api
|
||||
python3 scripts/track1_cache_benchmark.py --base-url http://localhost:8080 --mode protected \
|
||||
--concurrency 32 --repetitions 5 --metrics-token-file /tmp/track1-metrics-token \
|
||||
--runtime-version node=25.7.0 --runtime-version postgres=16.4 --runtime-version redis=7.4.2 \
|
||||
--output evidence/track1-raw/protected.json
|
||||
|
||||
python3 scripts/track1_verify.py --summary \
|
||||
--naive-raw evidence/track1-raw/naive.json --protected-raw evidence/track1-raw/protected.json \
|
||||
--output evidence/track1-cache-consistency.md
|
||||
|
||||
python3 scripts/track1_verify.py --restart-redis --evict-cache \
|
||||
--output evidence/track1-raw/redis-restart.json
|
||||
```
|
||||
|
||||
После измерений достаточно вернуть штатные значения: `docker compose --env-file .env up -d api` (в `.env` лежат `CACHE_MODE=protected`, `CACHE_MISS_DELAY_MS=0`).
|
||||
|
||||
## 10. Ограничения
|
||||
|
||||
- Замеры на одном хосте (closed-loop, конкуренция 32, 5 повторностей): это не production-пропускная способность и не поведение часов между хостами.
|
||||
- Латентность naive включает искусственную паузу `CACHE_MISS_DELAY_MS=75`; сравнение режимов по числу SQL-запросов от этой настройки не зависит.
|
||||
- В процентили латентности попадают только успешные запросы; ошибки считаются отдельно (в этих прогонах их 0).
|
||||
- Латентность включает накладные расходы Python-клиента и сети контейнеров.
|
||||
- Бенчмарк доказывает эффект stampede для одной холодной страницы на повторность; независимость разных cursor/limit/version проверена unit-тестами, а не этой нагрузкой.
|
||||
- Метрики принадлежат конкретному процессу API: при нескольких репликах нельзя суммировать счётчики как распределённый снимок.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user