forked from mtusi2026/mtusi2026lab5
lab5: базовый коммит из lab4 (abba248)
Перенесено дерево lab4 целиком: NestJS-приложение с вложениями и S3,
Dockerfile, compose.yaml, infra/{haproxy,minio}, стендовые скрипты,
scripts/lab4, evidence/lab4 и contracts/extensions.openapi.json.
Задание lab5 оставлено своим: README, REPORT, COURSE, lab.json,
contracts/{openapi,infrastructure,jobs.schema,attachment-states,examples},
tests, compose.example.yaml, .github/pull_request_template.md.
Адаптации при переносе:
- docker-проект mtusi-lab4 -> mtusi-lab5 и тег образа mtusi-messenger:lab5,
чтобы тома и контейнеры не пересекались с lab4 (scripts/stop-one.sh:
LAB_PROJECT вместо LAB4_PROJECT);
- Makefile: цели lab5 сохранены, добавлены стендовые (stand-up/down,
wait-ready, init-env, test-e2e, test-dependencies, s3-security,
consistency, bench);
- .env.example: реальные переменные приложения и стенда lab4 (без них
compose.yaml не поднимается) + блок lab5 (BROKER_URL_FILE, WORKER_*).
This commit is contained in:
+75
-9
@@ -1,23 +1,89 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
# Полный список переменных, которые читают приложение и стенд; значения-образцы
|
||||
# не являются секретами. Соответствие «переменная -> фактическая конфигурация»
|
||||
# описано в REPORT.md.
|
||||
#
|
||||
# Приложение (проверяется zod-схемой app/src/config/app-config.schema.ts):
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
DATABASE_URL=postgresql://messenger:change-me@postgres:5432/messenger
|
||||
REDIS_URL=redis://redis:6379
|
||||
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
|
||||
# Бюджет проверки зависимостей в /health/ready: LB пробует ту же ручку
|
||||
# (timeout check 500 ms), поэтому проба обязана уложиться заметно раньше.
|
||||
HEALTH_TIMEOUT_MS=400
|
||||
# Токен доступа к /internal/metrics; сгенерируйте свой.
|
||||
METRICS_TOKEN=change-me
|
||||
# Дрейн перед выходом по SIGTERM: реплика перестаёт проходить пробы LB,
|
||||
# ждёт DRAIN_DELAY_MS (длиннее обнаружения отказа ~1 s) и только потом закрывается.
|
||||
DRAIN_DELAY_MS=3000
|
||||
# Переопределяет X-Instance-Id; по умолчанию это hostname контейнера
|
||||
# (= короткий ID контейнера, по нему работает scripts/stop-one.sh).
|
||||
# INSTANCE_ID=api-1
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
|
||||
# Стенд (compose.yaml и scripts/):
|
||||
API_REPLICAS=2
|
||||
API_CPUS_PER_REPLICA=1.5
|
||||
API_MEMORY_PER_REPLICA=1024m
|
||||
PG_CPUS=1.5
|
||||
PG_MEMORY=512m
|
||||
REDIS_CPUS=0.25
|
||||
REDIS_MEMORY=128m
|
||||
LB_CPUS=0.25
|
||||
LB_MEMORY=128m
|
||||
# Тег образа API; BUILD_ID отличает сборки при rolling update.
|
||||
API_IMAGE=mtusi-messenger:lab5
|
||||
BUILD_ID=local
|
||||
APP_PUBLIC_PORT=8080
|
||||
LB_STATS_PORT=8404
|
||||
# Loopback-порты PostgreSQL/Redis нужны только операторским проверкам с хоста
|
||||
# (make test-e2e, psql). API-реплики портов не публикуют.
|
||||
POSTGRES_PUBLISHED_PORT=5432
|
||||
REDIS_PUBLISHED_PORT=6379
|
||||
|
||||
# PostgreSQL (пароль подставьте свой; тот же, что в DATABASE_URL):
|
||||
POSTGRES_DB=messenger
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=change-me
|
||||
|
||||
# Объектное хранилище MinIO. Credentials — файлы ./secrets/* (scripts/init-env.sh), не здесь.
|
||||
S3_ENDPOINT=http://s3:9000
|
||||
S3_PUBLIC_ENDPOINT=http://localhost:9000
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
S3_PUBLIC_BIND=127.0.0.1
|
||||
S3_PUBLIC_PORT=9000
|
||||
S3_CPUS=1.0
|
||||
S3_MEMORY=512m
|
||||
S3_CONNECT_TIMEOUT_MS=1000
|
||||
S3_REQUEST_TIMEOUT_MS=15000
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
# Каждая загрузка держит копию файла (≤ MAX_UPLOAD_BYTES) до полного декода;
|
||||
# худший декод (40 Мп RGBA16 interlaced PNG) ≈ 340 MiB. Граница памяти реплики:
|
||||
# базовый RSS (~250 MiB) + UPLOAD_MAX_IN_FLIGHT × 10 MiB + IMAGE_DECODE_MAX_CONCURRENT × 340 MiB
|
||||
# = 250 + 160 + 340 ≈ 750 MiB при API_MEMORY_PER_REPLICA=1024m.
|
||||
UPLOAD_MAX_IN_FLIGHT=16
|
||||
# Не больше стольких одновременных загрузок одного пользователя на реплику.
|
||||
UPLOAD_MAX_IN_FLIGHT_PER_USER=4
|
||||
IMAGE_DECODE_MAX_CONCURRENT=1
|
||||
DIRECT_UPLOAD_MAX_PENDING_PER_USER=10
|
||||
# UPLOAD_TIMEOUT_MS, DIRECT_UPLOAD_URL_TTL_SECONDS, ATTACHMENT_SWEEP_GRACE_SECONDS,
|
||||
# ATTACHMENT_SWEEP_INTERVAL_MS задаются в compose.yaml (environment) с умолчаниями
|
||||
# и переопределяются из shell только для экспериментов.
|
||||
|
||||
# lab5: очередь и асинхронная обработка изображений. Пока не реализовано —
|
||||
# приложение эти переменные не читает. URL брокера берётся из файла секрета,
|
||||
# байты и credentials в сообщения не попадают.
|
||||
BROKER_URL_FILE=/run/secrets/broker_url
|
||||
WORKER_CONCURRENCY=2
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
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 && npm prune --omit=dev
|
||||
|
||||
FROM node:25.7.0-slim AS runtime
|
||||
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
# BUILD_ID доказывается через GET /internal/metrics и меняется при rolling
|
||||
# update: он показывает, какая именно сборка отвечает на запрос.
|
||||
ARG BUILD_ID=unknown
|
||||
ENV BUILD_ID=$BUILD_ID
|
||||
|
||||
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 ./
|
||||
COPY --from=build /usr/src/app/node_modules ./node_modules
|
||||
COPY --from=build /usr/src/app/dist ./dist
|
||||
|
||||
USER node
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 \
|
||||
CMD node -e "const port=process.env.APP_PORT||'8080'; fetch('http://127.0.0.1:'+port+'/health/ready').then((response) => { if (!response.ok) process.exit(1); }).catch(() => process.exit(1))"
|
||||
|
||||
CMD ["node", "dist/main.js"]
|
||||
@@ -4,10 +4,10 @@ CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover
|
||||
.PHONY: help check validate test load test-persistence test-failover test-dependencies stand-up stand-down stand-status wait-ready init-env test-e2e s3-security consistency bench
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes; init-env: .env + secrets; test-e2e: app e2e; s3-security; consistency; bench"
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -28,3 +28,42 @@ test-persistence:
|
||||
test-failover:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
COMPOSE_ENV_FILE ?= .env
|
||||
COMPOSE = docker compose --env-file $(COMPOSE_ENV_FILE)
|
||||
|
||||
test-dependencies:
|
||||
cd app && E2E_COMPOSE_DIR="$(CURDIR)" E2E_COMPOSE_ENV_FILE="$(COMPOSE_ENV_FILE)" npm run test:dependencies
|
||||
|
||||
stand-up:
|
||||
$(COMPOSE) up -d --build --wait
|
||||
|
||||
stand-down:
|
||||
$(COMPOSE) down
|
||||
|
||||
stand-status:
|
||||
$(COMPOSE) ps
|
||||
|
||||
wait-ready:
|
||||
@for attempt in $$(seq 1 60); do \
|
||||
if curl -fsS "$(BASE_URL)/health/ready" >/dev/null 2>&1; then \
|
||||
echo "stand is ready ($(BASE_URL))"; exit 0; \
|
||||
fi; \
|
||||
sleep 1; \
|
||||
done; \
|
||||
echo "stand did not become ready within 60s" >&2; exit 1
|
||||
|
||||
init-env:
|
||||
./scripts/init-env.sh
|
||||
|
||||
test-e2e:
|
||||
scripts/app-e2e.sh
|
||||
|
||||
s3-security:
|
||||
scripts/lab4/check_s3_security.sh
|
||||
|
||||
consistency:
|
||||
scripts/lab4/consistency_check.sh
|
||||
|
||||
bench:
|
||||
scripts/lab4/run_matrix.sh
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# compiled output
|
||||
/dist
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# TypeScript build cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# Tests
|
||||
/coverage
|
||||
/.nyc_output
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# temp directory
|
||||
.temp
|
||||
.tmp
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"tabWidth": 4,
|
||||
"useTabs": true
|
||||
}
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
# app — API мессенджера
|
||||
|
||||
NestJS 12 + Fastify, ESM TypeScript. PostgreSQL — источник истины бизнес-данных,
|
||||
Redis — серверные Bearer-сессии и производный кэш истории сообщений.
|
||||
|
||||
Общая документация (в корне репозитория):
|
||||
|
||||
| Документ | Что содержит |
|
||||
|---|---|
|
||||
| [`../REPORT.md`](../REPORT.md) | архитектура, схема данных, транзакции, политика кэша, команды, результаты проверок и трека 1 |
|
||||
| [`../evidence/README.md`](../evidence/README.md) | индекс доказательств: что подтверждено и как это воспроизвести |
|
||||
| [`../contracts/openapi.json`](../contracts/openapi.json) | нормативный контракт API |
|
||||
| [`../tests/README.md`](../tests/README.md) | публичные проверки репозитория (`make check`, `make test`, persistence) |
|
||||
|
||||
## Что внутри
|
||||
|
||||
```text
|
||||
src/
|
||||
main.ts bootstrap: Fastify, ValidationPipe, shutdown hooks
|
||||
app.module.ts сборка модулей приложения
|
||||
config/ Zod-схема env + глобальный ConfigModule
|
||||
database/ pg.Pool, транзакции, миграции (001..004)
|
||||
redis/ клиент Redis (AOF-совместимый, без offline queue)
|
||||
auth/ Basic-вход, Redis-сессии, logout
|
||||
users/ регистрация (Argon2id), профиль
|
||||
chats/ создание чата в транзакции, список и чтение
|
||||
messages/ отправка сообщения, keyset-история
|
||||
cache/ версионированный кэш истории + lock на страницу
|
||||
idempotency/ журнал Idempotency-Key (claim/read/store/forget/GC)
|
||||
metrics/ /internal/metrics и /internal/metrics/reset
|
||||
health/ liveness/readiness с проверкой зависимостей (readiness — проба LB)
|
||||
common/
|
||||
http/ cursor (формат+календарь), page (конверт {items,next_cursor}), request-id
|
||||
errors/ exception filter и тип тела ошибки ApiErrorBody
|
||||
validation/ декоратор CodePointLength (длины в Unicode code points)
|
||||
auth/ guard и декоратор текущего пользователя
|
||||
test/
|
||||
app.e2e-spec.ts black-box набор против запущенного API (PG + Redis)
|
||||
scripts/
|
||||
graph-modules.ts генератор графа зависимостей (nestjs-spelunker)
|
||||
```
|
||||
|
||||
Принципы: raw `pg.Pool` без ORM, параметризованные запросы, никаких in-memory
|
||||
хранилищ в боевых путях; кэш — производное состояние и всегда допускает
|
||||
восстановление из PostgreSQL; отказ зависимости даёт ограниченную ошибку
|
||||
(`503`), а не аварийное завершение процесса; длины строк проверяются в Unicode
|
||||
code points (свой декоратор `@CodePointLength`), как в JSON Schema, а не в
|
||||
UTF-16-единицах; состояние, от которого зависит корректность (сессии, журнал
|
||||
идемпотентности), живёт только в общих PostgreSQL/Redis — локальных сессий и
|
||||
файлов на диске реплики нет, поэтому `N` взаимозаменяемых реплик за одним LB
|
||||
дают один и тот же результат.
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
Рекомендуемый путь — весь стенд из корня репозитория (PostgreSQL, Redis, миграции, API):
|
||||
|
||||
```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
|
||||
sed -i "s/^METRICS_TOKEN=.*/METRICS_TOKEN=$(openssl rand -hex 16)/" .env
|
||||
make stand-up # сборка + up -d --wait: migrate -> api x API_REPLICAS -> haproxy
|
||||
make wait-ready
|
||||
curl -fsS http://localhost:8080/health/ready
|
||||
for i in 1 2 3 4; do curl -sD- -o /dev/null localhost:8080/health/live | grep -i x-instance-id; done
|
||||
```
|
||||
|
||||
Публичной точкой входа служит HAProxy (`compose.yaml`): реплики API портов не
|
||||
публикуют. `API_REPLICAS` задаёт их число, `API_TOTAL_CPUS` / `API_TOTAL_MEMORY_MB`
|
||||
делятся между ними — это бюджет серии трека 1 (`../REPORT.md`).
|
||||
|
||||
Локальный запуск без Docker (нужны доступные PostgreSQL и Redis):
|
||||
|
||||
```sh
|
||||
cd app
|
||||
npm ci
|
||||
npm run build
|
||||
|
||||
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
|
||||
|
||||
npm run start:dev # или npm run start:prod после build
|
||||
```
|
||||
|
||||
## Переменные окружения
|
||||
|
||||
Читаются только через конфигурационный слой (`src/config`), типы и диапазоны
|
||||
проверяет Zod-схема на старте — при некорректном значении приложение падает
|
||||
с понятной ошибкой.
|
||||
|
||||
| Переменная | По умолчанию | Назначение |
|
||||
|---|---|---|
|
||||
| `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) |
|
||||
| `HEALTH_TIMEOUT_MS` | `400` | бюджет проверки PostgreSQL/Redis внутри `/health/ready`; меньше `timeout check` HAProxy (500 ms) и `DATABASE_STATEMENT_TIMEOUT_MS` |
|
||||
| `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` (в стенде `3000`) | окно дрейна при `SIGTERM`: реплика сразу перестаёт проходить пробу LB, ждёт этот интервал и только затем закрывает сервер и пулы |
|
||||
| `INSTANCE_ID` | hostname контейнера | значение `X-Instance-Id`; в Docker hostname = короткий ID контейнера, поэтому `scripts/stop-one.sh` находит реплику по нему |
|
||||
| `IDEMPOTENCY_TTL_SECONDS` | `86400` | срок хранения журнала Idempotency-Key (минимум 60) |
|
||||
|
||||
Поддерживаются также `DATABASE_URL_FILE` / `REDIS_URL_FILE`: если заданы, значение
|
||||
читается из файла (docker secrets / Swarm). Подробности и компромиссы —
|
||||
[`../REPORT.md`](../REPORT.md), раздел «Конфигурация и секреты».
|
||||
|
||||
## Эндпоинты
|
||||
|
||||
Публичный контракт — [`../contracts/openapi.json`](../contracts/openapi.json).
|
||||
|
||||
| Метод и путь | Аутентификация | Назначение |
|
||||
|---|---|---|
|
||||
| `GET /health/live` | нет | процесс жив; не обращается к зависимостям, поэтому отвечает `200` и при их отказе |
|
||||
| `GET /health/ready` | нет | готовность реплики: флаг дреина + PostgreSQL и Redis (бюджет `HEALTH_TIMEOUT_MS`), иначе `503`; эту же ручку пробует HAProxy |
|
||||
| `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` + обязательный `Idempotency-Key` | отправка сообщения (см. ниже) |
|
||||
| `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 test:dependencies` | автоматическая проверка отказов Redis/PostgreSQL: останавливает и поднимает контейнеры Compose-стенда |
|
||||
| `npm run idempotency:gc` | ручной прогон удаления просроченных записей Idempotency-Key |
|
||||
| `npm run lint` | oxlint по `src/` и `test/` |
|
||||
| `npm run format` | prettier |
|
||||
| `npm run graph` | граф модулей и провайдеров через nestjs-spelunker (пишет `../docs/architecture/`) |
|
||||
|
||||
## Тесты
|
||||
|
||||
Unit-тесты не требуют инфраструктуры:
|
||||
|
||||
```sh
|
||||
npm test
|
||||
```
|
||||
|
||||
Интеграционный набор работает по HTTP против запущенного стенда и дополнительно
|
||||
подключается к PostgreSQL (очистка тестовых данных) и Redis:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
Название `API_BASE_URL` (а не `BASE_URL`) выбрано потому, что Vitest сам
|
||||
устанавливает `process.env.BASE_URL` в значение Vite base. Кейс истечения сессии
|
||||
включается переменной `SESSION_TTL_SECONDS=2` и у запущенного API, и у набора.
|
||||
|
||||
## Отказы зависимостей
|
||||
|
||||
Отдельный набор останавливает и поднимает контейнеры Compose-стенда и проверяет
|
||||
ограниченные ошибки вместо 500:
|
||||
|
||||
```sh
|
||||
cd .. # из корня репозитория, стенд поднят через docker compose
|
||||
make test-dependencies
|
||||
```
|
||||
|
||||
Он включён по флагу `E2E_DEPENDENCY_FAULTS=1` (им же управляет цель Makefile),
|
||||
потому что требует прав на управление Docker Compose-проектом; остальные
|
||||
переменные — `E2E_COMPOSE_DIR`, `E2E_COMPOSE_ENV_FILE`, `E2E_REDIS_SERVICE`,
|
||||
`E2E_POSTGRES_SERVICE`, `E2E_API_SERVICE`, `E2E_LB_STATS_URL`,
|
||||
`E2E_POSTGRES_USER`, `E2E_POSTGRES_DB`, `E2E_PG_HBA_PATH`.
|
||||
|
||||
Проверяются три топологии отказа:
|
||||
|
||||
1. **Отказ Redis** (общая зависимость): `/health/live` реплики остаётся `200`,
|
||||
`/health/ready` и бизнес-запросы — `503 unavailable` с `request_id` из
|
||||
`X-Request-Id` и без деталей драйвера, запрос без сессии — по-прежнему `401`.
|
||||
Неготовыми становятся все реплики, HAProxy исключает их из ротации и
|
||||
отвечает собственным `503`; после старта Redis сессия и подтверждённое
|
||||
сообщение живы.
|
||||
2. **Отказ PostgreSQL** (общая зависимость): то же плюс проверка, что после
|
||||
возврата зависимости данные на месте и новая запись проходит.
|
||||
3. **Отказ PostgreSQL у одной реплики** (локальный путь к БД): для адреса
|
||||
выбранной реплики временно ставится `reject`-строка в `pg_hba.conf` (первое
|
||||
совпадение) и обрываются её соединения. Выбранная реплика отвечает `503` и её
|
||||
слот уходит в `DOWN`, здоровая продолжает `200`/`UP` и обслуживает все чтения
|
||||
через LB; `pg_hba.conf` восстанавливается в `finally`, после чего реплика
|
||||
возвращается в ротацию и снова получает запросы.
|
||||
|
||||
Реплики API портов не публикуют, поэтому отдельная реплика опрашивается изнутри
|
||||
своего контейнера (loopback), а состояние слотов — из `stats;csv` HAProxy
|
||||
(`127.0.0.1:8404`). Каждый запрос к остановленной БД ждёт
|
||||
`DATABASE_CONNECTION_TIMEOUT_MS`, поэтому набор идёт около минуты.
|
||||
|
||||
## Реплики, балансировка и остановка реплики
|
||||
|
||||
Все реплики запускаются из одного образа и одного `compose.yaml`; API портов не
|
||||
публикует, трафик идёт только через HAProxy. Состояние, от которого зависит
|
||||
корректность, лежит в общих PostgreSQL и Redis, поэтому клиент с одним
|
||||
Bearer-токеном обслуживается любой репликой:
|
||||
|
||||
```sh
|
||||
make test BASE_URL=http://localhost:8080 # сквозной сценарий через LB
|
||||
python3 scripts/lab3/lab3.py check spread # распределение X-Instance-Id
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh # отказ одной реплики
|
||||
scripts/start-replica.sh # вернуть остановленную реплику
|
||||
```
|
||||
|
||||
- `X-Instance-Id` = `INSTANCE_ID` или hostname процесса, стабилен для процесса;
|
||||
в Docker hostname контейнера — короткий ID, поэтому `scripts/stop-one.sh`
|
||||
останавливает ровно ту реплику, которую обслужил запрос теста. Тот же заголовок
|
||||
добавляется к ответам об ошибках, которые формируются фильтром до интерсептора.
|
||||
- **Остановка (`SIGTERM`)** идёт в порядке «сначала дрейн, потом разбор ресурсов»:
|
||||
реплика помечается not-ready (проба LB и `/health/ready` начинают отвечать
|
||||
`503`), `DRAIN_DELAY_MS` ждёт, пока LB её исключит (обнаружение ≈1 s), и лишь
|
||||
затем закрываются HTTP-сервер, пул PostgreSQL и соединение Redis. Если
|
||||
полагаться на стандартный порядок Nest (`onModuleDestroy` вызывает закрытие
|
||||
пулов раньше `beforeApplicationShutdown`), реплика какое-то время остаётся в
|
||||
ротации уже без ресурсов — это и было причиной явной последовательности в
|
||||
`src/main.ts`.
|
||||
- **Проба LB — тот же `/health/ready`**, что и healthcheck контейнера: реплика,
|
||||
потерявшая обязательную зависимость (свой путь к PostgreSQL или Redis),
|
||||
выходит из ротации, и трафик уходит на здоровые реплики. Проба с зависимостями
|
||||
ограничена общим дедлайном `HEALTH_TIMEOUT_MS=400` на реплику; проверка
|
||||
PostgreSQL (`SELECT 1`) идёт по отдельному соединению, а не из общего пула
|
||||
бизнес-запросов, а для `PING` Redis стоит `AbortSignal.timeout`, поэтому проба
|
||||
укладывается в `timeout check 500ms` HAProxy и не реагирует на перегрузку.
|
||||
Когда недоступна общая для всех зависимость,
|
||||
неготовыми становятся все реплики, и клиент получает `503` от самого LB: это
|
||||
честный ответ «готовых узлов нет» вместо маскировки отказа.
|
||||
- `/health/live` зависимостей не касается: он отвечает `200`, пока жив процесс,
|
||||
и по нему проверяют, что реплика не упала (в том числе при отказе PG/Redis).
|
||||
|
||||
## Идемпотентность отправки сообщения
|
||||
|
||||
`POST /api/v1/chats/{chatId}/messages` требует заголовок `Idempotency-Key`
|
||||
(ASCII `[A-Za-z0-9._:-]{1,128}`). Область уникальности — пользователь + метод +
|
||||
путь чата + ключ, поэтому одинаковый ключ у разных пользователей или в разных
|
||||
чатах не конфликтует. Журнал — таблица `idempotency_keys` (миграция 003), то
|
||||
есть общая для всех реплик.
|
||||
|
||||
| Ситуация | Ответ |
|
||||
|---|---|
|
||||
| Заголовок отсутствует, пуст или не подходит под шаблон | `400 invalid_request` (до обращения к БД) |
|
||||
| Первый запрос с ключом | `201` и сообщение; заявка, вставка сообщения, инкремент версии чата и тело ответа записываются **одним оператором SQL** (атомарность обеспечивает сам оператор) |
|
||||
| Повтор того же тела с тем же ключом | тот же `201` и тот же JSON (включая `id` и `created_at`), новое сообщение не создаётся |
|
||||
| Другое тело с тем же ключом | `409 conflict` |
|
||||
| Повтор после `404` (нет доступа к чату) | `404`, ключ не занят: оператор вставляет заявку только при наличии членства, иначе не создаётся ничего |
|
||||
| Ключ старше `IDEMPOTENCY_TTL_SECONDS` | запись удаляется, ключ считается свободным |
|
||||
| Одновременные повторы через разные реплики | ровно одно сообщение: заявка берётся `INSERT ... ON CONFLICT DO NOTHING`, повтор читает сохранённый ответ |
|
||||
|
||||
Путь записи — один round trip: `messages.createIdempotent` проверяет членство,
|
||||
занимает ключ (`INSERT ... ON CONFLICT DO NOTHING`), вставляет сообщение, поднимает
|
||||
`chats.message_version` и сохраняет тело ответа, а повтор читает сохранённый ответ
|
||||
вместе с повторной проверкой доступа (`idempotency.read`). До оптимизации это были
|
||||
8 обращений к БД в явной транзакции (см. REPORT.md, раздел «A/B улучшения»).
|
||||
|
||||
Отпечаток тела считается по валидированному DTO с фиксированным порядком полей,
|
||||
поэтому порядок ключей в JSON не влияет на результат. Транзиентные сбои
|
||||
PostgreSQL (`57014`, `40001`, `40P01`) и обрывы соединения отдаются как
|
||||
`503 unavailable` и не фиксируются как окончательный результат: клиент может
|
||||
безопасно повторить запрос с тем же ключом. Просроченные записи удаляются
|
||||
фоновым проходом (`idempotency.purged` в метриках) под
|
||||
`pg_try_advisory_xact_lock`, а также вручную: `npm run idempotency:gc`.
|
||||
|
||||
## Харнесс экспериментов
|
||||
|
||||
Уровни 3/4 и трек 1 обслуживает `../scripts/lab3/lab3.py` (только stdlib) и
|
||||
профили k6 в `../scripts/load/`: `run`, `sweep`, `track1-extras`, `failover`,
|
||||
`rolling-update`, `ab`, `analyze`, `watch`, `check`, `quiesce`, `track1`.
|
||||
Сырые результаты прогонов, манифесты условий измерения и графики складываются в
|
||||
`../evidence/track1/`. Подробности — в `../REPORT.md` и
|
||||
`../evidence/README.md`.
|
||||
|
||||
## Метрики
|
||||
|
||||
`GET /internal/metrics` возвращает `{counters, latency_ms, instance_id, build_id}`: именованные 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`, а также
|
||||
идемпотентность: `idempotency.claim`, `idempotency.replay`, `idempotency.conflict`,
|
||||
`idempotency.claim_lost`, `idempotency.released`, `idempotency.purged`,
|
||||
`idempotency.purge_error`, `messages.write`.
|
||||
|
||||
Счётчики локальны процессу: при нескольких репликах их нельзя суммировать как
|
||||
распределённый снимок, а рестарт API обнуляет их (данные PostgreSQL и Redis при
|
||||
этом не затрагиваются). `instance_id` и `build_id` позволяют сопоставить ответ
|
||||
конкретной реплике и сборке — этим пользуются rolling update и эксперименты.
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true,
|
||||
"assets": [
|
||||
{
|
||||
"include": "database/migrations/*.sql",
|
||||
"outDir": "dist"
|
||||
}
|
||||
],
|
||||
"watchAssets": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/crates/oxc_linter/src/rules.rs",
|
||||
"rules": {
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/no-floating-promises": "warn"
|
||||
},
|
||||
"env": {
|
||||
"node": true
|
||||
}
|
||||
}
|
||||
Generated
+8375
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,71 @@
|
||||
{
|
||||
"name": "app",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"deploy": "nest deploy",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "oxlint src/ test/",
|
||||
"test": "vitest run",
|
||||
"test:unit": "vitest run --include 'src/**/*.spec.ts'",
|
||||
"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",
|
||||
"test:dependencies": "E2E_DEPENDENCY_FAULTS=1 vitest run --config ./vitest.config.e2e.ts dependency-failures",
|
||||
"attachments:sweep": "tsx src/attachments/attachments-sweep.cli.ts",
|
||||
"idempotency:gc": "tsx src/messages/idempotency/idempotency-gc.cli.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.1156.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.1156.0",
|
||||
"@nestjs/common": "^12.0.1",
|
||||
"@nestjs/config": "^12.0.0",
|
||||
"@nestjs/core": "^12.0.1",
|
||||
"@nestjs/platform-express": "^12.0.1",
|
||||
"@nestjs/platform-fastify": "^12.0.3",
|
||||
"@smithy/node-http-handler": "^4.12.1",
|
||||
"argon2": "^0.45.1",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"date-fns": "^4.4.0",
|
||||
"fastify": "^5.12.5",
|
||||
"pg": "^8.23.1",
|
||||
"redis": "^6.3.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"sharp": "^0.35.5",
|
||||
"zod": "^4.6.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^12.0.0",
|
||||
"@nestjs/mau": "^0.2.6",
|
||||
"@nestjs/schematics": "^12.0.0",
|
||||
"@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),
|
||||
);
|
||||
@@ -0,0 +1,35 @@
|
||||
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 { AttachmentsModule } from './attachments/attachments.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: [
|
||||
AppConfigModule,
|
||||
DatabaseModule,
|
||||
RedisModule,
|
||||
UsersModule,
|
||||
AuthModule,
|
||||
HealthModule,
|
||||
ChatsModule,
|
||||
MessagesModule,
|
||||
AttachmentsModule,
|
||||
MetricsModule,
|
||||
],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_FILTER,
|
||||
useClass: ApiExceptionFilter,
|
||||
},
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,78 @@
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import { ObjectStorage } from '../storage/object-storage.js';
|
||||
import { AttachmentsRepository } from './attachments.repository.js';
|
||||
|
||||
const SWEEP_BATCH = 100;
|
||||
|
||||
/**
|
||||
* Removes unfinished uploads (pending past expiry + grace) and rows whose
|
||||
* deletion was claimed but never finished. A live upload is never touched:
|
||||
* its expiry is a hard request deadline and the grace period is far longer.
|
||||
*/
|
||||
@Injectable()
|
||||
export class AttachmentSweeper implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(AttachmentSweeper.name);
|
||||
private timer: NodeJS.Timeout | undefined;
|
||||
private running = false;
|
||||
|
||||
constructor(
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly repository: AttachmentsRepository,
|
||||
private readonly storage: ObjectStorage,
|
||||
private readonly metrics: MetricsService,
|
||||
) {}
|
||||
|
||||
onModuleInit(): void {
|
||||
const interval = this.config.getOrThrow('ATTACHMENT_SWEEP_INTERVAL_MS');
|
||||
if (interval <= 0) return;
|
||||
this.timer = setInterval(() => {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
this.sweepOnce()
|
||||
.catch((error: unknown) => {
|
||||
this.logger.warn(
|
||||
`Sweep failed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
this.running = false;
|
||||
});
|
||||
}, interval);
|
||||
this.timer.unref();
|
||||
}
|
||||
|
||||
onModuleDestroy(): void {
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
this.timer = undefined;
|
||||
}
|
||||
|
||||
async sweepOnce(): Promise<{ claimed: number; deleted: number }> {
|
||||
const claimed = await this.repository.claimExpired(
|
||||
this.config.getOrThrow('ATTACHMENT_SWEEP_GRACE_SECONDS'),
|
||||
SWEEP_BATCH,
|
||||
);
|
||||
let deleted = 0;
|
||||
for (const item of claimed) {
|
||||
try {
|
||||
await this.storage.delete(item.object_key);
|
||||
await this.repository.deleteClaimed(item.id);
|
||||
deleted += 1;
|
||||
this.metrics.increment('attachments.sweep.deleted');
|
||||
} catch (error) {
|
||||
this.metrics.increment('attachments.sweep.error');
|
||||
this.logger.warn(
|
||||
`Sweep of attachment ${item.id} failed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return { claimed: claimed.length, deleted };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
export type Attachment = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
owner_id: string;
|
||||
filename: string;
|
||||
content_type: 'image/png' | 'image/jpeg';
|
||||
size_bytes: number;
|
||||
sha256: string;
|
||||
status: 'ready';
|
||||
variants: never[];
|
||||
error_code: null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
export type AttachmentRow = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
owner_id: string;
|
||||
filename: string;
|
||||
content_type: 'image/png' | 'image/jpeg';
|
||||
upload_mode: 'proxy' | 'direct';
|
||||
status: 'pending' | 'ready' | 'deleting' | 'rejected';
|
||||
object_key: string;
|
||||
size_bytes: string | number | null;
|
||||
sha256: string | null;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
expires_at: Date | null;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
};
|
||||
|
||||
export function toAttachment(row: AttachmentRow): Attachment {
|
||||
return {
|
||||
id: row.id,
|
||||
chat_id: row.chat_id,
|
||||
owner_id: row.owner_id,
|
||||
filename: row.filename,
|
||||
content_type: row.content_type,
|
||||
size_bytes: Number(row.size_bytes),
|
||||
sha256: row.sha256 as string,
|
||||
status: 'ready',
|
||||
variants: [],
|
||||
error_code: null,
|
||||
created_at: row.created_at.toISOString(),
|
||||
updated_at: row.updated_at.toISOString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { parseAppConfig } from '../config/app-config.schema.js';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import { ObjectStorage } from '../storage/object-storage.js';
|
||||
import { AttachmentSweeper } from './attachment-sweeper.service.js';
|
||||
import { AttachmentsRepository } from './attachments.repository.js';
|
||||
|
||||
// Manual operator pass over unfinished uploads (the API also sweeps in the
|
||||
// background). Never touches rows before expiry + ATTACHMENT_SWEEP_GRACE_SECONDS.
|
||||
// in the stand: docker compose exec api node dist/attachments/attachments-sweep.cli.js
|
||||
// on the host: npm run attachments:sweep (needs reachable DATABASE_URL and S3)
|
||||
async function main(): Promise<void> {
|
||||
const config = parseAppConfig(process.env as Record<string, unknown>);
|
||||
const configService = {
|
||||
getOrThrow: (key: keyof typeof config) => config[key],
|
||||
} as never;
|
||||
const metrics = new MetricsService();
|
||||
const database = new DatabaseClient(configService, metrics);
|
||||
try {
|
||||
const sweeper = new AttachmentSweeper(
|
||||
configService,
|
||||
new AttachmentsRepository(database),
|
||||
new ObjectStorage(configService),
|
||||
metrics,
|
||||
);
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const { claimed, deleted } = await sweeper.sweepOnce();
|
||||
total += deleted;
|
||||
// A pass that claimed rows but could not delete any would loop forever.
|
||||
if (claimed === 0 || deleted === 0) break;
|
||||
}
|
||||
process.stdout.write(
|
||||
`Swept ${total} attachment(s) older than ${config.ATTACHMENT_SWEEP_GRACE_SECONDS} seconds past expiry\n`,
|
||||
);
|
||||
} finally {
|
||||
await database.onModuleDestroy();
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
|
||||
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Headers,
|
||||
HttpCode,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
StreamableFile,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import type { Readable } from 'node:stream';
|
||||
import { CurrentUser } from '../common/auth/current-user.decorator.js';
|
||||
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import { AttachmentsService } from './attachments.service.js';
|
||||
import { CreateDirectUploadDto } from './dto/create-direct-upload.dto.js';
|
||||
import { DirectUploadsService } from './direct-uploads.service.js';
|
||||
import type { UploadRequest } from './upload-request.js';
|
||||
import { contentDisposition } from './filename.js';
|
||||
|
||||
@Controller('api/v1')
|
||||
@UseGuards(CurrentUserGuard)
|
||||
export class AttachmentsController {
|
||||
private readonly maxUploadBytes: number;
|
||||
|
||||
constructor(
|
||||
private readonly attachments: AttachmentsService,
|
||||
private readonly directUploads: DirectUploadsService,
|
||||
config: ConfigService<AppConfig>,
|
||||
) {
|
||||
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
|
||||
}
|
||||
|
||||
@Post('chats/:chatId/attachments')
|
||||
@HttpCode(201)
|
||||
upload(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
@Query('filename') filename: unknown,
|
||||
@Headers('content-length') contentLength: string | undefined,
|
||||
@Req() request: FastifyRequest & UploadRequest,
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
) {
|
||||
// A gigantic body is not worth draining: close the connection after the answer.
|
||||
if (Number(contentLength) > 2 * this.maxUploadBytes)
|
||||
reply.header('Connection', 'close');
|
||||
return this.attachments.uploadProxy(
|
||||
chatId,
|
||||
user,
|
||||
filename,
|
||||
request.uploadContentType,
|
||||
contentLength,
|
||||
request.body as Readable | undefined,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('chats/:chatId/attachments/direct-uploads')
|
||||
@HttpCode(201)
|
||||
initDirectUpload(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
@Body() body: CreateDirectUploadDto,
|
||||
) {
|
||||
return this.directUploads.init(chatId, user, body);
|
||||
}
|
||||
|
||||
@Post('attachments/:attachmentId/complete')
|
||||
@HttpCode(200)
|
||||
completeDirectUpload(
|
||||
@Param('attachmentId', new ParseUUIDPipe()) attachmentId: string,
|
||||
@CurrentUser() user: User,
|
||||
) {
|
||||
return this.directUploads.complete(attachmentId, user);
|
||||
}
|
||||
|
||||
@Get('attachments/:attachmentId')
|
||||
metadata(
|
||||
@Param('attachmentId', new ParseUUIDPipe()) attachmentId: string,
|
||||
@CurrentUser() user: User,
|
||||
) {
|
||||
return this.attachments.getMetadata(attachmentId, user);
|
||||
}
|
||||
|
||||
@Get('attachments/:attachmentId/content')
|
||||
async content(
|
||||
@Param('attachmentId', new ParseUUIDPipe()) attachmentId: string,
|
||||
@CurrentUser() user: User,
|
||||
@Res({ passthrough: true }) reply: FastifyReply,
|
||||
@Query('variant') variant?: string,
|
||||
) {
|
||||
const { row, stream } = await this.attachments.openContent(
|
||||
attachmentId,
|
||||
user,
|
||||
variant,
|
||||
);
|
||||
reply.header('X-Content-Type-Options', 'nosniff');
|
||||
reply.header('Cache-Control', 'private, no-store');
|
||||
return new StreamableFile(stream, {
|
||||
type: row.content_type,
|
||||
length: Number(row.size_bytes),
|
||||
disposition: contentDisposition(row.filename),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
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 { RedisModule } from '../redis/redis.module.js';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
import { StorageModule } from '../storage/storage.module.js';
|
||||
import { AttachmentSweeper } from './attachment-sweeper.service.js';
|
||||
import { AttachmentsController } from './attachments.controller.js';
|
||||
import { AttachmentsRepository } from './attachments.repository.js';
|
||||
import { ImageDecoder } from './image/image-decoder.js';
|
||||
import { UploadSlots } from './upload-slots.js';
|
||||
import { DirectUploadsService } from './direct-uploads.service.js';
|
||||
import { AttachmentsService } from './attachments.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
DatabaseModule,
|
||||
ChatsModule,
|
||||
UsersModule,
|
||||
RedisModule,
|
||||
MetricsModule,
|
||||
StorageModule,
|
||||
],
|
||||
controllers: [AttachmentsController],
|
||||
providers: [
|
||||
AttachmentsRepository,
|
||||
AttachmentsService,
|
||||
DirectUploadsService,
|
||||
ImageDecoder,
|
||||
UploadSlots,
|
||||
AttachmentSweeper,
|
||||
],
|
||||
exports: [AttachmentsRepository],
|
||||
})
|
||||
export class AttachmentsModule {}
|
||||
@@ -0,0 +1,191 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import type { AttachmentRow } from './attachment.js';
|
||||
|
||||
export type InsertPending = {
|
||||
id: string;
|
||||
chatId: string;
|
||||
ownerId: string;
|
||||
filename: string;
|
||||
contentType: string;
|
||||
uploadMode: 'proxy' | 'direct';
|
||||
objectKey: string;
|
||||
sizeBytes: number | null;
|
||||
sha256: string | null;
|
||||
ttlMs: number;
|
||||
};
|
||||
|
||||
export type ReadyFields = {
|
||||
sizeBytes: number;
|
||||
sha256: string;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
const VISIBLE_MEMBER = `JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2`;
|
||||
|
||||
@Injectable()
|
||||
export class AttachmentsRepository {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
async insertPending(input: InsertPending): Promise<void> {
|
||||
await this.database.query(
|
||||
'attachments.insert_pending',
|
||||
`INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, upload_mode, status,
|
||||
object_key, size_bytes, sha256, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, 'pending', $7, $8, $9,
|
||||
now() + make_interval(secs => $10::double precision / 1000.0))`,
|
||||
[
|
||||
input.id,
|
||||
input.chatId,
|
||||
input.ownerId,
|
||||
input.filename,
|
||||
input.contentType,
|
||||
input.uploadMode,
|
||||
input.objectKey,
|
||||
input.sizeBytes,
|
||||
input.sha256,
|
||||
input.ttlMs,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
async markReady(
|
||||
id: string,
|
||||
fields: ReadyFields,
|
||||
): Promise<AttachmentRow | undefined> {
|
||||
const result = await this.database.query<AttachmentRow>(
|
||||
'attachments.mark_ready',
|
||||
`UPDATE attachments
|
||||
SET status = 'ready', size_bytes = $2, sha256 = $3, width = $4,
|
||||
height = $5, expires_at = NULL, updated_at = now()
|
||||
WHERE id = $1 AND status = 'pending'
|
||||
RETURNING *`,
|
||||
[id, fields.sizeBytes, fields.sha256, fields.width, fields.height],
|
||||
);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async deletePending(id: string): Promise<void> {
|
||||
await this.database.query(
|
||||
'attachments.delete_pending',
|
||||
`DELETE FROM attachments WHERE id = $1 AND status = 'pending'`,
|
||||
[id],
|
||||
);
|
||||
}
|
||||
|
||||
async rejectPending(id: string): Promise<boolean> {
|
||||
const result = await this.database.query(
|
||||
'attachments.reject_pending',
|
||||
`UPDATE attachments SET status = 'rejected', updated_at = now()
|
||||
WHERE id = $1 AND status = 'pending'`,
|
||||
[id],
|
||||
);
|
||||
return result.rowCount === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a pending row out of play before its object is deleted. The object
|
||||
* is deleted only when this returns true: a row that is already `ready`
|
||||
* (its commit succeeded even if the reply was lost) keeps its object.
|
||||
*/
|
||||
async claimForCompensation(id: string): Promise<boolean> {
|
||||
const result = await this.database.query(
|
||||
'attachments.claim_for_compensation',
|
||||
`UPDATE attachments SET status = 'deleting', updated_at = now()
|
||||
WHERE id = $1 AND status = 'pending'`,
|
||||
[id],
|
||||
);
|
||||
return result.rowCount === 1;
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<AttachmentRow | undefined> {
|
||||
const result = await this.database.query<AttachmentRow>(
|
||||
'attachments.find_by_id',
|
||||
'SELECT * FROM attachments WHERE id = $1',
|
||||
[id],
|
||||
);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async findVisible(
|
||||
id: string,
|
||||
userId: string,
|
||||
): Promise<AttachmentRow | undefined> {
|
||||
const result = await this.database.query<AttachmentRow>(
|
||||
'attachments.find_visible',
|
||||
`SELECT a.* FROM attachments a ${VISIBLE_MEMBER}
|
||||
WHERE a.id = $1 AND a.status = 'ready'`,
|
||||
[id, userId],
|
||||
);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async findForComplete(
|
||||
id: string,
|
||||
userId: string,
|
||||
): Promise<AttachmentRow | undefined> {
|
||||
const result = await this.database.query<AttachmentRow>(
|
||||
'attachments.find_for_complete',
|
||||
`SELECT a.* FROM attachments a ${VISIBLE_MEMBER}
|
||||
WHERE a.id = $1 AND a.upload_mode = 'direct' AND a.owner_id = $2
|
||||
AND a.status IN ('pending', 'ready')`,
|
||||
[id, userId],
|
||||
);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async countPendingDirect(ownerId: string): Promise<number> {
|
||||
const result = await this.database.query<{ count: string }>(
|
||||
'attachments.count_pending_direct',
|
||||
`SELECT count(*) AS count FROM attachments
|
||||
WHERE owner_id = $1 AND status IN ('pending', 'rejected')
|
||||
AND upload_mode = 'direct' AND expires_at > now()`,
|
||||
[ownerId],
|
||||
);
|
||||
return Number(result.rows[0].count);
|
||||
}
|
||||
|
||||
async allLinkable(chatId: string, ids: string[]): Promise<boolean> {
|
||||
const result = await this.database.query<{ count: string }>(
|
||||
'attachments.all_linkable',
|
||||
`SELECT count(*) AS count FROM attachments
|
||||
WHERE chat_id = $1 AND status = 'ready' AND id = ANY($2::uuid[])`,
|
||||
[chatId, ids],
|
||||
);
|
||||
return Number(result.rows[0].count) === ids.length;
|
||||
}
|
||||
|
||||
async claimExpired(
|
||||
graceSeconds: number,
|
||||
limit: number,
|
||||
): Promise<{ id: string; object_key: string }[]> {
|
||||
const result = await this.database.query<{
|
||||
id: string;
|
||||
object_key: string;
|
||||
}>(
|
||||
'attachments.claim_expired',
|
||||
`UPDATE attachments SET status = 'deleting', updated_at = now()
|
||||
WHERE id IN (
|
||||
SELECT id FROM attachments
|
||||
WHERE (status IN ('pending', 'rejected')
|
||||
AND expires_at < now() - make_interval(secs => $1::double precision))
|
||||
OR (status = 'deleting' AND updated_at < now() - interval '1 minute')
|
||||
ORDER BY expires_at NULLS FIRST
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED)
|
||||
RETURNING id, object_key`,
|
||||
[graceSeconds, limit],
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
async deleteClaimed(id: string): Promise<void> {
|
||||
await this.database.query(
|
||||
'attachments.delete_claimed',
|
||||
`DELETE FROM attachments WHERE id = $1 AND status = 'deleting'`,
|
||||
[id],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { Readable } from 'node:stream';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { AttachmentRow } from './attachment.js';
|
||||
import { AttachmentsService } from './attachments.service.js';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const png = readFileSync(join(here, '../../../tests/fixtures/sample.png'));
|
||||
const lostReply = () =>
|
||||
Object.assign(new Error('Connection terminated unexpectedly'), {});
|
||||
|
||||
const settings: Record<string, number> = {
|
||||
MAX_UPLOAD_BYTES: 10_485_760,
|
||||
MAX_IMAGE_PIXELS: 40_000_000,
|
||||
UPLOAD_TIMEOUT_MS: 10_000,
|
||||
};
|
||||
|
||||
function setup(repository: Record<string, unknown>) {
|
||||
const storage = {
|
||||
objectKey: (id: string) => `attachments/${id}/original`,
|
||||
putStream: vi.fn(async (_key: string, body: Readable) => {
|
||||
for await (const _chunk of body) {
|
||||
// drain like S3 does
|
||||
}
|
||||
}),
|
||||
delete: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const service = new AttachmentsService(
|
||||
{ getOrThrow: (key: string) => settings[key] } as never,
|
||||
{
|
||||
insertPending: vi.fn(),
|
||||
deleteClaimed: vi.fn(),
|
||||
...repository,
|
||||
} as never,
|
||||
storage as never,
|
||||
{ getForUser: vi.fn() } as never,
|
||||
{ increment: vi.fn(), add: vi.fn() } as never,
|
||||
{ verify: vi.fn() } as never,
|
||||
{
|
||||
run: (_user: string, work: () => Promise<unknown>) => work(),
|
||||
} as never,
|
||||
);
|
||||
const upload = () =>
|
||||
service.uploadProxy(
|
||||
'chat',
|
||||
{ id: 'user' } as never,
|
||||
'a.png',
|
||||
'image/png',
|
||||
String(png.length),
|
||||
Readable.from([png]),
|
||||
);
|
||||
return { storage, upload };
|
||||
}
|
||||
|
||||
const readyRow = (id: string): AttachmentRow => ({
|
||||
id,
|
||||
chat_id: 'chat',
|
||||
owner_id: 'user',
|
||||
filename: 'a.png',
|
||||
content_type: 'image/png',
|
||||
upload_mode: 'proxy',
|
||||
status: 'ready',
|
||||
object_key: `attachments/${id}/original`,
|
||||
size_bytes: png.length,
|
||||
sha256: 'a'.repeat(64),
|
||||
width: 320,
|
||||
height: 200,
|
||||
expires_at: null,
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
});
|
||||
|
||||
describe('AttachmentsService compensation', () => {
|
||||
it('keeps the object and answers 201 when ready was committed but its reply was lost', async () => {
|
||||
const { storage, upload } = setup({
|
||||
markReady: vi.fn().mockRejectedValue(lostReply()),
|
||||
claimForCompensation: vi.fn().mockResolvedValue(false),
|
||||
findById: vi.fn((id: string) => Promise.resolve(readyRow(id))),
|
||||
});
|
||||
const attachment = await upload();
|
||||
expect(attachment.status).toBe('ready');
|
||||
expect(storage.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('deletes nothing while PostgreSQL is unreachable', async () => {
|
||||
const { storage, upload } = setup({
|
||||
markReady: vi.fn().mockRejectedValue(lostReply()),
|
||||
claimForCompensation: vi.fn().mockRejectedValue(lostReply()),
|
||||
findById: vi.fn().mockRejectedValue(lostReply()),
|
||||
});
|
||||
await expect(upload()).rejects.toThrow();
|
||||
expect(storage.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('deletes the object only after claiming the pending row', async () => {
|
||||
const order: string[] = [];
|
||||
const { storage, upload } = setup({
|
||||
markReady: vi.fn().mockRejectedValue(lostReply()),
|
||||
claimForCompensation: vi.fn(async () => {
|
||||
order.push('claim');
|
||||
return true;
|
||||
}),
|
||||
deleteClaimed: vi.fn(async () => {
|
||||
order.push('delete-row');
|
||||
}),
|
||||
});
|
||||
storage.delete.mockImplementation(async () => {
|
||||
order.push('delete-object');
|
||||
});
|
||||
await expect(upload()).rejects.toThrow();
|
||||
expect(order).toEqual(['claim', 'delete-object', 'delete-row']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,373 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
HttpException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
PayloadTooLargeException,
|
||||
ServiceUnavailableException,
|
||||
UnsupportedMediaTypeException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { pipeline, Readable, Transform } from 'node:stream';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { ChatsService } from '../chats/chats.service.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import { ObjectStorage } from '../storage/object-storage.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import {
|
||||
toAttachment,
|
||||
type Attachment,
|
||||
type AttachmentRow,
|
||||
} from './attachment.js';
|
||||
import { validateFilename } from './filename.js';
|
||||
import {
|
||||
ImageHeader,
|
||||
ImageInspector,
|
||||
ImageRejectedError,
|
||||
} from './image/image-inspector.js';
|
||||
import { AttachmentsRepository } from './attachments.repository.js';
|
||||
import { ImageDecoder } from './image/image-decoder.js';
|
||||
import { UploadSlots } from './upload-slots.js';
|
||||
|
||||
const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']);
|
||||
|
||||
export function mediaType(header: unknown): string | undefined {
|
||||
if (typeof header !== 'string') return undefined;
|
||||
return header.split(';', 1)[0].trim().toLowerCase();
|
||||
}
|
||||
|
||||
export function imageRejection(error: ImageRejectedError): HttpException {
|
||||
return error.reason === 'too_many_pixels'
|
||||
? new PayloadTooLargeException(error.message)
|
||||
: new UnsupportedMediaTypeException(error.message);
|
||||
}
|
||||
|
||||
class UploadInterruptedError extends Error {}
|
||||
|
||||
@Injectable()
|
||||
export class AttachmentsService {
|
||||
private readonly logger = new Logger(AttachmentsService.name);
|
||||
private readonly maxUploadBytes: number;
|
||||
private readonly maxPixels: number;
|
||||
private readonly uploadTimeoutMs: number;
|
||||
|
||||
constructor(
|
||||
config: ConfigService<AppConfig>,
|
||||
private readonly repository: AttachmentsRepository,
|
||||
private readonly storage: ObjectStorage,
|
||||
private readonly chats: ChatsService,
|
||||
private readonly metrics: MetricsService,
|
||||
private readonly decoder: ImageDecoder,
|
||||
private readonly slots: UploadSlots,
|
||||
) {
|
||||
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
|
||||
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
|
||||
this.uploadTimeoutMs = config.getOrThrow('UPLOAD_TIMEOUT_MS');
|
||||
}
|
||||
|
||||
async uploadProxy(
|
||||
chatId: string,
|
||||
user: User,
|
||||
rawFilename: unknown,
|
||||
contentTypeHeader: unknown,
|
||||
contentLengthHeader: unknown,
|
||||
body: Readable | undefined,
|
||||
): Promise<Attachment> {
|
||||
const filename = validateFilename(rawFilename);
|
||||
const declared = mediaType(contentTypeHeader);
|
||||
if (declared === undefined || !MEDIA_TYPES.has(declared))
|
||||
throw new UnsupportedMediaTypeException(
|
||||
'Content-Type must be image/png or image/jpeg',
|
||||
);
|
||||
if (
|
||||
typeof contentLengthHeader !== 'string' ||
|
||||
!/^\d{1,15}$/u.test(contentLengthHeader)
|
||||
)
|
||||
throw new BadRequestException('Content-Length is required');
|
||||
const contentLength = Number(contentLengthHeader);
|
||||
if (contentLength === 0 || body === undefined)
|
||||
throw new UnsupportedMediaTypeException('Image body is empty');
|
||||
if (contentLength > this.maxUploadBytes)
|
||||
throw new PayloadTooLargeException('Image is too large');
|
||||
|
||||
return this.slots.run(user.id, async () => {
|
||||
await this.chats.getForUser(chatId, user);
|
||||
return this.receive(
|
||||
chatId,
|
||||
user,
|
||||
filename,
|
||||
declared,
|
||||
contentLength,
|
||||
body,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private async receive(
|
||||
chatId: string,
|
||||
user: User,
|
||||
filename: string,
|
||||
declared: string,
|
||||
contentLength: number,
|
||||
body: Readable,
|
||||
): Promise<Attachment> {
|
||||
const controller = new AbortController();
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
body.destroy(new Error('upload timeout'));
|
||||
controller.abort();
|
||||
}, this.uploadTimeoutMs);
|
||||
const iterator = body[Symbol.asyncIterator]() as AsyncIterator<Buffer>;
|
||||
const next = async (): Promise<IteratorResult<Buffer>> => {
|
||||
try {
|
||||
return await iterator.next();
|
||||
} catch {
|
||||
throw new UploadInterruptedError('Upload was interrupted');
|
||||
}
|
||||
};
|
||||
|
||||
const inspector = new ImageInspector(this.maxPixels);
|
||||
const head: Buffer[] = [];
|
||||
let id: string | undefined;
|
||||
let key = '';
|
||||
let rejection: unknown;
|
||||
try {
|
||||
// Header phase: nothing exists in the database or S3 yet. It is
|
||||
// bounded by Content-Length (<= MAX_UPLOAD_BYTES): a JPEG may carry
|
||||
// megabytes of APPn metadata before its frame header.
|
||||
try {
|
||||
while (inspector.header === undefined) {
|
||||
const step = await next();
|
||||
if (step.done) {
|
||||
inspector.finish();
|
||||
throw new ImageRejectedError(
|
||||
'unsupported_media_type',
|
||||
'Image header is missing',
|
||||
);
|
||||
}
|
||||
head.push(step.value);
|
||||
inspector.push(step.value);
|
||||
}
|
||||
} catch (error) {
|
||||
throw this.mapUploadError(error, timedOut);
|
||||
}
|
||||
const header = inspector.header as ImageHeader;
|
||||
if (header.contentType !== declared)
|
||||
throw new UnsupportedMediaTypeException(
|
||||
'Image content does not match Content-Type',
|
||||
);
|
||||
|
||||
id = randomUUID();
|
||||
key = this.storage.objectKey(id);
|
||||
await this.repository.insertPending({
|
||||
id,
|
||||
chatId,
|
||||
ownerId: user.id,
|
||||
filename,
|
||||
contentType: declared,
|
||||
uploadMode: 'proxy',
|
||||
objectKey: key,
|
||||
sizeBytes: null,
|
||||
sha256: null,
|
||||
ttlMs: this.uploadTimeoutMs,
|
||||
});
|
||||
|
||||
const sha256 = createHash('sha256');
|
||||
const decoder = this.decoder;
|
||||
// Copy for the full decode check; bounded by MAX_UPLOAD_BYTES and
|
||||
// UPLOAD_MAX_IN_FLIGHT, released as soon as the decode starts.
|
||||
const copy: Buffer[] = [];
|
||||
let total = 0;
|
||||
let allSent = false;
|
||||
const account = (chunk: Buffer, inspect: boolean): boolean => {
|
||||
total += chunk.length;
|
||||
if (total > contentLength)
|
||||
throw new UploadInterruptedError(
|
||||
'Body exceeds Content-Length',
|
||||
);
|
||||
if (inspect) inspector.push(chunk);
|
||||
sha256.update(chunk);
|
||||
this.metrics.add('attachments.proxy.bytes_in', chunk.length);
|
||||
copy.push(chunk);
|
||||
return total === contentLength;
|
||||
};
|
||||
// Validate before the last bytes reach S3: it cannot commit an object
|
||||
// whose body is incomplete, so an invalid image never becomes an object.
|
||||
const finalize = async (): Promise<void> => {
|
||||
inspector.finish();
|
||||
const data = Buffer.concat(copy, total);
|
||||
copy.length = 0;
|
||||
await decoder.verify(data, controller.signal);
|
||||
// From here S3 may receive the whole body and commit the object
|
||||
// even if this request fails or times out afterwards.
|
||||
allSent = true;
|
||||
};
|
||||
async function* generate(): AsyncGenerator<Buffer> {
|
||||
for (const chunk of head) {
|
||||
if (account(chunk, false)) await finalize();
|
||||
yield chunk;
|
||||
}
|
||||
for (;;) {
|
||||
const step = await next();
|
||||
if (step.done) break;
|
||||
if (account(step.value, true)) await finalize();
|
||||
yield step.value;
|
||||
}
|
||||
if (total < contentLength)
|
||||
throw new UploadInterruptedError('Upload was interrupted');
|
||||
}
|
||||
const readable = Readable.from(
|
||||
(async function* () {
|
||||
try {
|
||||
yield* generate();
|
||||
} catch (error) {
|
||||
rejection = error;
|
||||
throw error;
|
||||
}
|
||||
})(),
|
||||
);
|
||||
|
||||
// A failing body must abort the PUT at once: the SDK does not end a
|
||||
// request whose Content-Length can no longer be satisfied, it would
|
||||
// hang until the request timeout. The error itself is reported via
|
||||
// `rejection`; the listener also keeps a late error from crashing us.
|
||||
readable.on('error', () => controller.abort());
|
||||
let claimed = false;
|
||||
let stored = false;
|
||||
try {
|
||||
await this.storage.putStream(
|
||||
key,
|
||||
readable,
|
||||
contentLength,
|
||||
declared,
|
||||
controller.signal,
|
||||
);
|
||||
this.metrics.add(
|
||||
'attachments.proxy.bytes_to_s3',
|
||||
contentLength,
|
||||
);
|
||||
stored = true;
|
||||
const row = await this.repository.markReady(id, {
|
||||
sizeBytes: total,
|
||||
sha256: sha256.digest('hex'),
|
||||
width: header.width,
|
||||
height: header.height,
|
||||
});
|
||||
if (row === undefined) {
|
||||
claimed = true;
|
||||
throw new ServiceUnavailableException();
|
||||
}
|
||||
this.metrics.increment('attachments.upload.created');
|
||||
return toAttachment(row);
|
||||
} catch (error) {
|
||||
readable.destroy();
|
||||
if (!claimed) {
|
||||
// After the last byte was handed to S3, a PUT aborted on our
|
||||
// side may still be committed by S3 after our DELETE: keep the
|
||||
// row so the sweeper deletes the key again later.
|
||||
const outcome = await this.compensate(id, key, {
|
||||
keepRow: allSent && !stored,
|
||||
});
|
||||
// markReady failed on our side, but the row is no longer
|
||||
// pending: the commit may have succeeded with its reply lost.
|
||||
// If so, the upload is complete and 201 is the truth.
|
||||
if (outcome === 'not_pending' && stored) {
|
||||
const row = await this.repository
|
||||
.findById(id)
|
||||
.catch(() => undefined);
|
||||
if (row?.status === 'ready') {
|
||||
this.metrics.increment(
|
||||
'attachments.upload.recovered',
|
||||
);
|
||||
return toAttachment(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw this.mapUploadError(rejection ?? error, timedOut);
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
private mapUploadError(error: unknown, timedOut: boolean): unknown {
|
||||
if (error instanceof ImageRejectedError) return imageRejection(error);
|
||||
if (error instanceof UploadInterruptedError || timedOut)
|
||||
return new BadRequestException('Upload was interrupted');
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Undoes an upload that did not reach `ready`. The row is claimed first
|
||||
* (pending -> deleting) and the object is deleted only after a successful
|
||||
* claim: if PostgreSQL committed `ready` but the reply was lost, the claim
|
||||
* matches nothing and the object stays. If PostgreSQL is unreachable,
|
||||
* nothing is deleted; the sweeper finishes the job after expiry + grace
|
||||
* (a row stuck in `deleting` is re-claimed after a minute).
|
||||
*/
|
||||
async compensate(
|
||||
id: string,
|
||||
key: string,
|
||||
options: { keepRow?: boolean } = {},
|
||||
): Promise<'compensated' | 'not_pending' | 'deferred'> {
|
||||
try {
|
||||
if (!(await this.repository.claimForCompensation(id))) {
|
||||
this.metrics.increment('attachments.compensation_skipped');
|
||||
return 'not_pending';
|
||||
}
|
||||
await this.storage.delete(key);
|
||||
// A kept `deleting` row is re-claimed by the sweeper after a minute,
|
||||
// which deletes the key once more and only then the row.
|
||||
if (!options.keepRow) await this.repository.deleteClaimed(id);
|
||||
this.metrics.increment('attachments.compensated');
|
||||
return 'compensated';
|
||||
} catch (error) {
|
||||
this.metrics.increment('attachments.compensation_deferred');
|
||||
this.logger.warn(
|
||||
`Compensation of attachment ${id} deferred: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
return 'deferred';
|
||||
}
|
||||
}
|
||||
|
||||
async getMetadata(id: string, user: User): Promise<Attachment> {
|
||||
const row = await this.repository.findVisible(id, user.id);
|
||||
if (!row) throw new NotFoundException();
|
||||
return toAttachment(row);
|
||||
}
|
||||
|
||||
async openContent(
|
||||
id: string,
|
||||
user: User,
|
||||
variant: string | undefined,
|
||||
): Promise<{ row: AttachmentRow; stream: Readable }> {
|
||||
if (variant !== undefined && variant !== 'original') {
|
||||
if (['thumbnail', 'crop', 'optimized'].includes(variant))
|
||||
throw new NotFoundException();
|
||||
throw new BadRequestException('variant is invalid');
|
||||
}
|
||||
const row = await this.repository.findVisible(id, user.id);
|
||||
if (!row) throw new NotFoundException();
|
||||
const source = await this.storage.getStream(row.object_key);
|
||||
if (source === null) {
|
||||
this.metrics.increment('attachments.object_missing');
|
||||
this.logger.error(
|
||||
`Object for ready attachment ${row.id} is missing in storage`,
|
||||
);
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
const metrics = this.metrics;
|
||||
const counter = new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
metrics.add('attachments.download.bytes_out', chunk.length);
|
||||
callback(null, chunk);
|
||||
},
|
||||
});
|
||||
pipeline(source, counter, () => undefined);
|
||||
return { row, stream: counter };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
import {
|
||||
ConflictException,
|
||||
HttpException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
PayloadTooLargeException,
|
||||
UnsupportedMediaTypeException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { ChatsService } from '../chats/chats.service.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import {
|
||||
ObjectStorage,
|
||||
ObjectStorageUnavailableError,
|
||||
} from '../storage/object-storage.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import {
|
||||
toAttachment,
|
||||
type Attachment,
|
||||
type AttachmentRow,
|
||||
} from './attachment.js';
|
||||
import { AttachmentsRepository } from './attachments.repository.js';
|
||||
import { imageRejection } from './attachments.service.js';
|
||||
import type { CreateDirectUploadDto } from './dto/create-direct-upload.dto.js';
|
||||
import { validateFilename } from './filename.js';
|
||||
import { ImageDecoder } from './image/image-decoder.js';
|
||||
import { UploadSlots } from './upload-slots.js';
|
||||
import {
|
||||
ImageInspector,
|
||||
ImageRejectedError,
|
||||
type ImageHeader,
|
||||
} from './image/image-inspector.js';
|
||||
|
||||
export type DirectUpload = {
|
||||
attachment_id: string;
|
||||
method: 'PUT';
|
||||
url: string;
|
||||
headers: Record<string, string>;
|
||||
expires_at: string;
|
||||
};
|
||||
|
||||
const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']);
|
||||
|
||||
@Injectable()
|
||||
export class DirectUploadsService {
|
||||
private readonly maxUploadBytes: number;
|
||||
private readonly maxPixels: number;
|
||||
private readonly uploadTimeoutMs: number;
|
||||
private readonly ttlSeconds: number;
|
||||
private readonly maxPending: number;
|
||||
|
||||
constructor(
|
||||
config: ConfigService<AppConfig>,
|
||||
private readonly repository: AttachmentsRepository,
|
||||
private readonly storage: ObjectStorage,
|
||||
private readonly chats: ChatsService,
|
||||
private readonly metrics: MetricsService,
|
||||
private readonly decoder: ImageDecoder,
|
||||
private readonly slots: UploadSlots,
|
||||
) {
|
||||
this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES');
|
||||
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
|
||||
this.uploadTimeoutMs = config.getOrThrow('UPLOAD_TIMEOUT_MS');
|
||||
this.ttlSeconds = config.getOrThrow('DIRECT_UPLOAD_URL_TTL_SECONDS');
|
||||
this.maxPending = config.getOrThrow(
|
||||
'DIRECT_UPLOAD_MAX_PENDING_PER_USER',
|
||||
);
|
||||
}
|
||||
|
||||
async init(
|
||||
chatId: string,
|
||||
user: User,
|
||||
dto: CreateDirectUploadDto,
|
||||
): Promise<DirectUpload> {
|
||||
const filename = validateFilename(dto.filename);
|
||||
if (!MEDIA_TYPES.has(dto.content_type))
|
||||
throw new UnsupportedMediaTypeException(
|
||||
'content_type must be image/png or image/jpeg',
|
||||
);
|
||||
if (dto.size_bytes > this.maxUploadBytes)
|
||||
throw new PayloadTooLargeException('Image is too large');
|
||||
await this.chats.getForUser(chatId, user);
|
||||
if (
|
||||
(await this.repository.countPendingDirect(user.id)) >=
|
||||
this.maxPending
|
||||
)
|
||||
throw new HttpException(
|
||||
{
|
||||
message: 'Too many unfinished direct uploads',
|
||||
retryAfter: this.ttlSeconds,
|
||||
},
|
||||
429,
|
||||
);
|
||||
|
||||
const id = randomUUID();
|
||||
const key = this.storage.objectKey(id);
|
||||
await this.repository.insertPending({
|
||||
id,
|
||||
chatId,
|
||||
ownerId: user.id,
|
||||
filename,
|
||||
contentType: dto.content_type,
|
||||
uploadMode: 'direct',
|
||||
objectKey: key,
|
||||
sizeBytes: dto.size_bytes,
|
||||
sha256: dto.sha256,
|
||||
ttlMs: this.ttlSeconds * 1000,
|
||||
});
|
||||
const checksum = Buffer.from(dto.sha256, 'hex').toString('base64');
|
||||
let url: string;
|
||||
try {
|
||||
url = await this.storage.presignPut(key, {
|
||||
contentType: dto.content_type,
|
||||
contentLength: dto.size_bytes,
|
||||
checksumSha256Base64: checksum,
|
||||
expiresInSeconds: this.ttlSeconds,
|
||||
});
|
||||
} catch (error) {
|
||||
await this.repository.deletePending(id);
|
||||
throw error;
|
||||
}
|
||||
this.metrics.increment('attachments.direct.initiated');
|
||||
return {
|
||||
attachment_id: id,
|
||||
method: 'PUT',
|
||||
url,
|
||||
headers: {
|
||||
'Content-Type': dto.content_type,
|
||||
'x-amz-checksum-sha256': checksum,
|
||||
},
|
||||
expires_at: new Date(
|
||||
Date.now() + this.ttlSeconds * 1000,
|
||||
).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
async complete(attachmentId: string, user: User): Promise<Attachment> {
|
||||
const row = await this.repository.findForComplete(
|
||||
attachmentId,
|
||||
user.id,
|
||||
);
|
||||
if (!row) throw new NotFoundException();
|
||||
if (row.status === 'ready') return toAttachment(row);
|
||||
return this.slots.run(user.id, () => this.verifyAndMarkReady(row));
|
||||
}
|
||||
|
||||
private async verifyAndMarkReady(row: AttachmentRow): Promise<Attachment> {
|
||||
const size = Number(row.size_bytes);
|
||||
const expectedChecksum = Buffer.from(
|
||||
row.sha256 as string,
|
||||
'hex',
|
||||
).toString('base64');
|
||||
const head = await this.storage.head(row.object_key);
|
||||
if (head === null)
|
||||
throw new ConflictException('Upload has not been received');
|
||||
if (head.size !== size || head.checksumSha256 !== expectedChecksum) {
|
||||
await this.reject(row);
|
||||
throw new ConflictException(
|
||||
'Uploaded object does not match the declaration',
|
||||
);
|
||||
}
|
||||
|
||||
let header: ImageHeader;
|
||||
try {
|
||||
header = await this.verifyObject(row.object_key, size);
|
||||
} catch (error) {
|
||||
if (error instanceof ImageRejectedError) {
|
||||
await this.reject(row);
|
||||
throw imageRejection(error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (header.contentType !== row.content_type) {
|
||||
await this.reject(row);
|
||||
throw new UnsupportedMediaTypeException(
|
||||
'Image content does not match content_type',
|
||||
);
|
||||
}
|
||||
const ready = await this.repository.markReady(row.id, {
|
||||
sizeBytes: size,
|
||||
sha256: row.sha256 as string,
|
||||
width: header.width,
|
||||
height: header.height,
|
||||
});
|
||||
if (!ready) {
|
||||
// A parallel complete of the same upload won: answer like a repeat.
|
||||
const current = await this.repository.findForComplete(
|
||||
row.id,
|
||||
row.owner_id,
|
||||
);
|
||||
if (current?.status === 'ready') return toAttachment(current);
|
||||
throw new ConflictException('Upload is no longer pending');
|
||||
}
|
||||
this.metrics.increment('attachments.direct.completed');
|
||||
return toAttachment(ready);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the whole object: a correct signed checksum only proves that the
|
||||
* bytes are the ones the client declared, not that they form an image. The
|
||||
* stream goes through ImageInspector (structure, CRCs, completeness), then
|
||||
* the copy is fully decoded. Memory is bounded like a proxy upload.
|
||||
*/
|
||||
private async verifyObject(
|
||||
key: string,
|
||||
size: number,
|
||||
): Promise<ImageHeader> {
|
||||
// Same deadline as a proxy upload: a slow or hung read releases its slot.
|
||||
const signal = AbortSignal.timeout(this.uploadTimeoutMs);
|
||||
const stream = await this.storage.getStream(key, signal);
|
||||
if (stream === null)
|
||||
throw new ConflictException('Upload has not been received');
|
||||
const inspector = new ImageInspector(this.maxPixels);
|
||||
const chunks: Buffer[] = [];
|
||||
let read = 0;
|
||||
try {
|
||||
for await (const chunk of stream as AsyncIterable<Buffer>) {
|
||||
read += chunk.length;
|
||||
if (read > size)
|
||||
throw new ImageRejectedError(
|
||||
'unsupported_media_type',
|
||||
'Object is larger than declared',
|
||||
);
|
||||
inspector.push(chunk);
|
||||
chunks.push(chunk);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ImageRejectedError) throw error;
|
||||
// The object stream broke mid-read (S3 outage, timeout): the image
|
||||
// was not judged, so this is an outage, not a client error.
|
||||
throw new ObjectStorageUnavailableError();
|
||||
} finally {
|
||||
stream.destroy();
|
||||
this.metrics.add('attachments.direct.verify_bytes', read);
|
||||
}
|
||||
const header = inspector.finish();
|
||||
const data = Buffer.concat(chunks, read);
|
||||
chunks.length = 0;
|
||||
await this.decoder.verify(data, signal);
|
||||
return header;
|
||||
}
|
||||
|
||||
/**
|
||||
* A rejected claim keeps its row (status `rejected`, original expiry) while
|
||||
* the signed URL may still be used: a later re-PUT would otherwise leave an
|
||||
* object that no row refers to. The sweeper removes both after expiry + grace.
|
||||
*/
|
||||
private async reject(row: AttachmentRow): Promise<void> {
|
||||
// Row first: a row that is not pending any more (ready after a parallel
|
||||
// complete, or claimed by the sweeper) keeps its object.
|
||||
if (!(await this.repository.rejectPending(row.id))) return;
|
||||
try {
|
||||
await this.storage.delete(row.object_key);
|
||||
} catch {
|
||||
// The sweeper deletes the object again after expiry.
|
||||
}
|
||||
this.metrics.increment('attachments.direct.rejected');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { IsInt, IsString, Matches, Min } from 'class-validator';
|
||||
|
||||
export class CreateDirectUploadDto {
|
||||
@IsString()
|
||||
filename!: string;
|
||||
|
||||
@IsString()
|
||||
content_type!: string;
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
size_bytes!: number;
|
||||
|
||||
@Matches(/^[a-f0-9]{64}$/u)
|
||||
sha256!: string;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
const FORBIDDEN =
|
||||
// eslint-disable-next-line no-control-regex
|
||||
/[/\\\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/u;
|
||||
|
||||
/** The name is stored as-is and used for display only, never in paths or keys. */
|
||||
export function validateFilename(value: unknown): string {
|
||||
if (typeof value !== 'string') throw invalid();
|
||||
const length = [...value].length;
|
||||
if (
|
||||
length < 1 ||
|
||||
length > 255 ||
|
||||
/^\s*$/u.test(value) ||
|
||||
value === '.' ||
|
||||
value === '..' ||
|
||||
FORBIDDEN.test(value)
|
||||
)
|
||||
throw invalid();
|
||||
return value;
|
||||
}
|
||||
|
||||
function invalid(): BadRequestException {
|
||||
return new BadRequestException('filename is invalid');
|
||||
}
|
||||
|
||||
export function contentDisposition(filename: string): string {
|
||||
const fallback = filename.replace(/[^\x20-\x7e]|["\\]/gu, '_');
|
||||
const encoded = encodeURIComponent(filename).replace(
|
||||
/['()*]/gu,
|
||||
(character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
);
|
||||
return `inline; filename="${fallback}"; filename*=UTF-8''${encoded}`;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { jpegWithoutScanData } from '../../../test/support/jpeg.js';
|
||||
import {
|
||||
maxPixelsRgba16Png,
|
||||
noisePng,
|
||||
pngWithGarbageIdat,
|
||||
} from '../../../test/support/png.js';
|
||||
import { ImageDecoder } from './image-decoder.js';
|
||||
import { ImageInspector, ImageRejectedError } from './image-inspector.js';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const png = readFileSync(join(here, '../../../../tests/fixtures/sample.png'));
|
||||
const jpeg = readFileSync(join(here, '../../../test/fixtures/sample.jpg'));
|
||||
const progressive = readFileSync(
|
||||
join(here, '../../../test/fixtures/sample-progressive.jpg'),
|
||||
);
|
||||
|
||||
const settings: Record<string, number> = {
|
||||
MAX_IMAGE_PIXELS: 40_000_000,
|
||||
IMAGE_DECODE_MAX_CONCURRENT: 1,
|
||||
};
|
||||
const decoder = new ImageDecoder(
|
||||
{ getOrThrow: (key: string) => settings[key] } as never,
|
||||
{ increment: () => undefined, add: () => undefined } as never,
|
||||
);
|
||||
|
||||
describe('ImageDecoder', () => {
|
||||
it('accepts valid PNG and JPEG files, also concurrently', async () => {
|
||||
await Promise.all(
|
||||
[png, jpeg, progressive, noisePng(1_048_576)].map((data) =>
|
||||
decoder.verify(data),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// These files pass the structural inspector; only a decode catches them.
|
||||
it.each([
|
||||
['PNG with a garbage zlib stream', pngWithGarbageIdat()],
|
||||
['JPEG without scan data', jpegWithoutScanData(jpeg)],
|
||||
[
|
||||
'progressive JPEG without scan data',
|
||||
jpegWithoutScanData(progressive),
|
||||
],
|
||||
])('rejects a %s', async (_name, data) => {
|
||||
const inspector = new ImageInspector(40_000_000);
|
||||
inspector.push(data);
|
||||
expect(inspector.finish().width).toBe(320);
|
||||
await expect(decoder.verify(data)).rejects.toBeInstanceOf(
|
||||
ImageRejectedError,
|
||||
);
|
||||
});
|
||||
|
||||
it('accepts the heaviest valid input: 40 MP RGBA 16-bit', async () => {
|
||||
await decoder.verify(await maxPixelsRgba16Png());
|
||||
});
|
||||
|
||||
it('drops an aborted waiter from the queue without running its decode', async () => {
|
||||
const busy = decoder.verify(noisePng(4_000_000));
|
||||
const controller = new AbortController();
|
||||
const waiting = decoder.verify(png, controller.signal);
|
||||
controller.abort();
|
||||
await expect(waiting).rejects.toMatchObject({ status: 503 });
|
||||
await busy;
|
||||
// The slot was not leaked: the next decode runs.
|
||||
await decoder.verify(png);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import {
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
Logger,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import sharp from 'sharp';
|
||||
import type { AppConfig } from '../../config/app-config.schema.js';
|
||||
import { MetricsService } from '../../metrics/metrics.service.js';
|
||||
import { ImageRejectedError } from './image-inspector.js';
|
||||
|
||||
// One libvips worker per decode and no operation cache: decodes are one-off,
|
||||
// and memory must stay predictable under the per-replica limit.
|
||||
sharp.cache(false);
|
||||
sharp.concurrency(1);
|
||||
|
||||
// Failures of the replica itself, not of the image: they must not turn into a
|
||||
// client 415. libvips spills large images to a temp file unless
|
||||
// VIPS_DISC_THRESHOLD (compose.yaml) keeps them in memory; a full /tmp or an
|
||||
// allocation failure ends up here.
|
||||
const SERVER_FAULT =
|
||||
/no space left|out of memory|unable to allocate|cannot allocate|write failed|unable to open|tmp/iu;
|
||||
|
||||
/**
|
||||
* Full decode check. ImageInspector only proves the container structure
|
||||
* (signature, chunk CRCs, markers, dimensions); a PNG with a garbage zlib stream
|
||||
* or a JPEG without scan data passes it. Decoding every scanline with
|
||||
* failOn=warning rejects those, including truncated or corrupted compressed
|
||||
* data. A downscale to a thumbnail is the sink: it decodes all input but keeps
|
||||
* far less in memory than a full-size pipeline (measured in
|
||||
* evidence/lab4/decode-memory.txt). Decodes are bounded by
|
||||
* IMAGE_DECODE_MAX_CONCURRENT; a waiter whose request was aborted leaves the
|
||||
* queue and releases its buffer.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ImageDecoder {
|
||||
private readonly logger = new Logger(ImageDecoder.name);
|
||||
private readonly maxPixels: number;
|
||||
private readonly maxConcurrent: number;
|
||||
private active = 0;
|
||||
private readonly waiting = new Set<() => void>();
|
||||
|
||||
constructor(
|
||||
config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {
|
||||
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
|
||||
this.maxConcurrent = config.getOrThrow('IMAGE_DECODE_MAX_CONCURRENT');
|
||||
}
|
||||
|
||||
async verify(data: Buffer, signal?: AbortSignal): Promise<void> {
|
||||
await this.acquire(signal);
|
||||
const started = performance.now();
|
||||
try {
|
||||
await sharp(data, {
|
||||
failOn: 'warning',
|
||||
sequentialRead: true,
|
||||
limitInputPixels: this.maxPixels,
|
||||
})
|
||||
.resize(64, 64, { fit: 'inside' })
|
||||
.toBuffer();
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
if (SERVER_FAULT.test(message)) {
|
||||
this.metrics.increment('attachments.decode.server_error');
|
||||
this.logger.error(
|
||||
`Image decode failed on the server: ${message}`,
|
||||
);
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
this.metrics.increment('attachments.decode.rejected');
|
||||
throw new ImageRejectedError(
|
||||
'unsupported_media_type',
|
||||
'Image data cannot be decoded',
|
||||
);
|
||||
} finally {
|
||||
this.metrics.add(
|
||||
'attachments.decode.ms',
|
||||
performance.now() - started,
|
||||
);
|
||||
this.release();
|
||||
}
|
||||
}
|
||||
|
||||
private acquire(signal?: AbortSignal): Promise<void> {
|
||||
const abandoned = new ServiceUnavailableException(
|
||||
'Image check was abandoned',
|
||||
);
|
||||
if (signal?.aborted) return Promise.reject(abandoned);
|
||||
if (this.active < this.maxConcurrent) {
|
||||
this.active += 1;
|
||||
return Promise.resolve();
|
||||
}
|
||||
const { promise, resolve, reject } = Promise.withResolvers<void>();
|
||||
const cancel = () => {
|
||||
this.waiting.delete(grant);
|
||||
reject(abandoned);
|
||||
};
|
||||
const grant = () => {
|
||||
signal?.removeEventListener('abort', cancel);
|
||||
resolve();
|
||||
};
|
||||
this.waiting.add(grant);
|
||||
signal?.addEventListener('abort', cancel, { once: true });
|
||||
return promise;
|
||||
}
|
||||
|
||||
private release(): void {
|
||||
const next = this.waiting.values().next();
|
||||
if (next.done) {
|
||||
this.active -= 1;
|
||||
return;
|
||||
}
|
||||
this.waiting.delete(next.value);
|
||||
next.value();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { noisePng, pixelBombPng } from '../../../test/support/png.js';
|
||||
import { ImageInspector, ImageRejectedError } from './image-inspector.js';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const png = readFileSync(join(here, '../../../../tests/fixtures/sample.png'));
|
||||
const jpeg = readFileSync(join(here, '../../../test/fixtures/sample.jpg'));
|
||||
const progressive = readFileSync(
|
||||
join(here, '../../../test/fixtures/sample-progressive.jpg'),
|
||||
);
|
||||
const MAX = 40_000_000;
|
||||
|
||||
function inspect(data: Buffer, step = data.length, max = MAX) {
|
||||
const inspector = new ImageInspector(max);
|
||||
for (let offset = 0; offset < data.length; offset += step)
|
||||
inspector.push(data.subarray(offset, offset + step));
|
||||
return inspector.finish();
|
||||
}
|
||||
|
||||
function rejection(action: () => unknown): ImageRejectedError {
|
||||
try {
|
||||
action();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ImageRejectedError);
|
||||
return error as ImageRejectedError;
|
||||
}
|
||||
throw new Error('expected rejection');
|
||||
}
|
||||
|
||||
describe('ImageInspector', () => {
|
||||
it.each([
|
||||
['png', png, 'image/png'],
|
||||
['jpeg', jpeg, 'image/jpeg'],
|
||||
['progressive jpeg', progressive, 'image/jpeg'],
|
||||
])('accepts %s and reports its size', (_name, data, contentType) => {
|
||||
const expected = { contentType, width: 320, height: 200 };
|
||||
expect(inspect(data)).toEqual(expected);
|
||||
expect(inspect(data, 1)).toEqual(expected);
|
||||
expect(inspect(data, 7)).toEqual(expected);
|
||||
});
|
||||
|
||||
it('rejects truncated files on finish', () => {
|
||||
for (const data of [png, jpeg, progressive])
|
||||
for (const cut of [10, 40, data.length - 100, data.length - 1]) {
|
||||
const reason = rejection(() =>
|
||||
inspect(data.subarray(0, cut)),
|
||||
).reason;
|
||||
expect(reason).toBe('unsupported_media_type');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a flipped byte inside IDAT by checksum', () => {
|
||||
const damaged = Buffer.from(png);
|
||||
damaged[Math.floor(png.length / 2)] ^= 0xff;
|
||||
expect(rejection(() => inspect(damaged)).reason).toBe(
|
||||
'unsupported_media_type',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a pixel bomb right after IHDR, before any IDAT', () => {
|
||||
const bomb = pixelBombPng();
|
||||
const inspector = new ImageInspector(MAX);
|
||||
// signature + IHDR chunk = 8 + 25 bytes
|
||||
const reason = rejection(() =>
|
||||
inspector.push(bomb.subarray(0, 33)),
|
||||
).reason;
|
||||
expect(reason).toBe('too_many_pixels');
|
||||
expect(inspector.header).toBeUndefined();
|
||||
});
|
||||
|
||||
it('applies the pixel limit to JPEG frame headers', () => {
|
||||
expect(rejection(() => inspect(jpeg, jpeg.length, 63_999)).reason).toBe(
|
||||
'too_many_pixels',
|
||||
);
|
||||
expect(inspect(jpeg, jpeg.length, 64_000).width).toBe(320);
|
||||
});
|
||||
|
||||
it('rejects foreign formats and trailing data after IEND', () => {
|
||||
for (const data of [
|
||||
Buffer.from('GIF89a' + 'x'.repeat(40)),
|
||||
Buffer.from('plain text, not an image'),
|
||||
Buffer.alloc(0),
|
||||
])
|
||||
expect(rejection(() => inspect(data)).reason).toBe(
|
||||
'unsupported_media_type',
|
||||
);
|
||||
expect(
|
||||
rejection(() => inspect(Buffer.concat([png, Buffer.from([0])])))
|
||||
.reason,
|
||||
).toBe('unsupported_media_type');
|
||||
});
|
||||
|
||||
it('accepts padded and noise PNGs of exact sizes', () => {
|
||||
for (const size of [131_072, 1_048_576]) {
|
||||
const data = noisePng(size);
|
||||
expect(data.length).toBe(size);
|
||||
expect(inspect(data).width).toBe(1024);
|
||||
}
|
||||
});
|
||||
|
||||
it('tolerates trailing data after JPEG EOI', () => {
|
||||
expect(
|
||||
inspect(Buffer.concat([jpeg, Buffer.from('MPF trailer')])).height,
|
||||
).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,387 @@
|
||||
import { crc32 } from 'node:zlib';
|
||||
|
||||
export type ImageHeader = {
|
||||
contentType: 'image/png' | 'image/jpeg';
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
export class ImageRejectedError extends Error {
|
||||
constructor(
|
||||
readonly reason: 'unsupported_media_type' | 'too_many_pixels',
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ImageRejectedError';
|
||||
}
|
||||
}
|
||||
|
||||
const PNG_SIGNATURE = Buffer.from([
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
||||
]);
|
||||
const PNG_MAX_DIMENSION = 2 ** 31 - 1;
|
||||
const PNG_BIT_DEPTHS: Record<number, readonly number[]> = {
|
||||
0: [1, 2, 4, 8, 16],
|
||||
2: [8, 16],
|
||||
3: [1, 2, 4, 8],
|
||||
4: [8, 16],
|
||||
6: [8, 16],
|
||||
};
|
||||
const SOF_MARKERS = new Set([
|
||||
0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce,
|
||||
0xcf,
|
||||
]);
|
||||
|
||||
type State =
|
||||
| 'start'
|
||||
// PNG
|
||||
| 'png_chunk_head'
|
||||
| 'png_ihdr'
|
||||
| 'png_skip'
|
||||
| 'png_crc'
|
||||
| 'png_done'
|
||||
// JPEG
|
||||
| 'jpeg_marker'
|
||||
| 'jpeg_code'
|
||||
| 'jpeg_length'
|
||||
| 'jpeg_sof'
|
||||
| 'jpeg_skip'
|
||||
| 'jpeg_entropy'
|
||||
| 'jpeg_entropy_ff'
|
||||
| 'jpeg_trailer';
|
||||
|
||||
function unsupported(message: string): ImageRejectedError {
|
||||
return new ImageRejectedError('unsupported_media_type', message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Streaming structural validator for PNG and JPEG. It never buffers the body:
|
||||
* only fixed-size fields (chunk headers, IHDR, SOF) are accumulated, and
|
||||
* nothing is decompressed. It is the early gate (type, dimensions, pixel limit
|
||||
* before anything is stored), not proof of a valid image: compressed pixel
|
||||
* data is checked by ImageDecoder.
|
||||
*/
|
||||
export class ImageInspector {
|
||||
private state: State = 'start';
|
||||
private imageHeader: ImageHeader | undefined;
|
||||
|
||||
// Accumulator for fixed-length fields.
|
||||
private field = Buffer.alloc(16);
|
||||
private fieldNeed = 0;
|
||||
private fieldLength = 0;
|
||||
|
||||
// Remaining bytes to skip in png_skip / jpeg_skip.
|
||||
private skip = 0;
|
||||
|
||||
// PNG
|
||||
private chunkType = '';
|
||||
private chunkLength = 0;
|
||||
private crc = 0;
|
||||
private firstChunk = true;
|
||||
private seenIdat = false;
|
||||
|
||||
// JPEG
|
||||
private marker = 0;
|
||||
private scans = 0;
|
||||
private afterSkip: State = 'jpeg_marker';
|
||||
|
||||
constructor(private readonly maxPixels: number) {}
|
||||
|
||||
get header(): ImageHeader | undefined {
|
||||
return this.imageHeader;
|
||||
}
|
||||
|
||||
push(chunk: Buffer): void {
|
||||
let offset = 0;
|
||||
while (offset < chunk.length) offset = this.step(chunk, offset);
|
||||
}
|
||||
|
||||
finish(): ImageHeader {
|
||||
const done = this.state === 'png_done' || this.state === 'jpeg_trailer';
|
||||
if (!done || this.imageHeader === undefined)
|
||||
throw unsupported('Image data is incomplete');
|
||||
return this.imageHeader;
|
||||
}
|
||||
|
||||
private collect(need: number): void {
|
||||
this.fieldNeed = need;
|
||||
this.fieldLength = 0;
|
||||
}
|
||||
|
||||
/** Copies up to fieldNeed bytes; returns new offset and whether complete. */
|
||||
private fill(chunk: Buffer, offset: number): [number, boolean] {
|
||||
const take = Math.min(
|
||||
this.fieldNeed - this.fieldLength,
|
||||
chunk.length - offset,
|
||||
);
|
||||
chunk.copy(this.field, this.fieldLength, offset, offset + take);
|
||||
this.fieldLength += take;
|
||||
return [offset + take, this.fieldLength === this.fieldNeed];
|
||||
}
|
||||
|
||||
private step(chunk: Buffer, offset: number): number {
|
||||
switch (this.state) {
|
||||
case 'start':
|
||||
return this.stepStart(chunk, offset);
|
||||
case 'png_chunk_head':
|
||||
case 'png_ihdr':
|
||||
case 'png_crc':
|
||||
case 'jpeg_length':
|
||||
case 'jpeg_sof': {
|
||||
const [next, complete] = this.fill(chunk, offset);
|
||||
if (complete) this.fieldDone();
|
||||
return next;
|
||||
}
|
||||
case 'png_skip':
|
||||
case 'jpeg_skip': {
|
||||
const take = Math.min(this.skip, chunk.length - offset);
|
||||
if (this.state === 'png_skip')
|
||||
this.crc = crc32(
|
||||
chunk.subarray(offset, offset + take),
|
||||
this.crc,
|
||||
);
|
||||
this.skip -= take;
|
||||
if (this.skip === 0) this.skipDone();
|
||||
return offset + take;
|
||||
}
|
||||
case 'png_done':
|
||||
throw unsupported('Data after the PNG end chunk');
|
||||
case 'jpeg_marker':
|
||||
if (chunk[offset] !== 0xff)
|
||||
throw unsupported('Unexpected byte between JPEG segments');
|
||||
this.state = 'jpeg_code';
|
||||
return offset + 1;
|
||||
case 'jpeg_code':
|
||||
this.onMarkerCode(chunk[offset]);
|
||||
return offset + 1;
|
||||
case 'jpeg_entropy': {
|
||||
const next = chunk.indexOf(0xff, offset);
|
||||
if (next === -1) return chunk.length;
|
||||
this.state = 'jpeg_entropy_ff';
|
||||
return next + 1;
|
||||
}
|
||||
case 'jpeg_entropy_ff': {
|
||||
const byte = chunk[offset];
|
||||
if (byte === 0xff) return offset + 1;
|
||||
if (byte === 0x00 || (byte >= 0xd0 && byte <= 0xd7)) {
|
||||
this.state = 'jpeg_entropy';
|
||||
return offset + 1;
|
||||
}
|
||||
this.onMarkerCode(byte);
|
||||
return offset + 1;
|
||||
}
|
||||
case 'jpeg_trailer':
|
||||
return chunk.length;
|
||||
}
|
||||
}
|
||||
|
||||
private stepStart(chunk: Buffer, offset: number): number {
|
||||
// Accumulate until the type is certain: 3 bytes for JPEG, 8 for PNG.
|
||||
if (this.fieldLength === 0 && this.fieldNeed === 0) this.collect(8);
|
||||
const have = this.fieldLength;
|
||||
const take = Math.min(this.fieldNeed - have, chunk.length - offset);
|
||||
chunk.copy(this.field, have, offset, offset + take);
|
||||
this.fieldLength += take;
|
||||
const first = this.field[0];
|
||||
if (first === 0xff) {
|
||||
if (this.fieldLength >= 3) {
|
||||
if (this.field[1] !== 0xd8 || this.field[2] !== 0xff)
|
||||
throw unsupported('Not a JPEG file');
|
||||
// The third byte opens the next marker.
|
||||
this.state = 'jpeg_code';
|
||||
this.fieldNeed = 0;
|
||||
this.fieldLength = 0;
|
||||
return offset + (3 - have);
|
||||
}
|
||||
return offset + take;
|
||||
}
|
||||
if (first === PNG_SIGNATURE[0]) {
|
||||
for (let index = 0; index < this.fieldLength; index += 1)
|
||||
if (this.field[index] !== PNG_SIGNATURE[index])
|
||||
throw unsupported('Not a PNG file');
|
||||
if (this.fieldLength === 8) {
|
||||
this.state = 'png_chunk_head';
|
||||
this.collect(8);
|
||||
}
|
||||
return offset + take;
|
||||
}
|
||||
throw unsupported('Unsupported image format');
|
||||
}
|
||||
|
||||
private fieldDone(): void {
|
||||
switch (this.state) {
|
||||
case 'png_chunk_head':
|
||||
this.onPngChunkHead();
|
||||
return;
|
||||
case 'png_ihdr':
|
||||
this.crc = crc32(this.field.subarray(0, 13), this.crc);
|
||||
this.parseIhdr();
|
||||
this.state = 'png_crc';
|
||||
this.collect(4);
|
||||
return;
|
||||
case 'png_crc': {
|
||||
const expected = this.field.readUInt32BE(0);
|
||||
if (this.crc >>> 0 !== expected)
|
||||
throw unsupported('PNG chunk checksum mismatch');
|
||||
this.onPngChunkEnd();
|
||||
return;
|
||||
}
|
||||
case 'jpeg_length':
|
||||
this.onJpegLength();
|
||||
return;
|
||||
case 'jpeg_sof':
|
||||
this.onJpegSof();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private skipDone(): void {
|
||||
if (this.state === 'png_skip') {
|
||||
this.state = 'png_crc';
|
||||
this.collect(4);
|
||||
} else {
|
||||
this.state = this.afterSkip;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- PNG ----
|
||||
|
||||
private onPngChunkHead(): void {
|
||||
const length = this.field.readUInt32BE(0);
|
||||
const type = this.field.toString('latin1', 4, 8);
|
||||
if (length > PNG_MAX_DIMENSION)
|
||||
throw unsupported('PNG chunk is too long');
|
||||
if (!/^[A-Za-z]{4}$/u.test(type))
|
||||
throw unsupported('PNG chunk type is invalid');
|
||||
if (this.firstChunk) {
|
||||
if (type !== 'IHDR' || length !== 13)
|
||||
throw unsupported('PNG must start with IHDR');
|
||||
this.firstChunk = false;
|
||||
} else if (type === 'IHDR') {
|
||||
throw unsupported('Duplicate PNG IHDR');
|
||||
}
|
||||
if (type === 'IEND') {
|
||||
if (length !== 0 || !this.seenIdat)
|
||||
throw unsupported('PNG IEND is invalid');
|
||||
}
|
||||
if (type === 'IDAT') this.seenIdat = true;
|
||||
this.chunkType = type;
|
||||
this.chunkLength = length;
|
||||
this.crc = crc32(this.field.subarray(4, 8), 0);
|
||||
if (type === 'IHDR') {
|
||||
this.state = 'png_ihdr';
|
||||
this.collect(13);
|
||||
} else if (length === 0) {
|
||||
this.state = 'png_crc';
|
||||
this.collect(4);
|
||||
} else {
|
||||
this.state = 'png_skip';
|
||||
this.skip = length;
|
||||
}
|
||||
}
|
||||
|
||||
private parseIhdr(): void {
|
||||
const width = this.field.readUInt32BE(0);
|
||||
const height = this.field.readUInt32BE(4);
|
||||
const bitDepth = this.field[8];
|
||||
const colorType = this.field[9];
|
||||
if (width < 1 || width > PNG_MAX_DIMENSION)
|
||||
throw unsupported('PNG width is invalid');
|
||||
if (height < 1 || height > PNG_MAX_DIMENSION)
|
||||
throw unsupported('PNG height is invalid');
|
||||
if (!PNG_BIT_DEPTHS[colorType]?.includes(bitDepth))
|
||||
throw unsupported('PNG color type / bit depth is invalid');
|
||||
if (this.field[10] !== 0 || this.field[11] !== 0)
|
||||
throw unsupported('PNG compression/filter method is invalid');
|
||||
if (this.field[12] > 1)
|
||||
throw unsupported('PNG interlace method is invalid');
|
||||
this.pendingHeader = { contentType: 'image/png', width, height };
|
||||
}
|
||||
|
||||
private pendingHeader: ImageHeader | undefined;
|
||||
|
||||
private onPngChunkEnd(): void {
|
||||
if (this.chunkType === 'IHDR' && this.pendingHeader) {
|
||||
const { width, height } = this.pendingHeader;
|
||||
if (width * height > this.maxPixels)
|
||||
throw new ImageRejectedError(
|
||||
'too_many_pixels',
|
||||
'Image has too many pixels',
|
||||
);
|
||||
this.imageHeader = this.pendingHeader;
|
||||
}
|
||||
if (this.chunkType === 'IEND') {
|
||||
this.state = 'png_done';
|
||||
return;
|
||||
}
|
||||
this.state = 'png_chunk_head';
|
||||
this.collect(8);
|
||||
}
|
||||
|
||||
// ---- JPEG ----
|
||||
|
||||
private onMarkerCode(code: number): void {
|
||||
if (code === 0xff) return; // fill byte
|
||||
this.marker = code;
|
||||
if (code === 0x00 || code === 0xd8)
|
||||
throw unsupported('Unexpected JPEG marker');
|
||||
if (code === 0x01 || (code >= 0xd0 && code <= 0xd7)) {
|
||||
this.state = 'jpeg_marker';
|
||||
return;
|
||||
}
|
||||
if (code === 0xd9) {
|
||||
if (this.imageHeader === undefined || this.scans === 0)
|
||||
throw unsupported('JPEG ended before image data');
|
||||
this.state = 'jpeg_trailer';
|
||||
return;
|
||||
}
|
||||
if (code === 0xda && this.imageHeader === undefined)
|
||||
throw unsupported('JPEG scan before frame header');
|
||||
this.state = 'jpeg_length';
|
||||
this.collect(2);
|
||||
}
|
||||
|
||||
private onJpegLength(): void {
|
||||
const length = this.field.readUInt16BE(0);
|
||||
if (length < 2) throw unsupported('JPEG segment length is invalid');
|
||||
const dataLength = length - 2;
|
||||
if (SOF_MARKERS.has(this.marker)) {
|
||||
if (this.imageHeader !== undefined || this.pendingHeader)
|
||||
throw unsupported('Duplicate JPEG frame header');
|
||||
if (dataLength < 6) throw unsupported('JPEG frame header is short');
|
||||
this.skip = dataLength - 6;
|
||||
this.afterSkip = 'jpeg_marker';
|
||||
this.state = 'jpeg_sof';
|
||||
this.collect(6);
|
||||
return;
|
||||
}
|
||||
if (this.marker === 0xda) {
|
||||
this.scans += 1;
|
||||
this.afterSkip = 'jpeg_entropy';
|
||||
} else {
|
||||
this.afterSkip = 'jpeg_marker';
|
||||
}
|
||||
if (dataLength === 0) this.state = this.afterSkip;
|
||||
else {
|
||||
this.skip = dataLength;
|
||||
this.state = 'jpeg_skip';
|
||||
}
|
||||
}
|
||||
|
||||
private onJpegSof(): void {
|
||||
const height = this.field.readUInt16BE(1);
|
||||
const width = this.field.readUInt16BE(3);
|
||||
if (width === 0 || height === 0 || this.field[5] === 0)
|
||||
throw unsupported('JPEG dimensions are invalid');
|
||||
if (width * height > this.maxPixels)
|
||||
throw new ImageRejectedError(
|
||||
'too_many_pixels',
|
||||
'Image has too many pixels',
|
||||
);
|
||||
this.imageHeader = { contentType: 'image/jpeg', width, height };
|
||||
if (this.skip === 0) this.state = 'jpeg_marker';
|
||||
else this.state = 'jpeg_skip';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Request of the upload route; see the onRequest hook in main.ts. */
|
||||
export type UploadRequest = {
|
||||
method: string;
|
||||
routeOptions?: { url?: string };
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
/** Content-Type as sent by the client (the header itself is rewritten). */
|
||||
uploadContentType?: string | string[];
|
||||
body?: unknown;
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { UploadSlots } from './upload-slots.js';
|
||||
|
||||
const slots = (max: number, perUser: number) =>
|
||||
new UploadSlots({
|
||||
getOrThrow: (key: string) =>
|
||||
key === 'UPLOAD_MAX_IN_FLIGHT' ? max : perUser,
|
||||
} as never);
|
||||
|
||||
function hold() {
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
return { work: () => promise, release: resolve };
|
||||
}
|
||||
|
||||
describe('UploadSlots', () => {
|
||||
it('caps one user without starving others, and frees slots after work', async () => {
|
||||
const limiter = slots(10, 2);
|
||||
const held = [hold(), hold()];
|
||||
const running = held.map((h) => limiter.run('a', h.work));
|
||||
await expect(limiter.run('a', async () => 'x')).rejects.toMatchObject({
|
||||
status: 429,
|
||||
});
|
||||
await expect(limiter.run('b', async () => 'ok')).resolves.toBe('ok');
|
||||
held.forEach((h) => h.release());
|
||||
await Promise.all(running);
|
||||
await expect(limiter.run('a', async () => 'again')).resolves.toBe(
|
||||
'again',
|
||||
);
|
||||
});
|
||||
|
||||
it('applies the replica-wide cap across users', async () => {
|
||||
const limiter = slots(2, 2);
|
||||
const held = [hold(), hold()];
|
||||
const running = [
|
||||
limiter.run('a', held[0].work),
|
||||
limiter.run('b', held[1].work),
|
||||
];
|
||||
await expect(limiter.run('c', async () => 'x')).rejects.toMatchObject({
|
||||
status: 429,
|
||||
});
|
||||
held.forEach((h) => h.release());
|
||||
await Promise.all(running);
|
||||
});
|
||||
|
||||
it('releases a slot when the work fails', async () => {
|
||||
const limiter = slots(1, 1);
|
||||
await expect(
|
||||
limiter.run('a', async () => {
|
||||
throw new Error('boom');
|
||||
}),
|
||||
).rejects.toThrow('boom');
|
||||
await expect(limiter.run('a', async () => 'ok')).resolves.toBe('ok');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { HttpException, Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
|
||||
/**
|
||||
* Per-replica caps on requests that hold an image in memory (proxy upload,
|
||||
* direct complete): each may keep up to MAX_UPLOAD_BYTES for the decode check.
|
||||
* The per-user cap keeps one client (e.g. slow senders holding slots until
|
||||
* UPLOAD_TIMEOUT_MS) from starving everyone else.
|
||||
*/
|
||||
@Injectable()
|
||||
export class UploadSlots {
|
||||
private inFlight = 0;
|
||||
private readonly perUser = new Map<string, number>();
|
||||
private readonly max: number;
|
||||
private readonly maxPerUser: number;
|
||||
|
||||
constructor(config: ConfigService<AppConfig>) {
|
||||
this.max = config.getOrThrow('UPLOAD_MAX_IN_FLIGHT');
|
||||
this.maxPerUser = config.getOrThrow('UPLOAD_MAX_IN_FLIGHT_PER_USER');
|
||||
}
|
||||
|
||||
async run<T>(userId: string, work: () => Promise<T>): Promise<T> {
|
||||
const mine = this.perUser.get(userId) ?? 0;
|
||||
if (this.inFlight >= this.max || mine >= this.maxPerUser)
|
||||
throw new HttpException(
|
||||
{ message: 'Too many concurrent uploads', retryAfter: 1 },
|
||||
429,
|
||||
);
|
||||
this.inFlight += 1;
|
||||
this.perUser.set(userId, mine + 1);
|
||||
try {
|
||||
return await work();
|
||||
} finally {
|
||||
this.inFlight -= 1;
|
||||
const left = (this.perUser.get(userId) ?? 1) - 1;
|
||||
if (left === 0) this.perUser.delete(userId);
|
||||
else this.perUser.set(userId, left);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export type Chat = {
|
||||
id: string;
|
||||
title: string;
|
||||
member_ids: string[];
|
||||
created_at: string;
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
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 { 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) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() body: CreateChatDto, @CurrentUser() currentUser: User) {
|
||||
return this.chatsService.create(body, currentUser);
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
@Get(':chatId')
|
||||
get(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@CurrentUser() currentUser: User,
|
||||
) {
|
||||
return this.chatsService.getForUser(chatId, currentUser);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
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, DatabaseModule, RedisModule, MetricsModule],
|
||||
controllers: [ChatsController],
|
||||
providers: [ChatsRepository, ChatsService],
|
||||
exports: [ChatsService],
|
||||
})
|
||||
export class ChatsModule {}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { BadRequestException, Injectable } 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 {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
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,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { encodeCursor, decodeCursor } from '../common/http/cursor.js';
|
||||
import type { Page } from '../common/http/page.js';
|
||||
import type { User } from '../users/user.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) {}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
async getForUser(chatId: string, currentUser: User): Promise<Chat> {
|
||||
const chat = await this.chatsRepository.findForUser(
|
||||
chatId,
|
||||
currentUser,
|
||||
);
|
||||
if (!chat) throw new NotFoundException();
|
||||
return chat;
|
||||
}
|
||||
|
||||
async listForUser(
|
||||
currentUser: User,
|
||||
limit: number,
|
||||
cursorValue?: string,
|
||||
): Promise<Page<Chat>> {
|
||||
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,26 @@
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
ArrayMinSize,
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsString,
|
||||
IsUUID,
|
||||
Matches,
|
||||
} from 'class-validator';
|
||||
import { CodePointLength } from '../../common/validation/code-point-length.js';
|
||||
|
||||
export class CreateChatDto {
|
||||
@IsString()
|
||||
@CodePointLength(1, 100)
|
||||
@Matches(/\S/, {
|
||||
message: 'title must contain a non-whitespace character',
|
||||
})
|
||||
title: string;
|
||||
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ArrayMaxSize(100)
|
||||
@ArrayUnique()
|
||||
@IsUUID('4', { each: true })
|
||||
member_ids: string[];
|
||||
}
|
||||
@@ -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!;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,85 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
ServiceUnavailableException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
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';
|
||||
import { MetricsService } from '../../metrics/metrics.service.js';
|
||||
|
||||
@Injectable()
|
||||
export class CurrentUserGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly redis: RedisClient,
|
||||
private readonly users: UsersService,
|
||||
private readonly metrics: MetricsService,
|
||||
) {}
|
||||
|
||||
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"',
|
||||
});
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export type ApiErrorBody = {
|
||||
error: {
|
||||
code: string;
|
||||
message: string;
|
||||
request_id: string;
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,181 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { AppConfig } from '../../config/app-config.schema.js';
|
||||
import { resolveInstanceId } from '../../config/instance-id.js';
|
||||
import type { ApiErrorBody } from './api-error.js';
|
||||
|
||||
type RequestWithId = { requestId?: string; method?: string; url?: string };
|
||||
type ExceptionBody = {
|
||||
message?: unknown;
|
||||
challenge?: unknown;
|
||||
retryAfter?: unknown;
|
||||
};
|
||||
|
||||
// Connection/session loss codes reported by node-postgres and the network layer.
|
||||
const UNAVAILABLE_ERROR_CODES: Record<string, true> = {
|
||||
ECONNREFUSED: true,
|
||||
ECONNRESET: true,
|
||||
ENOTFOUND: true,
|
||||
ETIMEDOUT: true,
|
||||
EPIPE: true,
|
||||
'08000': true,
|
||||
'08001': true,
|
||||
'08003': true,
|
||||
'08004': true,
|
||||
'08006': true,
|
||||
'57P01': true,
|
||||
'57P02': true,
|
||||
'57P03': true,
|
||||
'53300': true,
|
||||
// Transient aborts: the statement was cancelled by statement_timeout, the
|
||||
// transaction was rolled back by a serialization failure or a deadlock. The
|
||||
// work was never confirmed, so callers see a retryable 503 instead of an
|
||||
// internal error. Without this, such an abort would be recorded as the final
|
||||
// result of an idempotent operation.
|
||||
'57014': true,
|
||||
'40001': true,
|
||||
'40P01': true,
|
||||
};
|
||||
|
||||
// Some driver failures carry no `code` at all: node-postgres raises plain errors
|
||||
// when a connection dies or its pool attempt times out, and node-redis reports a
|
||||
// closed socket the same way. Without these patterns a stopped database would
|
||||
// surface as an internal fault instead of a bounded outage.
|
||||
const UNAVAILABLE_ERROR_MESSAGES = [
|
||||
'Connection terminated unexpectedly',
|
||||
'Connection terminated due to connection timeout',
|
||||
'timeout exceeded when trying to connect',
|
||||
'Client has encountered a connection error and is not queryable',
|
||||
'Socket closed unexpectedly',
|
||||
'Connection is closed',
|
||||
];
|
||||
|
||||
function isDependencyOutage(exception: unknown): boolean {
|
||||
if (typeof exception !== 'object' || exception === null) return false;
|
||||
const code = (exception as { code?: unknown }).code;
|
||||
if (typeof code === 'string' && UNAVAILABLE_ERROR_CODES[code] === true)
|
||||
return true;
|
||||
const message = (exception as { message?: unknown }).message;
|
||||
return (
|
||||
typeof message === 'string' &&
|
||||
UNAVAILABLE_ERROR_MESSAGES.some((pattern) => message.includes(pattern))
|
||||
);
|
||||
}
|
||||
|
||||
function errorCodeForStatus(status: number): string {
|
||||
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 {
|
||||
private readonly logger = new Logger(ApiExceptionFilter.name);
|
||||
// Guards and pipes run before interceptors, so an error response may be the
|
||||
// first thing the filter writes: it must carry the replica identity too.
|
||||
private readonly instanceId: string;
|
||||
|
||||
constructor(
|
||||
private readonly adapterHost: HttpAdapterHost,
|
||||
config: ConfigService<AppConfig>,
|
||||
) {
|
||||
this.instanceId = resolveInstanceId(config);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
let status = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
let message = 'Internal server error';
|
||||
let challenge: string | undefined;
|
||||
let retryAfter = 1;
|
||||
if (exception instanceof HttpException) {
|
||||
status = exception.getStatus();
|
||||
const body = exception.getResponse();
|
||||
const details: ExceptionBody =
|
||||
typeof body === 'object' && body !== null
|
||||
? (body as ExceptionBody)
|
||||
: {};
|
||||
const rawMessage =
|
||||
'message' in details ? details.message : undefined;
|
||||
challenge =
|
||||
typeof details.challenge === 'string'
|
||||
? details.challenge
|
||||
: undefined;
|
||||
if (
|
||||
typeof details.retryAfter === 'number' &&
|
||||
Number.isFinite(details.retryAfter) &&
|
||||
details.retryAfter >= 1
|
||||
)
|
||||
retryAfter = Math.ceil(details.retryAfter);
|
||||
message = Array.isArray(rawMessage)
|
||||
? rawMessage.join('; ')
|
||||
: typeof rawMessage === 'string'
|
||||
? rawMessage
|
||||
: 'Request failed';
|
||||
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';
|
||||
this.logger.warn(
|
||||
`Dependency outage on ${request.method ?? ''} ${request.url ?? ''}: ${exception instanceof Error ? exception.message : 'unknown error'}`,
|
||||
);
|
||||
} else {
|
||||
this.logger.error(
|
||||
`Unhandled exception on ${request.method ?? ''} ${request.url ?? ''}`,
|
||||
exception instanceof Error
|
||||
? exception.stack
|
||||
: String(exception),
|
||||
);
|
||||
}
|
||||
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);
|
||||
}
|
||||
if (status === HttpStatus.TOO_MANY_REQUESTS)
|
||||
adapter.setHeader(response, 'Retry-After', String(retryAfter));
|
||||
adapter.setHeader(response, 'X-Request-Id', requestId);
|
||||
adapter.setHeader(response, 'X-Instance-Id', this.instanceId);
|
||||
const payload: ApiErrorBody = {
|
||||
error: {
|
||||
code: errorCodeForStatus(status),
|
||||
message,
|
||||
request_id: requestId,
|
||||
},
|
||||
};
|
||||
adapter.reply(response, payload, status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { decodeCursor, encodeCursor } from './cursor.js';
|
||||
|
||||
const scope = 'messages:6f1c2a3e-1111-4222-8333-444455556666';
|
||||
|
||||
function encode(createdAt: string, cursorScope = scope): string {
|
||||
return encodeCursor({
|
||||
scope: cursorScope,
|
||||
created_at: createdAt,
|
||||
id: randomUUID(),
|
||||
});
|
||||
}
|
||||
|
||||
describe('decodeCursor', () => {
|
||||
it('accepts valid instants and normalizes them to canonical milliseconds', () => {
|
||||
const accepted: Array<[string, string]> = [
|
||||
['2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'],
|
||||
['2026-01-01T00:00:00Z', '2026-01-01T00:00:00.000Z'],
|
||||
['2026-01-01T00:00:00.999999Z', '2026-01-01T00:00:00.999Z'],
|
||||
['2024-02-29T23:59:59.000Z', '2024-02-29T23:59:59.000Z'],
|
||||
['2026-12-31T23:59:59.999Z', '2026-12-31T23:59:59.999Z'],
|
||||
];
|
||||
for (const [createdAt, expected] of accepted) {
|
||||
const decoded = decodeCursor(encode(createdAt), scope);
|
||||
expect(decoded.created_at).toBe(expected);
|
||||
expect(decoded.scope).toBe(scope);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects calendar dates that the platform parser rolls over', () => {
|
||||
// 2026-02-31 would silently become 2026-03-03 and then fail inside SQL.
|
||||
for (const createdAt of [
|
||||
'2026-02-31T00:00:00.000Z',
|
||||
'2025-02-29T00:00:00.000Z',
|
||||
'2026-04-31T00:00:00.000Z',
|
||||
'2026-06-31T12:00:00.000Z',
|
||||
]) {
|
||||
expect(() => decodeCursor(encode(createdAt), scope)).toThrow(
|
||||
BadRequestException,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects out-of-range and malformed timestamps', () => {
|
||||
for (const createdAt of [
|
||||
'2026-01-01T24:00:00.000Z',
|
||||
'2026-01-01T00:00:60.000Z',
|
||||
'2026-13-01T00:00:00.000Z',
|
||||
'2026-00-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00',
|
||||
'2026-01-01T00:00:00+02:00',
|
||||
'2026-1-1T00:00:00.000Z',
|
||||
'2026-01-01',
|
||||
'not-a-timestamp',
|
||||
]) {
|
||||
expect(() => decodeCursor(encode(createdAt), scope)).toThrow(
|
||||
BadRequestException,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a cursor from another scope, a malformed id, and non-cursor input', () => {
|
||||
expect(() =>
|
||||
decodeCursor(
|
||||
encode('2026-01-01T00:00:00.000Z', 'messages:other'),
|
||||
scope,
|
||||
),
|
||||
).toThrow(BadRequestException);
|
||||
expect(() =>
|
||||
decodeCursor(
|
||||
encodeCursor({
|
||||
scope,
|
||||
created_at: '2026-01-01T00:00:00.000Z',
|
||||
id: 'not-a-uuid',
|
||||
}),
|
||||
scope,
|
||||
),
|
||||
).toThrow(BadRequestException);
|
||||
expect(() => decodeCursor('not-a-cursor', scope)).toThrow(
|
||||
BadRequestException,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { isValid, parseISO } from 'date-fns';
|
||||
|
||||
export type Cursor = {
|
||||
scope: string;
|
||||
created_at: string;
|
||||
id: string;
|
||||
};
|
||||
|
||||
// Format check for the canonical API shape: `Date.prototype.toISOString()` with
|
||||
// optional fractional seconds. Explicit ranges reject values such as 24:00:00.
|
||||
// Calendar validity (2026-02-31, 2025-02-29, 2026-04-31) is checked by
|
||||
// date-fns `parseISO`, which refuses impossible dates that the platform parser
|
||||
// would silently roll over into another day.
|
||||
const CURSOR_TIMESTAMP =
|
||||
/^\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$/u;
|
||||
|
||||
export function encodeCursor(cursor: Cursor): string {
|
||||
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 ||
|
||||
!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(
|
||||
parsed.id,
|
||||
) ||
|
||||
!CURSOR_TIMESTAMP.test(parsed.created_at)
|
||||
)
|
||||
throw new Error('invalid cursor');
|
||||
const instant = parseISO(parsed.created_at);
|
||||
if (!isValid(instant)) throw new Error('invalid cursor');
|
||||
|
||||
return {
|
||||
scope: parsed.scope,
|
||||
created_at: instant.toISOString(),
|
||||
id: parsed.id,
|
||||
};
|
||||
} catch {
|
||||
throw new BadRequestException('Invalid cursor');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export type Page<T> = {
|
||||
items: T[];
|
||||
next_cursor: string | null;
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { finalize, Observable } from 'rxjs';
|
||||
import type { AppConfig } from '../../config/app-config.schema.js';
|
||||
import { resolveInstanceId } from '../../config/instance-id.js';
|
||||
import { MetricsService } from '../../metrics/metrics.service.js';
|
||||
|
||||
type RequestWithId = { requestId?: string };
|
||||
|
||||
@Injectable()
|
||||
export class RequestIdInterceptor implements NestInterceptor {
|
||||
// Resolved once: the identity must be stable for the whole process lifetime,
|
||||
// otherwise a client cannot tell whether it moved to another replica.
|
||||
private readonly instanceId: string;
|
||||
|
||||
constructor(
|
||||
private readonly adapterHost: HttpAdapterHost,
|
||||
private readonly metrics: MetricsService,
|
||||
config: ConfigService<AppConfig>,
|
||||
) {
|
||||
this.instanceId = resolveInstanceId(config);
|
||||
}
|
||||
|
||||
intercept(
|
||||
context: ExecutionContext,
|
||||
next: CallHandler,
|
||||
): Observable<unknown> {
|
||||
const request = context.switchToHttp().getRequest<RequestWithId>();
|
||||
const response = context.switchToHttp().getResponse<unknown>();
|
||||
const requestId = randomUUID();
|
||||
const startedAt = performance.now();
|
||||
request.requestId = requestId;
|
||||
this.adapterHost.httpAdapter.setHeader(
|
||||
response,
|
||||
'X-Request-Id',
|
||||
requestId,
|
||||
);
|
||||
this.adapterHost.httpAdapter.setHeader(
|
||||
response,
|
||||
'X-Instance-Id',
|
||||
this.instanceId,
|
||||
);
|
||||
this.metrics.increment('request_count');
|
||||
return next
|
||||
.handle()
|
||||
.pipe(
|
||||
finalize(() =>
|
||||
this.metrics.observeLatency(performance.now() - startedAt),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { validate } from 'class-validator';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { CodePointLength } from './code-point-length.js';
|
||||
|
||||
class Sample {
|
||||
@CodePointLength(3, 5)
|
||||
value!: string;
|
||||
}
|
||||
|
||||
async function fails(value: unknown): Promise<boolean> {
|
||||
const sample = new Sample();
|
||||
(sample as { value: unknown }).value = value;
|
||||
const errors = await validate(sample);
|
||||
return errors.length > 0;
|
||||
}
|
||||
|
||||
describe('CodePointLength', () => {
|
||||
it('counts Unicode code points instead of UTF-16 units', async () => {
|
||||
// '🔐' is one code point but two UTF-16 units.
|
||||
expect(await fails('🔐🔐')).toBe(true);
|
||||
expect(await fails('🔐🔐🔐')).toBe(false);
|
||||
expect(await fails('🔐🔐🔐🔐🔐')).toBe(false);
|
||||
expect(await fails('🔐🔐🔐🔐🔐🔐')).toBe(true);
|
||||
// Combining marks are separate code points, not grapheme clusters:
|
||||
// three 'é' sequences are six code points and exceed the maximum.
|
||||
expect(await fails('e\u0301e\u0301')).toBe(false);
|
||||
expect(await fails('e\u0301e\u0301e\u0301')).toBe(true);
|
||||
});
|
||||
|
||||
it('applies to BMP text boundaries', async () => {
|
||||
expect(await fails('ab')).toBe(true);
|
||||
expect(await fails('abc')).toBe(false);
|
||||
expect(await fails('abcde')).toBe(false);
|
||||
expect(await fails('abcdef')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects empty and non-string values', async () => {
|
||||
expect(await fails('')).toBe(true);
|
||||
expect(await fails(undefined)).toBe(true);
|
||||
expect(await fails(12345)).toBe(true);
|
||||
expect(await fails(['a', 'b', 'c'])).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
registerDecorator,
|
||||
ValidatorConstraint,
|
||||
type ValidationArguments,
|
||||
type ValidatorConstraintInterface,
|
||||
} from 'class-validator';
|
||||
|
||||
// JSON Schema (and the course contract) measure string lengths in Unicode code
|
||||
// points, while String.prototype.length counts UTF-16 units: one emoji outside
|
||||
// the BMP is two units. `@Length` therefore accepted an 11-emoji password
|
||||
// (22 units) and rejected 4000 emoji (8000 units), so these fields use an
|
||||
// explicit code-point validator instead.
|
||||
@ValidatorConstraint({ name: 'codePointLength', async: false })
|
||||
class CodePointLengthConstraint implements ValidatorConstraintInterface {
|
||||
validate(value: unknown, args: ValidationArguments): boolean {
|
||||
const [min, max] = args.constraints as [number, number];
|
||||
if (typeof value !== 'string') return false;
|
||||
const length = [...value].length;
|
||||
return length >= min && length <= max;
|
||||
}
|
||||
|
||||
defaultMessage(args: ValidationArguments): string {
|
||||
const [min, max] = args.constraints as [number, number];
|
||||
return `${args.property} must be between ${min} and ${max} code points`;
|
||||
}
|
||||
}
|
||||
|
||||
export function CodePointLength(min: number, max: number): PropertyDecorator {
|
||||
return (target, propertyKey) => {
|
||||
registerDecorator({
|
||||
name: 'codePointLength',
|
||||
target: target.constructor,
|
||||
propertyName: String(propertyKey),
|
||||
constraints: [min, max],
|
||||
validator: CodePointLengthConstraint,
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -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,186 @@
|
||||
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,
|
||||
),
|
||||
// Бюджет зависимостей в /health/ready: LB проверяет ту же ручку, поэтому
|
||||
// проба готовности обязана уложиться в timeout check HAProxy (500 ms).
|
||||
HEALTH_TIMEOUT_MS: numeric('HEALTH_TIMEOUT_MS', 1, undefined, 400),
|
||||
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),
|
||||
INSTANCE_ID: z.string().min(1).optional(),
|
||||
IDEMPOTENCY_TTL_SECONDS: numeric(
|
||||
'IDEMPOTENCY_TTL_SECONDS',
|
||||
60,
|
||||
undefined,
|
||||
86400,
|
||||
),
|
||||
S3_ENDPOINT: requiredString('S3_ENDPOINT'),
|
||||
S3_PUBLIC_ENDPOINT: requiredString('S3_PUBLIC_ENDPOINT'),
|
||||
S3_REGION: z.string().min(1).default('us-east-1'),
|
||||
S3_BUCKET: requiredString('S3_BUCKET'),
|
||||
S3_ACCESS_KEY_ID: requiredString('S3_ACCESS_KEY_ID'),
|
||||
S3_SECRET_ACCESS_KEY: requiredString('S3_SECRET_ACCESS_KEY'),
|
||||
S3_CONNECT_TIMEOUT_MS: numeric(
|
||||
'S3_CONNECT_TIMEOUT_MS',
|
||||
1,
|
||||
undefined,
|
||||
1000,
|
||||
),
|
||||
S3_REQUEST_TIMEOUT_MS: numeric(
|
||||
'S3_REQUEST_TIMEOUT_MS',
|
||||
1,
|
||||
undefined,
|
||||
15000,
|
||||
),
|
||||
MAX_UPLOAD_BYTES: numeric('MAX_UPLOAD_BYTES', 1, 10485760, 10485760),
|
||||
MAX_IMAGE_PIXELS: numeric('MAX_IMAGE_PIXELS', 1, 40000000, 40000000),
|
||||
UPLOAD_TIMEOUT_MS: numeric('UPLOAD_TIMEOUT_MS', 1000, undefined, 25000),
|
||||
UPLOAD_MAX_IN_FLIGHT: numeric('UPLOAD_MAX_IN_FLIGHT', 1, 1024, 16),
|
||||
UPLOAD_MAX_IN_FLIGHT_PER_USER: numeric(
|
||||
'UPLOAD_MAX_IN_FLIGHT_PER_USER',
|
||||
1,
|
||||
1024,
|
||||
4,
|
||||
),
|
||||
IMAGE_DECODE_MAX_CONCURRENT: numeric(
|
||||
'IMAGE_DECODE_MAX_CONCURRENT',
|
||||
1,
|
||||
64,
|
||||
1,
|
||||
),
|
||||
// 0 отключает фоновый проход уборщика (остаётся ручной CLI).
|
||||
ATTACHMENT_SWEEP_INTERVAL_MS: numeric(
|
||||
'ATTACHMENT_SWEEP_INTERVAL_MS',
|
||||
0,
|
||||
undefined,
|
||||
60000,
|
||||
),
|
||||
ATTACHMENT_SWEEP_GRACE_SECONDS: numeric(
|
||||
'ATTACHMENT_SWEEP_GRACE_SECONDS',
|
||||
0,
|
||||
undefined,
|
||||
900,
|
||||
),
|
||||
DIRECT_UPLOAD_URL_TTL_SECONDS: numeric(
|
||||
'DIRECT_UPLOAD_URL_TTL_SECONDS',
|
||||
1,
|
||||
3600,
|
||||
300,
|
||||
),
|
||||
DIRECT_UPLOAD_MAX_PENDING_PER_USER: numeric(
|
||||
'DIRECT_UPLOAD_MAX_PENDING_PER_USER',
|
||||
1,
|
||||
1000,
|
||||
10,
|
||||
),
|
||||
})
|
||||
.strip();
|
||||
|
||||
export const databaseConfigSchema = appConfigSchema.pick({
|
||||
DATABASE_URL: true,
|
||||
DATABASE_POOL_MAX: true,
|
||||
DATABASE_CONNECTION_TIMEOUT_MS: true,
|
||||
DATABASE_STATEMENT_TIMEOUT_MS: true,
|
||||
HEALTH_TIMEOUT_MS: true,
|
||||
IDEMPOTENCY_TTL_SECONDS: true,
|
||||
});
|
||||
export type DatabaseConfig = z.infer<typeof databaseConfigSchema>;
|
||||
|
||||
export type AppConfig = z.infer<typeof appConfigSchema>;
|
||||
export type AppConfigKey = keyof AppConfig;
|
||||
|
||||
function resolveSecret(
|
||||
raw: Record<string, unknown>,
|
||||
key:
|
||||
| 'DATABASE_URL'
|
||||
| 'REDIS_URL'
|
||||
| 'S3_ACCESS_KEY_ID'
|
||||
| 'S3_SECRET_ACCESS_KEY',
|
||||
): 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'),
|
||||
S3_ACCESS_KEY_ID: resolveSecret(raw, 'S3_ACCESS_KEY_ID'),
|
||||
S3_SECRET_ACCESS_KEY: resolveSecret(raw, 'S3_SECRET_ACCESS_KEY'),
|
||||
});
|
||||
}
|
||||
|
||||
// Для процессов, которым нужна только БД (миграции, GC идемпотентности).
|
||||
export function parseDatabaseConfig(
|
||||
raw: Record<string, unknown>,
|
||||
): DatabaseConfig {
|
||||
return databaseConfigSchema.parse({
|
||||
...raw,
|
||||
DATABASE_URL: resolveSecret(raw, 'DATABASE_URL'),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { hostname } from 'node:os';
|
||||
import type { ConfigService } from '@nestjs/config';
|
||||
import type { AppConfig } from './app-config.schema.js';
|
||||
|
||||
// A replica must be identifiable from the outside. Inside Docker the hostname is
|
||||
// the short container ID, so X-Instance-Id can be mapped back to exactly one
|
||||
// container; INSTANCE_ID exists for platforms where that mapping is not useful.
|
||||
export function resolveInstanceId(config: ConfigService<AppConfig>): string {
|
||||
const configured = config.get('INSTANCE_ID');
|
||||
if (configured) return configured;
|
||||
const host = hostname();
|
||||
return host.length > 0 ? host : randomUUID();
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
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 healthPool: 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}`);
|
||||
});
|
||||
// Проба готовности не должна стоять в очереди за бизнес-запросами: занятый
|
||||
// общий пул — это перегрузка, а не потеря зависимости.
|
||||
this.healthPool = new pg.Pool({
|
||||
connectionString: this.config.getOrThrow('DATABASE_URL'),
|
||||
max: 1,
|
||||
idleTimeoutMillis: 0,
|
||||
connectionTimeoutMillis:
|
||||
this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
|
||||
query_timeout: this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
|
||||
});
|
||||
this.healthPool.on('error', (error: Error) => {
|
||||
this.metrics.increment('database.health_pool_error');
|
||||
this.logger.warn(
|
||||
`PostgreSQL health connection 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> {
|
||||
this.metrics.increment('health.database');
|
||||
await this.healthPool.query('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 Promise.all([this.pool.end(), this.healthPool.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 { parseDatabaseConfig } 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 = parseDatabaseConfig(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);
|
||||
@@ -0,0 +1,20 @@
|
||||
-- Shared idempotency ledger for POST /api/v1/chats/{id}/messages.
|
||||
-- The key scope is (user, method, path, key): the same key from another user or
|
||||
-- another chat is independent, as the contract requires.
|
||||
-- claim + response are committed in one transaction, so a committed row always
|
||||
-- carries status_code and response_body (there is no "poisoned" intermediate state).
|
||||
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
method text NOT NULL,
|
||||
path text NOT NULL,
|
||||
key text NOT NULL,
|
||||
request_fingerprint text NOT NULL,
|
||||
status_code integer,
|
||||
response_body jsonb,
|
||||
message_id uuid,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, method, path, key)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idempotency_keys_created_at_idx
|
||||
ON idempotency_keys (created_at);
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Instrumentation for the scaling experiments. pg_stat_statements only works
|
||||
-- when the server is started with shared_preload_libraries=pg_stat_statements
|
||||
-- (compose.yaml does that); without the preload the CREATE fails with a plain
|
||||
-- notice, so a database started without the preload still migrates cleanly.
|
||||
DO $$ BEGIN
|
||||
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
|
||||
EXCEPTION WHEN OTHERS THEN
|
||||
RAISE NOTICE 'pg_stat_statements unavailable: %', SQLERRM;
|
||||
END $$;
|
||||
@@ -0,0 +1,42 @@
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_id_chat_key UNIQUE (id, chat_id);
|
||||
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
owner_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||
filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
upload_mode text NOT NULL CHECK (upload_mode IN ('proxy', 'direct')),
|
||||
status text NOT NULL CHECK (status IN ('pending', 'ready', 'deleting')),
|
||||
object_key text NOT NULL UNIQUE,
|
||||
size_bytes bigint CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 text CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
width integer CHECK (width > 0),
|
||||
height integer CHECK (height > 0),
|
||||
expires_at timestamptz(3),
|
||||
created_at timestamptz(3) NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz(3) NOT NULL DEFAULT now(),
|
||||
CONSTRAINT attachments_id_chat_key UNIQUE (id, chat_id),
|
||||
CONSTRAINT attachments_owner_member_fk FOREIGN KEY (chat_id, owner_id)
|
||||
REFERENCES chat_members (chat_id, user_id),
|
||||
CONSTRAINT attachments_ready_complete CHECK (status <> 'ready' OR
|
||||
(size_bytes IS NOT NULL AND sha256 IS NOT NULL AND width IS NOT NULL AND height IS NOT NULL)),
|
||||
CONSTRAINT attachments_unfinished_expiry CHECK (status = 'ready' OR expires_at IS NOT NULL)
|
||||
);
|
||||
CREATE INDEX attachments_unfinished_idx ON attachments (expires_at) WHERE status <> 'ready';
|
||||
CREATE INDEX attachments_owner_direct_pending_idx ON attachments (owner_id)
|
||||
WHERE status = 'pending' AND upload_mode = 'direct';
|
||||
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL,
|
||||
chat_id uuid NOT NULL,
|
||||
attachment_id uuid NOT NULL,
|
||||
ordinal smallint NOT NULL CHECK (ordinal BETWEEN 1 AND 10),
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
CONSTRAINT message_attachments_ordinal_key UNIQUE (message_id, ordinal),
|
||||
CONSTRAINT message_attachments_message_fk FOREIGN KEY (message_id, chat_id)
|
||||
REFERENCES messages (id, chat_id) ON DELETE CASCADE,
|
||||
CONSTRAINT message_attachments_attachment_fk FOREIGN KEY (attachment_id, chat_id)
|
||||
REFERENCES attachments (id, chat_id)
|
||||
);
|
||||
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Rejected direct uploads keep their row until the signed URL can no longer be
|
||||
-- used, so an object re-PUT after rejection is still found by the sweeper.
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check
|
||||
CHECK (status IN ('pending', 'ready', 'deleting', 'rejected'));
|
||||
DROP INDEX attachments_owner_direct_pending_idx;
|
||||
CREATE INDEX attachments_owner_direct_pending_idx ON attachments (owner_id)
|
||||
WHERE status IN ('pending', 'rejected') AND upload_mode = 'direct';
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { HealthService } from './health.service.js';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(private readonly healthService: HealthService) {}
|
||||
|
||||
@Get('live')
|
||||
getLive() {
|
||||
return this.healthService.getLiveness();
|
||||
}
|
||||
|
||||
@Get('ready')
|
||||
async getReady() {
|
||||
return this.healthService.getReadiness();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +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: [DatabaseModule, RedisModule],
|
||||
controllers: [HealthController],
|
||||
providers: [HealthService],
|
||||
})
|
||||
export class HealthModule {}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { ServiceUnavailableException } from '@nestjs/common';
|
||||
import { HealthService } from './health.service.js';
|
||||
|
||||
describe('HealthService', () => {
|
||||
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 service = new HealthService(
|
||||
database as never,
|
||||
redis as never,
|
||||
{ getOrThrow: () => 50 } as never,
|
||||
);
|
||||
expect(service.getLiveness()).toEqual({ status: 'ok' });
|
||||
await expect(service.getReadiness()).resolves.toEqual({ status: 'ok' });
|
||||
});
|
||||
|
||||
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,
|
||||
{ getOrThrow: () => 50 } as never,
|
||||
);
|
||||
await expect(service.getReadiness()).rejects.toBeInstanceOf(
|
||||
ServiceUnavailableException,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects readiness when Redis alone is unavailable', async () => {
|
||||
const database = { health: vi.fn().mockResolvedValue(undefined) };
|
||||
const redis = {
|
||||
health: vi.fn().mockRejectedValue(new Error('down')),
|
||||
};
|
||||
const service = new HealthService(
|
||||
database as never,
|
||||
redis as never,
|
||||
{ getOrThrow: () => 50 } as never,
|
||||
);
|
||||
await expect(service.getReadiness()).rejects.toBeInstanceOf(
|
||||
ServiceUnavailableException,
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps liveness healthy while draining', async () => {
|
||||
const service = new HealthService(
|
||||
{ health: vi.fn() } as never,
|
||||
{ health: vi.fn() } as never,
|
||||
{ getOrThrow: () => 50 } as never,
|
||||
);
|
||||
service.setDraining();
|
||||
expect(service.getLiveness()).toEqual({ status: 'ok' });
|
||||
await expect(service.getReadiness()).rejects.toThrow(
|
||||
'Service is shutting down',
|
||||
);
|
||||
});
|
||||
|
||||
it('answers not-ready during drain without probing dependencies', async () => {
|
||||
const database = { health: vi.fn().mockResolvedValue(undefined) };
|
||||
const redis = { health: vi.fn().mockResolvedValue(undefined) };
|
||||
const service = new HealthService(
|
||||
database as never,
|
||||
redis as never,
|
||||
{ getOrThrow: () => 50 } as never,
|
||||
);
|
||||
service.setDraining();
|
||||
await expect(service.getReadiness()).rejects.toThrow(
|
||||
'Service is shutting down',
|
||||
);
|
||||
// Дрейн обязан отвечать сразу: проба LB не должна ждать зависимости,
|
||||
// когда реплика уже выходит из ротации.
|
||||
expect(database.health).not.toHaveBeenCalled();
|
||||
expect(redis.health).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fails readiness within the budget when a dependency hangs', async () => {
|
||||
const database = { health: vi.fn(() => new Promise<void>(() => {})) };
|
||||
const redis = { health: vi.fn().mockResolvedValue(undefined) };
|
||||
const service = new HealthService(
|
||||
database as never,
|
||||
redis as never,
|
||||
{ getOrThrow: () => 20 } as never,
|
||||
);
|
||||
await expect(service.getReadiness()).rejects.toBeInstanceOf(
|
||||
ServiceUnavailableException,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import {
|
||||
Global,
|
||||
Injectable,
|
||||
Module,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { DatabaseClient } from '../database/database.client.js';
|
||||
import { RedisClient } from '../redis/redis.client.js';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
|
||||
@Injectable()
|
||||
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');
|
||||
const dependencies = Promise.all([
|
||||
this.database.health(),
|
||||
this.redis.health(),
|
||||
]);
|
||||
// Поздний отказ после дедлайна не должен стать unhandled rejection.
|
||||
dependencies.catch(() => undefined);
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const deadline = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(
|
||||
() => reject(new Error('readiness budget exceeded')),
|
||||
this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
|
||||
);
|
||||
});
|
||||
try {
|
||||
await Promise.race([dependencies, deadline]);
|
||||
} catch {
|
||||
throw new ServiceUnavailableException('Dependencies unavailable');
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
return { status: 'ok' as const };
|
||||
}
|
||||
// Called on SIGTERM before the drain delay: the replica turns not-ready while
|
||||
// it finishes in-flight requests, so the load balancer stops probing it
|
||||
// successfully and removes it from rotation. The delay itself lives in
|
||||
// main.ts, because Nest destroys providers (closing the pools) before this
|
||||
// class could serve anyone.
|
||||
setDraining() {
|
||||
this.ready = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Global()
|
||||
@Module({ providers: [HealthService], exports: [HealthService] })
|
||||
export class HealthServiceModule {}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { HttpAdapterHost } from '@nestjs/core';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import type { UploadRequest } from './attachments/upload-request.js';
|
||||
import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
} from '@nestjs/platform-fastify';
|
||||
import { AppModule } from './app.module.js';
|
||||
import { HealthService } from './health/health.service.js';
|
||||
import { MetricsService } from './metrics/metrics.service.js';
|
||||
import { RequestIdInterceptor } from './common/http/request-id.interceptor.js';
|
||||
|
||||
const UPLOAD_ROUTE = '/api/v1/chats/:chatId/attachments';
|
||||
const UPLOAD_STREAM_TYPE = 'application/x-messenger-upload-stream';
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.create<NestFastifyApplication>(
|
||||
AppModule,
|
||||
new FastifyAdapter({ logger: true }),
|
||||
);
|
||||
// The upload route receives its body as an unread stream whatever the
|
||||
// declared Content-Type: the service checks the type itself, after the
|
||||
// auth guard (401 before 415, contracts/README.md), and bounds the body by
|
||||
// its own limits, not Fastify's bodyLimit. The declared type is kept on the
|
||||
// request; all other routes keep Fastify's parsers untouched.
|
||||
const fastify = app.getHttpAdapter().getInstance();
|
||||
fastify.addHook(
|
||||
'onRequest',
|
||||
(request: UploadRequest, _reply: unknown, done: () => void) => {
|
||||
if (
|
||||
request.method === 'POST' &&
|
||||
request.routeOptions?.url === UPLOAD_ROUTE
|
||||
) {
|
||||
request.uploadContentType = request.headers['content-type'];
|
||||
request.headers['content-type'] = UPLOAD_STREAM_TYPE;
|
||||
}
|
||||
done();
|
||||
},
|
||||
);
|
||||
fastify.addContentTypeParser(
|
||||
UPLOAD_STREAM_TYPE,
|
||||
(
|
||||
_request: unknown,
|
||||
payload: unknown,
|
||||
done: (error: Error | null, body?: unknown) => void,
|
||||
) => done(null, payload),
|
||||
);
|
||||
app.useGlobalInterceptors(
|
||||
new RequestIdInterceptor(
|
||||
app.get(HttpAdapterHost),
|
||||
app.get(MetricsService),
|
||||
app.get(ConfigService),
|
||||
),
|
||||
);
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
|
||||
const config = app.get(ConfigService);
|
||||
const port = config.getOrThrow<number>('APP_PORT');
|
||||
const host = config.getOrThrow<string>('APP_HOST');
|
||||
await app.listen(port, host);
|
||||
|
||||
// Drain before teardown. Nest's own shutdown sequence destroys providers
|
||||
// (closing the database pool and Redis) before `beforeApplicationShutdown`
|
||||
// runs, so relying on it would keep the replica listed in the load balancer
|
||||
// while it can no longer serve: SIGTERM must first turn the replica
|
||||
// not-ready for the LB probe, then wait DRAIN_DELAY_MS, and only then close
|
||||
// the server and the pools.
|
||||
const health = app.get(HealthService);
|
||||
const drainDelayMs = config.getOrThrow<number>('DRAIN_DELAY_MS');
|
||||
let shuttingDown = false;
|
||||
const shutdown = async (): Promise<void> => {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
health.setDraining();
|
||||
if (drainDelayMs > 0)
|
||||
await new Promise<void>((resolve) =>
|
||||
setTimeout(resolve, drainDelayMs),
|
||||
);
|
||||
await app.close();
|
||||
process.exit(0);
|
||||
};
|
||||
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const)
|
||||
process.once(signal, () => {
|
||||
void shutdown();
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
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 type { Page } from '../../common/http/page.js';
|
||||
import { MetricsService } from '../../metrics/metrics.service.js';
|
||||
|
||||
const LOCK_RETRY_COUNT = 4;
|
||||
const LOCK_RETRY_DELAY_MS = 25;
|
||||
|
||||
export type CachePage = Page<unknown>;
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsString,
|
||||
IsUUID,
|
||||
ValidateIf,
|
||||
} from 'class-validator';
|
||||
import { CodePointLength } from '../../common/validation/code-point-length.js';
|
||||
|
||||
export class CreateMessageDto {
|
||||
@IsString()
|
||||
@CodePointLength(0, 4000)
|
||||
text!: string;
|
||||
|
||||
// Absent means []; null is a client error.
|
||||
@ValidateIf((_, value) => value !== undefined)
|
||||
@IsArray()
|
||||
@ArrayMaxSize(10)
|
||||
@ArrayUnique()
|
||||
@IsUUID('all', { each: true })
|
||||
attachment_ids: string[] = [];
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { parseDatabaseConfig } from '../../config/app-config.schema.js';
|
||||
import { DatabaseClient } from '../../database/database.client.js';
|
||||
import { MetricsService } from '../../metrics/metrics.service.js';
|
||||
import { IdempotencyRepository } from './idempotency.repository.js';
|
||||
|
||||
// Manual operator pass over the idempotency ledger: the API also purges expired
|
||||
// claims in the background, but an operator must be able to reclaim space
|
||||
// without waiting for traffic. It never touches unexpired claims.
|
||||
// in the stand: docker compose exec api node dist/messages/idempotency/idempotency-gc.cli.js
|
||||
// on the host: npm run idempotency:gc (needs a reachable DATABASE_URL)
|
||||
async function main(): Promise<void> {
|
||||
const config = parseDatabaseConfig(process.env as Record<string, unknown>);
|
||||
const database = new DatabaseClient(
|
||||
{
|
||||
getOrThrow: (key: keyof typeof config) => config[key],
|
||||
} as never,
|
||||
new MetricsService(),
|
||||
);
|
||||
try {
|
||||
const repository = new IdempotencyRepository(database);
|
||||
const purged = await repository.purgeExpired(
|
||||
config.IDEMPOTENCY_TTL_SECONDS,
|
||||
);
|
||||
process.stdout.write(
|
||||
`Purged ${purged} idempotency key(s) older than ${config.IDEMPOTENCY_TTL_SECONDS} seconds\n`,
|
||||
);
|
||||
} finally {
|
||||
await database.onModuleDestroy();
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { DatabaseModule } from '../../database/database.module.js';
|
||||
import { IdempotencyRepository } from './idempotency.repository.js';
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule],
|
||||
providers: [IdempotencyRepository],
|
||||
exports: [IdempotencyRepository],
|
||||
})
|
||||
export class IdempotencyModule {}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { IdempotencyRepository } from './idempotency.repository.js';
|
||||
|
||||
describe('IdempotencyRepository expired-key cleanup', () => {
|
||||
it('deletes only rows older than the configured TTL', async () => {
|
||||
const query = vi.fn().mockResolvedValue({ rowCount: 0, rows: [] });
|
||||
const repository = new IdempotencyRepository({ query } as never);
|
||||
|
||||
await repository.forget(
|
||||
'user',
|
||||
'/api/v1/chats/chat/messages',
|
||||
'key',
|
||||
86400,
|
||||
);
|
||||
|
||||
expect(query).toHaveBeenCalledWith(
|
||||
'idempotency.forget',
|
||||
expect.stringContaining(
|
||||
'created_at < now() - make_interval(secs => $4::double precision)',
|
||||
),
|
||||
['user', '/api/v1/chats/chat/messages', 'key', 86400],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import pg from 'pg';
|
||||
import { DatabaseClient } from '../../database/database.client.js';
|
||||
import type { Message } from '../message.js';
|
||||
|
||||
// A committed row always carries the response: the claim and the stored response
|
||||
// are written by one statement, so there is no poisoned intermediate state to
|
||||
// re-check at replay time.
|
||||
export type IdempotencyRecord = {
|
||||
request_fingerprint: string;
|
||||
status_code: number;
|
||||
response_body: Message;
|
||||
created_at: Date | string;
|
||||
expired: boolean;
|
||||
is_member: boolean;
|
||||
};
|
||||
|
||||
const PURGE_BATCH_LIMIT = 1000;
|
||||
const PURGE_BATCHES = 10;
|
||||
|
||||
@Injectable()
|
||||
export class IdempotencyRepository {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
/**
|
||||
* Reads the stored result and re-checks access in the same round trip: a
|
||||
* replay must still prove that the caller may read this chat.
|
||||
*/
|
||||
async read(
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
chatId: string,
|
||||
ttlSeconds: number,
|
||||
): Promise<IdempotencyRecord | undefined> {
|
||||
const result = await this.database.query<IdempotencyRecord>(
|
||||
'idempotency.read',
|
||||
`SELECT k.request_fingerprint, k.status_code, k.response_body, k.created_at,
|
||||
k.created_at < now() - make_interval(secs => $4::double precision) AS expired,
|
||||
EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $5 AND user_id = $1
|
||||
) AS is_member
|
||||
FROM idempotency_keys k
|
||||
WHERE k.user_id = $1 AND k.method = 'POST' AND k.path = $2 AND k.key = $3`,
|
||||
[userId, path, key, ttlSeconds, chatId],
|
||||
);
|
||||
return result.rows[0];
|
||||
}
|
||||
|
||||
async forget(
|
||||
userId: string,
|
||||
path: string,
|
||||
key: string,
|
||||
ttlSeconds: number,
|
||||
): Promise<void> {
|
||||
await this.database.query(
|
||||
'idempotency.forget',
|
||||
`DELETE FROM idempotency_keys
|
||||
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3
|
||||
AND created_at < now() - make_interval(secs => $4::double precision)`,
|
||||
[userId, path, key, ttlSeconds],
|
||||
);
|
||||
}
|
||||
|
||||
async isMember(chatId: string, userId: string): Promise<boolean> {
|
||||
const result = await this.database.query<{ is_member: boolean }>(
|
||||
'messages.checkMembership',
|
||||
`SELECT EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2
|
||||
) AS is_member`,
|
||||
[chatId, userId],
|
||||
);
|
||||
return result.rows[0]?.is_member === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes expired claims in bounded batches. The transaction-scoped advisory
|
||||
* lock makes the pass single-flight across replicas without risking a lock
|
||||
* leaking back into the pool with a released connection. Returns the number
|
||||
* of deleted rows (0 when another replica is purging).
|
||||
*/
|
||||
async purgeExpired(ttlSeconds: number): Promise<number> {
|
||||
const client: pg.PoolClient = await this.database.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
try {
|
||||
const lock = await client.query<{ locked: boolean }>(
|
||||
"SELECT pg_try_advisory_xact_lock(hashtext('idempotency_gc')) AS locked",
|
||||
);
|
||||
if (lock.rows[0]?.locked !== true) {
|
||||
await client.query('ROLLBACK');
|
||||
return 0;
|
||||
}
|
||||
let purged = 0;
|
||||
for (let batch = 0; batch < PURGE_BATCHES; batch += 1) {
|
||||
const result = await client.query(
|
||||
`DELETE FROM idempotency_keys
|
||||
WHERE ctid IN (
|
||||
SELECT ctid FROM idempotency_keys
|
||||
WHERE created_at < now() - make_interval(secs => $1::double precision)
|
||||
LIMIT ${PURGE_BATCH_LIMIT}
|
||||
)`,
|
||||
[ttlSeconds],
|
||||
);
|
||||
const deleted = result.rowCount ?? 0;
|
||||
purged += deleted;
|
||||
if (deleted < PURGE_BATCH_LIMIT) break;
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
return purged;
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
// Contract: ASCII [A-Za-z0-9._:-]{1,128}. Anything else (including a duplicated
|
||||
// header, which Fastify joins with ", ") is rejected as a client error.
|
||||
export const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
|
||||
|
||||
export function messagesPath(chatId: string): string {
|
||||
return `/api/v1/chats/${chatId}/messages`;
|
||||
}
|
||||
|
||||
// The fingerprint is derived from the validated payload with a fixed field
|
||||
// order, so neither JSON key order nor an absent optional field can change it.
|
||||
// Text-only messages keep the lab3 fingerprint; the order of attachment ids
|
||||
// is significant because it is the order of attachments in the message.
|
||||
export function idempotencyFingerprint(
|
||||
text: string,
|
||||
attachmentIds: string[],
|
||||
): string {
|
||||
return createHash('sha256')
|
||||
.update(
|
||||
attachmentIds.length === 0
|
||||
? JSON.stringify({ text })
|
||||
: JSON.stringify({ text, attachment_ids: attachmentIds }),
|
||||
)
|
||||
.digest('hex');
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export type Message = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
attachment_ids: string[];
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
DefaultValuePipe,
|
||||
Get,
|
||||
Headers,
|
||||
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 { User } from '../users/user.js';
|
||||
import { CreateMessageDto } from './dto/create-message.dto.js';
|
||||
import { MessagesService } from './messages.service.js';
|
||||
|
||||
@Controller('api/v1/chats/:chatId/messages')
|
||||
@UseGuards(CurrentUserGuard)
|
||||
export class MessagesController {
|
||||
constructor(private readonly messagesService: MessagesService) {}
|
||||
|
||||
@Post()
|
||||
create(
|
||||
@Param('chatId', new ParseUUIDPipe()) chatId: string,
|
||||
@Body() body: CreateMessageDto,
|
||||
@CurrentUser() currentUser: User,
|
||||
@Headers('idempotency-key') idempotencyKey?: string | string[],
|
||||
) {
|
||||
return this.messagesService.create(
|
||||
chatId,
|
||||
body,
|
||||
currentUser,
|
||||
idempotencyKey,
|
||||
);
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { DatabaseModule } from '../database/database.module.js';
|
||||
import { ChatsModule } from '../chats/chats.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 { IdempotencyModule } from './idempotency/idempotency.module.js';
|
||||
import { UsersModule } from '../users/users.module.js';
|
||||
import { RedisModule } from '../redis/redis.module.js';
|
||||
import { AttachmentsModule } from '../attachments/attachments.module.js';
|
||||
import { MetricsModule } from '../metrics/metrics.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ChatsModule,
|
||||
MessagesCacheModule,
|
||||
IdempotencyModule,
|
||||
DatabaseModule,
|
||||
UsersModule,
|
||||
RedisModule,
|
||||
MetricsModule,
|
||||
AttachmentsModule,
|
||||
],
|
||||
controllers: [MessagesController],
|
||||
providers: [MessagesRepository, MessagesService],
|
||||
})
|
||||
export class MessagesModule {}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
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,
|
||||
attachment_ids: [],
|
||||
});
|
||||
|
||||
describe('MessagesRepository', () => {
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import { 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 { Message } from './message.js';
|
||||
|
||||
type MessageRow = {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: Date | string;
|
||||
attachment_ids?: string[] | null;
|
||||
};
|
||||
|
||||
export type CreateOnceRequest = {
|
||||
userId: string;
|
||||
chatId: string;
|
||||
path: string;
|
||||
key: string;
|
||||
fingerprint: string;
|
||||
text: string;
|
||||
attachmentIds: 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(),
|
||||
attachment_ids: row.attachment_ids ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
// Один оператор делает всё, что нужно пути записи: проверяет членство, занимает
|
||||
// ключ идемпотентности, вставляет сообщение, увеличивает версию чата (якорь
|
||||
// инвалидации кэша истории) и сохраняет тело ответа. Атомарность даёт сам
|
||||
// оператор, поэтому явная транзакция и отдельные round trip'ы не нужны; тело
|
||||
// ответа строится в SQL и служит единственным источником истины и для первого
|
||||
// ответа, и для повторов.
|
||||
//
|
||||
// Зависимости CTE задают порядок выполнения: claim -> inserted -> bumped.
|
||||
const CREATE_ONCE_SQL = `
|
||||
WITH claim AS (
|
||||
INSERT INTO idempotency_keys (user_id, method, path, key, request_fingerprint,
|
||||
status_code, response_body, message_id)
|
||||
SELECT $1, 'POST', $2, $3, $4, 201,
|
||||
jsonb_build_object(
|
||||
'id', $5::uuid,
|
||||
'chat_id', $7::uuid,
|
||||
'sender_id', $1::uuid,
|
||||
'text', $6::text,
|
||||
'created_at', to_char(date_trunc('milliseconds', now()) AT TIME ZONE 'UTC',
|
||||
'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'),
|
||||
'attachment_ids', to_jsonb($8::uuid[])),
|
||||
$5::uuid
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $7::uuid AND user_id = $1
|
||||
)
|
||||
AND (SELECT count(*) FROM attachments a
|
||||
WHERE a.chat_id = $7::uuid AND a.status = 'ready'
|
||||
AND a.id = ANY($8::uuid[])) = cardinality($8::uuid[])
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING response_body
|
||||
), inserted AS (
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT $5::uuid, $7::uuid, $1::uuid, $6::text, date_trunc('milliseconds', now())
|
||||
FROM claim
|
||||
RETURNING id
|
||||
), linked AS (
|
||||
INSERT INTO message_attachments (message_id, chat_id, attachment_id, ordinal)
|
||||
SELECT $5::uuid, $7::uuid, t.id, t.ord
|
||||
FROM inserted, unnest($8::uuid[]) WITH ORDINALITY AS t(id, ord)
|
||||
), bumped AS (
|
||||
UPDATE chats SET message_version = message_version + 1
|
||||
WHERE id = $7::uuid AND EXISTS (SELECT 1 FROM inserted)
|
||||
)
|
||||
SELECT response_body FROM claim`;
|
||||
|
||||
@Injectable()
|
||||
export class MessagesRepository {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
/**
|
||||
* Returns the created message, or undefined when the key is already taken or
|
||||
* the caller is not a member of the chat (both leave no side effect).
|
||||
*/
|
||||
async createOnce(request: CreateOnceRequest): Promise<Message | undefined> {
|
||||
const result = await this.database.query<{ response_body: Message }>(
|
||||
'messages.createIdempotent',
|
||||
CREATE_ONCE_SQL,
|
||||
[
|
||||
request.userId,
|
||||
request.path,
|
||||
request.key,
|
||||
request.fingerprint,
|
||||
randomUUID(),
|
||||
request.text,
|
||||
request.chatId,
|
||||
request.attachmentIds,
|
||||
],
|
||||
);
|
||||
return result.rows[0]?.response_body;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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 (m.created_at, m.id) > ($2::timestamptz, $3::uuid)';
|
||||
}
|
||||
values.push(limit + 1);
|
||||
const result = await this.database.query<MessageRow>(
|
||||
'messages.history',
|
||||
`SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
COALESCE((SELECT json_agg(ma.attachment_id ORDER BY ma.ordinal)
|
||||
FROM message_attachments ma WHERE ma.message_id = m.id), '[]'::json) AS attachment_ids
|
||||
FROM messages m WHERE m.chat_id = $1 ${predicate} ORDER BY m.created_at, m.id LIMIT $${values.length}`,
|
||||
values,
|
||||
);
|
||||
return {
|
||||
items: result.rows.slice(0, limit).map(toMessage),
|
||||
hasMore: result.rows.length > limit,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { MessagesService } from './messages.service.js';
|
||||
import { idempotencyFingerprint } from './idempotency/idempotency.js';
|
||||
import type { Message } from './message.js';
|
||||
|
||||
type StoredRow = {
|
||||
request_fingerprint: string;
|
||||
response_body: Message;
|
||||
created_at: Date;
|
||||
expired: boolean;
|
||||
is_member: boolean;
|
||||
};
|
||||
|
||||
function deferred(): { promise: Promise<void>; resolve: () => void } {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
describe('MessagesService idempotency expiry race', () => {
|
||||
it('does not let a stale expiry decision delete a replacement claim', async () => {
|
||||
const oldCreatedAt = new Date('2020-01-01T00:00:00.000Z');
|
||||
const newMessage: Message = {
|
||||
id: 'message-new',
|
||||
chat_id: 'chat',
|
||||
sender_id: 'user',
|
||||
text: 'hello',
|
||||
created_at: '2026-01-01T00:00:00.000Z',
|
||||
attachment_ids: [],
|
||||
};
|
||||
let row: StoredRow | undefined = {
|
||||
request_fingerprint: idempotencyFingerprint('hello', []),
|
||||
response_body: {
|
||||
...newMessage,
|
||||
id: 'message-old',
|
||||
text: 'old',
|
||||
},
|
||||
created_at: oldCreatedAt,
|
||||
expired: true,
|
||||
is_member: true,
|
||||
};
|
||||
let createCalls = 0;
|
||||
let readCalls = 0;
|
||||
let forgetCalls = 0;
|
||||
let messageWrites = 0;
|
||||
const bothInitialClaims = deferred();
|
||||
const bothInitialReads = deferred();
|
||||
const replacementCreated = deferred();
|
||||
|
||||
const messagesRepository = {
|
||||
createOnce: vi.fn(async () => {
|
||||
createCalls += 1;
|
||||
if (createCalls === 2) bothInitialClaims.resolve();
|
||||
if (createCalls <= 2) {
|
||||
await bothInitialClaims.promise;
|
||||
return undefined;
|
||||
}
|
||||
if (row) return undefined;
|
||||
messageWrites += 1;
|
||||
row = {
|
||||
request_fingerprint: idempotencyFingerprint('hello', []),
|
||||
response_body: newMessage,
|
||||
created_at: new Date('2026-01-01T00:00:00.000Z'),
|
||||
expired: false,
|
||||
is_member: true,
|
||||
};
|
||||
replacementCreated.resolve();
|
||||
return newMessage;
|
||||
}),
|
||||
};
|
||||
const idempotency = {
|
||||
read: vi.fn(async () => {
|
||||
readCalls += 1;
|
||||
if (readCalls === 2) bothInitialReads.resolve();
|
||||
if (readCalls <= 2) await bothInitialReads.promise;
|
||||
return row;
|
||||
}),
|
||||
forget: vi.fn(async (...args: unknown[]) => {
|
||||
forgetCalls += 1;
|
||||
if (args.length !== 4) {
|
||||
row = undefined;
|
||||
return;
|
||||
}
|
||||
if (forgetCalls === 2) await replacementCreated.promise;
|
||||
if (
|
||||
!row ||
|
||||
row.created_at >= new Date('2026-01-01T00:00:00.000Z')
|
||||
)
|
||||
return;
|
||||
row = undefined;
|
||||
}),
|
||||
isMember: vi.fn().mockResolvedValue(true),
|
||||
};
|
||||
const makeService = () =>
|
||||
new MessagesService(
|
||||
messagesRepository as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
idempotency as never,
|
||||
{ getOrThrow: vi.fn().mockReturnValue(60) } as never,
|
||||
{ increment: vi.fn() } as never,
|
||||
{} as never,
|
||||
);
|
||||
const input = { text: 'hello', attachment_ids: [] } as never;
|
||||
const user = { id: 'user' } as never;
|
||||
|
||||
const results = await Promise.all([
|
||||
makeService().create('chat', input, user, 'same-key'),
|
||||
makeService().create('chat', input, user, 'same-key'),
|
||||
]);
|
||||
|
||||
expect(results).toEqual([newMessage, newMessage]);
|
||||
expect(new Set(results.map((message) => message.id))).toEqual(
|
||||
new Set(['message-new']),
|
||||
);
|
||||
expect(messageWrites).toBe(1);
|
||||
expect(forgetCalls).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { decodeCursor, encodeCursor } from '../common/http/cursor.js';
|
||||
import type { Page } from '../common/http/page.js';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import type { User } from '../users/user.js';
|
||||
import { ChatsService } from '../chats/chats.service.js';
|
||||
import { AttachmentsRepository } from '../attachments/attachments.repository.js';
|
||||
import { MetricsService } from '../metrics/metrics.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';
|
||||
import {
|
||||
IDEMPOTENCY_KEY_PATTERN,
|
||||
idempotencyFingerprint,
|
||||
messagesPath,
|
||||
} from './idempotency/idempotency.js';
|
||||
import { IdempotencyRepository } from './idempotency/idempotency.repository.js';
|
||||
|
||||
// Один повтор нужен только для просроченного ключа: запись удаляется, и тот же
|
||||
// оператор занимает ключ заново. Больше трёх кругов означает, что ключ
|
||||
// перехватывают параллельные запросы, и честнее вернуть 503, чем крутиться.
|
||||
const MAX_CLAIM_ATTEMPTS = 3;
|
||||
const PURGE_EVERY_REQUESTS = 512;
|
||||
|
||||
@Injectable()
|
||||
export class MessagesService {
|
||||
private readonly logger = new Logger(MessagesService.name);
|
||||
private requestsSincePurge = 0;
|
||||
|
||||
constructor(
|
||||
private readonly messagesRepository: MessagesRepository,
|
||||
private readonly chatsService: ChatsService,
|
||||
private readonly cache: MessagesCacheService,
|
||||
private readonly idempotency: IdempotencyRepository,
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
private readonly attachments: AttachmentsRepository,
|
||||
) {}
|
||||
|
||||
async create(
|
||||
chatId: string,
|
||||
input: CreateMessageDto,
|
||||
currentUser: User,
|
||||
rawKey: string | string[] | undefined,
|
||||
): Promise<Message> {
|
||||
// Ключ и тело проверяются до обращения к БД: клиентская ошибка не должна
|
||||
// создавать заявку и не должна зависеть от состояния хранилища.
|
||||
if (typeof rawKey !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(rawKey))
|
||||
throw new BadRequestException('Idempotency-Key header is required');
|
||||
const ids = input.attachment_ids.map((id) => id.toLowerCase());
|
||||
if (new Set(ids).size !== ids.length)
|
||||
throw new BadRequestException('attachment_ids must be unique');
|
||||
if (
|
||||
ids.length === 0 &&
|
||||
[...input.text].every((character) => /\s/u.test(character))
|
||||
)
|
||||
throw new BadRequestException('Message text cannot be blank');
|
||||
|
||||
const path = messagesPath(chatId);
|
||||
const fingerprint = idempotencyFingerprint(input.text, ids);
|
||||
const ttl = this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS');
|
||||
for (let attempt = 1; attempt <= MAX_CLAIM_ATTEMPTS; attempt += 1) {
|
||||
const created = await this.messagesRepository.createOnce({
|
||||
userId: currentUser.id,
|
||||
chatId,
|
||||
path,
|
||||
key: rawKey,
|
||||
fingerprint,
|
||||
text: input.text,
|
||||
attachmentIds: ids,
|
||||
});
|
||||
if (created) {
|
||||
this.metrics.increment('idempotency.claim');
|
||||
this.metrics.increment('messages.write');
|
||||
this.scheduleExpiredPurge();
|
||||
return created;
|
||||
}
|
||||
|
||||
const stored = await this.idempotency.read(
|
||||
currentUser.id,
|
||||
path,
|
||||
rawKey,
|
||||
chatId,
|
||||
ttl,
|
||||
);
|
||||
if (!stored) {
|
||||
// Заявки нет: либо запрос не имеет доступа к чату (404), либо
|
||||
// чужую заявку сняли между нашими двумя запросами (503).
|
||||
if (!(await this.idempotency.isMember(chatId, currentUser.id)))
|
||||
throw new NotFoundException();
|
||||
// Unknown, foreign-chat or unfinished attachment: not found.
|
||||
if (
|
||||
ids.length > 0 &&
|
||||
!(await this.attachments.allLinkable(chatId, ids))
|
||||
)
|
||||
throw new NotFoundException();
|
||||
this.metrics.increment('idempotency.claim_lost');
|
||||
throw new ServiceUnavailableException(
|
||||
'Idempotency key could not be claimed',
|
||||
);
|
||||
}
|
||||
if (stored.expired) {
|
||||
this.metrics.increment('idempotency.released');
|
||||
await this.idempotency.forget(
|
||||
currentUser.id,
|
||||
path,
|
||||
rawKey,
|
||||
ttl,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (stored.request_fingerprint !== fingerprint) {
|
||||
this.metrics.increment('idempotency.conflict');
|
||||
throw new ConflictException(
|
||||
'Idempotency key reused with a different body',
|
||||
);
|
||||
}
|
||||
if (!stored.is_member) throw new NotFoundException();
|
||||
this.metrics.increment('idempotency.replay');
|
||||
// Bodies stored before attachments existed carry no attachment_ids.
|
||||
return {
|
||||
...stored.response_body,
|
||||
attachment_ids: stored.response_body.attachment_ids ?? [],
|
||||
};
|
||||
}
|
||||
throw new ServiceUnavailableException(
|
||||
'Idempotency key could not be claimed',
|
||||
);
|
||||
}
|
||||
|
||||
// Expired claims are storage hygiene, not part of the request: the pass runs
|
||||
// outside the request path, at most once per PURGE_EVERY_REQUESTS successful
|
||||
// writes, and its failure never changes the client's result.
|
||||
private scheduleExpiredPurge(): void {
|
||||
this.requestsSincePurge += 1;
|
||||
if (this.requestsSincePurge < PURGE_EVERY_REQUESTS) return;
|
||||
this.requestsSincePurge = 0;
|
||||
const ttl = this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS');
|
||||
void this.idempotency
|
||||
.purgeExpired(ttl)
|
||||
.then((purged) => {
|
||||
if (purged > 0) this.metrics.increment('idempotency.purged');
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
this.metrics.increment('idempotency.purge_error');
|
||||
this.logger.warn(
|
||||
`Idempotency purge failed: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async list(
|
||||
chatId: string,
|
||||
currentUser: User,
|
||||
limit: number,
|
||||
cursorValue?: string,
|
||||
): Promise<Page<Message>> {
|
||||
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 Page<Message>;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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 { resolveInstanceId } from '../config/instance-id.js';
|
||||
import { MetricsService } from './metrics.service.js';
|
||||
|
||||
@Controller('internal')
|
||||
export class MetricsController {
|
||||
private readonly instanceId: string;
|
||||
private readonly buildId: string;
|
||||
|
||||
constructor(
|
||||
private readonly config: ConfigService<AppConfig>,
|
||||
private readonly metrics: MetricsService,
|
||||
) {
|
||||
this.instanceId = resolveInstanceId(config);
|
||||
this.buildId = process.env.BUILD_ID ?? 'unknown';
|
||||
}
|
||||
|
||||
@Get('metrics')
|
||||
get(@Headers('authorization') authorization?: string) {
|
||||
this.requireToken(authorization);
|
||||
return {
|
||||
...this.metrics.snapshot(),
|
||||
instance_id: this.instanceId,
|
||||
build_id: this.buildId,
|
||||
};
|
||||
}
|
||||
|
||||
@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,77 @@
|
||||
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);
|
||||
const snapshot = metrics.snapshot();
|
||||
expect(snapshot.counters).toEqual({ cache_hit: 2 });
|
||||
expect(snapshot.latency_ms).toEqual({
|
||||
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,
|
||||
});
|
||||
});
|
||||
|
||||
it('adds byte counters and ignores invalid amounts', () => {
|
||||
const metrics = new MetricsService();
|
||||
metrics.add('bytes', 100);
|
||||
metrics.add('bytes', 28);
|
||||
for (const value of [-1, NaN, Infinity]) metrics.add('bytes', value);
|
||||
expect(metrics.snapshot().counters.bytes).toBe(128);
|
||||
});
|
||||
|
||||
it('tracks memory peaks until reset', () => {
|
||||
const metrics = new MetricsService();
|
||||
const ballast = Buffer.alloc(32 * 1024 * 1024, 1);
|
||||
const during = metrics.snapshot().memory_peak_bytes.array_buffers;
|
||||
expect(during).toBeGreaterThanOrEqual(ballast.length);
|
||||
ballast.fill(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
|
||||
const LATENCY_SAMPLE_CAPACITY = 4096;
|
||||
|
||||
type LatencySnapshot = {
|
||||
count: number;
|
||||
sample_count: number;
|
||||
p50: number;
|
||||
p95: number;
|
||||
p99: number;
|
||||
max: number;
|
||||
};
|
||||
|
||||
const MEMORY_SAMPLE_INTERVAL_MS = 50;
|
||||
|
||||
type MemoryUsage = {
|
||||
rss: number;
|
||||
heap_used: number;
|
||||
external: number;
|
||||
array_buffers: number;
|
||||
};
|
||||
|
||||
function currentMemory(): MemoryUsage {
|
||||
const usage = process.memoryUsage();
|
||||
return {
|
||||
rss: usage.rss,
|
||||
heap_used: usage.heapUsed,
|
||||
external: usage.external,
|
||||
array_buffers: usage.arrayBuffers,
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MetricsService implements OnModuleInit, OnModuleDestroy {
|
||||
private memoryPeak: MemoryUsage = currentMemory();
|
||||
private memoryTimer: NodeJS.Timeout | undefined;
|
||||
private readonly counters: Record<string, number> = {};
|
||||
private readonly latencies: number[] = [];
|
||||
private latencyCount = 0;
|
||||
private maximumLatency = 0;
|
||||
private nextSample = 0;
|
||||
|
||||
onModuleInit(): void {
|
||||
this.memoryTimer = setInterval(
|
||||
() => this.sampleMemory(),
|
||||
MEMORY_SAMPLE_INTERVAL_MS,
|
||||
);
|
||||
this.memoryTimer.unref();
|
||||
}
|
||||
|
||||
onModuleDestroy(): void {
|
||||
if (this.memoryTimer) clearInterval(this.memoryTimer);
|
||||
this.memoryTimer = undefined;
|
||||
}
|
||||
|
||||
add(name: string, amount: number): void {
|
||||
if (!Number.isFinite(amount) || amount < 0) return;
|
||||
this.counters[name] = (this.counters[name] ?? 0) + amount;
|
||||
}
|
||||
|
||||
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;
|
||||
memory_bytes: MemoryUsage;
|
||||
memory_peak_bytes: MemoryUsage;
|
||||
} {
|
||||
this.sampleMemory();
|
||||
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,
|
||||
},
|
||||
memory_bytes: currentMemory(),
|
||||
memory_peak_bytes: { ...this.memoryPeak },
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
this.memoryPeak = currentMemory();
|
||||
}
|
||||
|
||||
private sampleMemory(): void {
|
||||
const now = currentMemory();
|
||||
const peak = this.memoryPeak;
|
||||
peak.rss = Math.max(peak.rss, now.rss);
|
||||
peak.heap_used = Math.max(peak.heap_used, now.heap_used);
|
||||
peak.external = Math.max(peak.external, now.external);
|
||||
peak.array_buffers = Math.max(peak.array_buffers, now.array_buffers);
|
||||
}
|
||||
|
||||
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,145 @@
|
||||
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');
|
||||
// AbortSignal.timeout ограничивает именно пробу: обычные GET/SET остаются
|
||||
// без командного таймаута, а замороженный Redis проваливает готовность
|
||||
// в бюджет, который короче timeout check балансировщика.
|
||||
const timeout = AbortSignal.timeout(
|
||||
this.config.getOrThrow('HEALTH_TIMEOUT_MS'),
|
||||
);
|
||||
await this.client.withAbortSignal(timeout).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 {}
|
||||
@@ -0,0 +1,192 @@
|
||||
import {
|
||||
DeleteObjectCommand,
|
||||
GetObjectCommand,
|
||||
HeadObjectCommand,
|
||||
PutObjectCommand,
|
||||
S3Client,
|
||||
} from '@aws-sdk/client-s3';
|
||||
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
|
||||
import { NodeHttpHandler } from '@smithy/node-http-handler';
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import http from 'node:http';
|
||||
import { Readable } from 'node:stream';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
|
||||
export class ObjectStorageUnavailableError extends ServiceUnavailableException {
|
||||
constructor() {
|
||||
super('Object storage unavailable');
|
||||
}
|
||||
}
|
||||
|
||||
export type PresignPutOptions = {
|
||||
contentType: string;
|
||||
contentLength: number;
|
||||
checksumSha256Base64: string;
|
||||
expiresInSeconds: number;
|
||||
};
|
||||
|
||||
function isMissingKey(error: unknown): boolean {
|
||||
const candidate = error as {
|
||||
name?: string;
|
||||
$metadata?: { httpStatusCode?: number };
|
||||
};
|
||||
return (
|
||||
candidate?.name === 'NoSuchKey' ||
|
||||
candidate?.name === 'NotFound' ||
|
||||
candidate?.$metadata?.httpStatusCode === 404
|
||||
);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ObjectStorage {
|
||||
private readonly logger = new Logger(ObjectStorage.name);
|
||||
private readonly bucket: string;
|
||||
private readonly internal: S3Client;
|
||||
private readonly presign: S3Client;
|
||||
|
||||
constructor(config: ConfigService<AppConfig>) {
|
||||
this.bucket = config.getOrThrow('S3_BUCKET');
|
||||
const common = {
|
||||
region: config.getOrThrow('S3_REGION'),
|
||||
forcePathStyle: true,
|
||||
credentials: {
|
||||
accessKeyId: config.getOrThrow('S3_ACCESS_KEY_ID'),
|
||||
secretAccessKey: config.getOrThrow('S3_SECRET_ACCESS_KEY'),
|
||||
},
|
||||
// Поток нельзя повторить: повтор — решение клиента API.
|
||||
maxAttempts: 1,
|
||||
requestChecksumCalculation: 'WHEN_REQUIRED' as const,
|
||||
responseChecksumValidation: 'WHEN_REQUIRED' as const,
|
||||
// requestTimeout bounds a request until its response arrives and,
|
||||
// with throwOnRequestTimeout, actually fails it (otherwise smithy
|
||||
// only logs a warning); socketTimeout bounds a stalled body read.
|
||||
// A hung S3 therefore costs at most S3_REQUEST_TIMEOUT_MS per call.
|
||||
requestHandler: new NodeHttpHandler({
|
||||
connectionTimeout: config.getOrThrow('S3_CONNECT_TIMEOUT_MS'),
|
||||
requestTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'),
|
||||
throwOnRequestTimeout: true,
|
||||
socketTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'),
|
||||
httpAgent: new http.Agent({ keepAlive: true, maxSockets: 64 }),
|
||||
}),
|
||||
};
|
||||
this.internal = new S3Client({
|
||||
...common,
|
||||
endpoint: config.getOrThrow('S3_ENDPOINT'),
|
||||
});
|
||||
// Сеть не использует: только подпись URL для клиента.
|
||||
this.presign = new S3Client({
|
||||
...common,
|
||||
endpoint: config.getOrThrow('S3_PUBLIC_ENDPOINT'),
|
||||
});
|
||||
}
|
||||
|
||||
objectKey(attachmentId: string): string {
|
||||
return `attachments/${attachmentId}/original`;
|
||||
}
|
||||
|
||||
async putStream(
|
||||
key: string,
|
||||
body: Readable,
|
||||
contentLength: number,
|
||||
contentType: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.internal.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: this.bucket,
|
||||
Key: key,
|
||||
Body: body,
|
||||
ContentLength: contentLength,
|
||||
ContentType: contentType,
|
||||
}),
|
||||
// The upload deadline (UPLOAD_TIMEOUT_MS, via `signal`) bounds the
|
||||
// PUT: it lasts as long as the client sends, not S3_REQUEST_TIMEOUT_MS.
|
||||
{ abortSignal: signal, requestTimeout: 0 },
|
||||
);
|
||||
} catch (error) {
|
||||
throw this.fail('put', error);
|
||||
}
|
||||
}
|
||||
|
||||
async getStream(
|
||||
key: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Readable | null> {
|
||||
try {
|
||||
const result = await this.internal.send(
|
||||
new GetObjectCommand({ Bucket: this.bucket, Key: key }),
|
||||
{ abortSignal: signal },
|
||||
);
|
||||
return result.Body as Readable;
|
||||
} catch (error) {
|
||||
if (isMissingKey(error)) return null;
|
||||
throw this.fail('get', error);
|
||||
}
|
||||
}
|
||||
|
||||
async head(
|
||||
key: string,
|
||||
): Promise<{ size: number; checksumSha256?: string } | null> {
|
||||
try {
|
||||
const result = await this.internal.send(
|
||||
new HeadObjectCommand({
|
||||
Bucket: this.bucket,
|
||||
Key: key,
|
||||
ChecksumMode: 'ENABLED',
|
||||
}),
|
||||
);
|
||||
return {
|
||||
size: Number(result.ContentLength ?? 0),
|
||||
checksumSha256: result.ChecksumSHA256,
|
||||
};
|
||||
} catch (error) {
|
||||
if (isMissingKey(error)) return null;
|
||||
throw this.fail('head', error);
|
||||
}
|
||||
}
|
||||
|
||||
async delete(key: string): Promise<void> {
|
||||
try {
|
||||
await this.internal.send(
|
||||
new DeleteObjectCommand({ Bucket: this.bucket, Key: key }),
|
||||
);
|
||||
} catch (error) {
|
||||
if (isMissingKey(error)) return;
|
||||
throw this.fail('delete', error);
|
||||
}
|
||||
}
|
||||
|
||||
async presignPut(key: string, options: PresignPutOptions): Promise<string> {
|
||||
return getSignedUrl(
|
||||
this.presign,
|
||||
new PutObjectCommand({
|
||||
Bucket: this.bucket,
|
||||
Key: key,
|
||||
ContentType: options.contentType,
|
||||
ContentLength: options.contentLength,
|
||||
ChecksumSHA256: options.checksumSha256Base64,
|
||||
}),
|
||||
{
|
||||
expiresIn: options.expiresInSeconds,
|
||||
signableHeaders: new Set([
|
||||
'content-type',
|
||||
'content-length',
|
||||
'x-amz-checksum-sha256',
|
||||
]),
|
||||
unhoistableHeaders: new Set(['x-amz-checksum-sha256']),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private fail(operation: string, error: unknown): Error {
|
||||
const name = (error as { name?: string })?.name ?? 'UnknownError';
|
||||
this.logger.warn(`S3 ${operation} failed: ${name}`);
|
||||
return new ObjectStorageUnavailableError();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ObjectStorage } from './object-storage.js';
|
||||
|
||||
@Module({ providers: [ObjectStorage], exports: [ObjectStorage] })
|
||||
export class StorageModule {}
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
import { User } from './users/user.ts';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
currentUser?: User;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { IsString, Matches } from 'class-validator';
|
||||
import { CodePointLength } from '../../common/validation/code-point-length.js';
|
||||
|
||||
export class CreateUserDTO {
|
||||
@IsString()
|
||||
@Matches(/^[a-z0-9_]{3,32}$/)
|
||||
username!: string;
|
||||
|
||||
@IsString()
|
||||
@CodePointLength(1, 100)
|
||||
@Matches(/\S/u, {
|
||||
message: 'display_name must contain a non-whitespace character',
|
||||
})
|
||||
display_name!: string;
|
||||
|
||||
@IsString()
|
||||
@CodePointLength(12, 128)
|
||||
@Matches(/\S/u, {
|
||||
message: 'password must contain a non-whitespace character',
|
||||
})
|
||||
password!: string;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export type User = {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
created_at: string;
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
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 {
|
||||
constructor(private readonly usersService: UsersService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() body: CreateUserDTO) {
|
||||
return this.usersService.create(body);
|
||||
}
|
||||
|
||||
@Get('/me')
|
||||
@UseGuards(CurrentUserGuard)
|
||||
getMe(@CurrentUser() currentUser: User) {
|
||||
return currentUser;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
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, RedisModule, MetricsModule],
|
||||
})
|
||||
export class UsersModule {}
|
||||
@@ -0,0 +1,71 @@
|
||||
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 {
|
||||
constructor(private readonly database: DatabaseClient) {}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { 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 { UsersRepository } from './users.repository.js';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private readonly usersRepository: UsersRepository) {}
|
||||
|
||||
async create(input: CreateUserDTO): Promise<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,
|
||||
password_hash: passwordHash,
|
||||
});
|
||||
}
|
||||
|
||||
findById(id: string): Promise<User | undefined> {
|
||||
return this.usersRepository.findById(id);
|
||||
}
|
||||
|
||||
findByUsername(username: string) {
|
||||
return this.usersRepository.findByUsername(username);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,674 @@
|
||||
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 type { SessionResponse } from '../src/auth/auth.service.js';
|
||||
import type { Chat } from '../src/chats/chat.js';
|
||||
import type { ApiErrorBody } from '../src/common/errors/api-error.js';
|
||||
import type { Page } from '../src/common/http/page.js';
|
||||
import type { Message } from '../src/messages/message.js';
|
||||
import type { User } from '../src/users/user.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>;
|
||||
|
||||
type Actor = { user: User; password: string; token: string };
|
||||
type HttpResult<T> = { body: T; response: Response };
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
function json(
|
||||
body: unknown,
|
||||
headers: Record<string, string> = {},
|
||||
): RequestInit {
|
||||
return {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
};
|
||||
}
|
||||
|
||||
function basic(username: string, secret: string): string {
|
||||
return `Basic ${Buffer.from(`${username}:${secret}`, 'utf8').toString('base64')}`;
|
||||
}
|
||||
|
||||
function bearer(token: string): Record<string, string> {
|
||||
return { authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
function idempotencyKey(): Record<string, string> {
|
||||
return { 'idempotency-key': randomUUID().replaceAll('-', '') };
|
||||
}
|
||||
|
||||
function messageHeaders(token: string): Record<string, string> {
|
||||
return { ...bearer(token), ...idempotencyKey() };
|
||||
}
|
||||
|
||||
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<SessionResponse> {
|
||||
const result = await http<SessionResponse>('/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;
|
||||
}
|
||||
|
||||
async function actor(displayName?: string): Promise<Actor> {
|
||||
const user = await register(displayName);
|
||||
const session = await login(user);
|
||||
return { user, password, token: session.token };
|
||||
}
|
||||
|
||||
function expectError(
|
||||
result: HttpResult<ApiErrorBody>,
|
||||
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'),
|
||||
);
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
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('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<ApiErrorBody>('/api/v1/users/me');
|
||||
expectError(denied, 401, 'unauthorized');
|
||||
expect(denied.response.headers.get('www-authenticate')).toBe(
|
||||
bearerChallenge,
|
||||
);
|
||||
});
|
||||
|
||||
it('measures string lengths in Unicode code points', async () => {
|
||||
const emoji = '🔐';
|
||||
const username = (suffix: string) =>
|
||||
`e2e_${runId}_${suffix}`.slice(0, 32);
|
||||
const rejected = await http<ApiErrorBody>(
|
||||
'/api/v1/users',
|
||||
json({
|
||||
username: username('cp_short'),
|
||||
display_name: 'Code points',
|
||||
password: emoji.repeat(11),
|
||||
}),
|
||||
);
|
||||
expectError(rejected, 400, 'invalid_request');
|
||||
const tooLongPassword = await http<ApiErrorBody>(
|
||||
'/api/v1/users',
|
||||
json({
|
||||
username: username('cp_long'),
|
||||
display_name: 'Code points',
|
||||
password: emoji.repeat(129),
|
||||
}),
|
||||
);
|
||||
expectError(tooLongPassword, 400, 'invalid_request');
|
||||
const tooLongName = await http<ApiErrorBody>(
|
||||
'/api/v1/users',
|
||||
json({
|
||||
username: username('cp_name'),
|
||||
display_name: emoji.repeat(101),
|
||||
password,
|
||||
}),
|
||||
);
|
||||
expectError(tooLongName, 400, 'invalid_request');
|
||||
|
||||
const shortUsername = username('cp_ok');
|
||||
usernames.push(shortUsername);
|
||||
const boundaryPassword = emoji.repeat(12);
|
||||
const created = await http<User>(
|
||||
'/api/v1/users',
|
||||
json({
|
||||
username: shortUsername,
|
||||
display_name: emoji.repeat(100),
|
||||
password: boundaryPassword,
|
||||
}),
|
||||
);
|
||||
expect(created.response.status).toBe(201);
|
||||
expect([...created.body.display_name].length).toBe(100);
|
||||
// The stored password keeps all 12 code points: authentication works.
|
||||
const session = await http<SessionResponse>('/api/v1/auth/sessions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: basic(shortUsername, boundaryPassword),
|
||||
},
|
||||
});
|
||||
expect(session.response.status).toBe(201);
|
||||
tokens.push(session.body.token);
|
||||
|
||||
const longTitleRejected = await http<ApiErrorBody>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: emoji.repeat(101), member_ids: [created.body.id] },
|
||||
bearer(session.body.token),
|
||||
),
|
||||
);
|
||||
expectError(longTitleRejected, 400, 'invalid_request');
|
||||
const longTitle = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: emoji.repeat(100), member_ids: [created.body.id] },
|
||||
bearer(session.body.token),
|
||||
),
|
||||
);
|
||||
expect(longTitle.response.status).toBe(201);
|
||||
const tooLongText = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${longTitle.body.id}/messages`,
|
||||
json({ text: emoji.repeat(4001) }, messageHeaders(session.body.token)),
|
||||
);
|
||||
expectError(tooLongText, 400, 'invalid_request');
|
||||
const boundaryText = await http<Message>(
|
||||
`/api/v1/chats/${longTitle.body.id}/messages`,
|
||||
json({ text: emoji.repeat(4000) }, messageHeaders(session.body.token)),
|
||||
);
|
||||
expect(boundaryText.response.status).toBe(201);
|
||||
expect([...boundaryText.body.text].length).toBe(4000);
|
||||
});
|
||||
|
||||
it('rejects whitespace-only and too-short credentials', async () => {
|
||||
const username = `e2e_${runId}_${sequence++}`.slice(0, 32);
|
||||
usernames.push(username);
|
||||
const cases = [
|
||||
{ password: ' '.repeat(12), display_name: 'Пользователь' },
|
||||
{ password: '\t'.repeat(16), display_name: 'Пользователь' },
|
||||
{ password: 'short-pass', display_name: 'Пользователь' },
|
||||
{ password, display_name: ' ' },
|
||||
];
|
||||
for (const body of cases) {
|
||||
const result = await http<ApiErrorBody>(
|
||||
'/api/v1/users',
|
||||
json({ username, ...body }),
|
||||
);
|
||||
expectError(result, 400, 'invalid_request');
|
||||
}
|
||||
const accepted = await http<User>(
|
||||
'/api/v1/users',
|
||||
json({ username, display_name: 'Пользователь', password }),
|
||||
);
|
||||
expect(accepted.response.status).toBe(201);
|
||||
});
|
||||
|
||||
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<ApiErrorBody>('/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<ApiErrorBody>('/api/v1/auth/sessions', {
|
||||
...json({ unexpected: true }),
|
||||
headers: { authorization: basic(user.username, password) },
|
||||
});
|
||||
expectError(bodyResult, 400, 'invalid_request');
|
||||
});
|
||||
|
||||
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('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<ApiErrorBody>('/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<ApiErrorBody>('/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<ApiErrorBody>('/api/v1/users/me', {
|
||||
headers: bearer(alice.token),
|
||||
});
|
||||
expectError(replay, 401, 'unauthorized');
|
||||
});
|
||||
|
||||
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<ApiErrorBody>(
|
||||
'/api/v1/chats',
|
||||
json(
|
||||
{ title: 'unknown', member_ids: [alice.user.id, randomUUID()] },
|
||||
bearer(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(unknown, 400, 'invalid_request');
|
||||
const leaked = await http<ApiErrorBody>(`/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<ApiErrorBody>(
|
||||
'/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<ApiErrorBody>(
|
||||
`/api/v1/chats/${created.body.id}`,
|
||||
{ headers: bearer(outsider.token) },
|
||||
);
|
||||
expectError(hidden, 404, 'not_found');
|
||||
});
|
||||
|
||||
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<ApiErrorBody>(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json(
|
||||
{ text: ' \n\t', sender_id: randomUUID() },
|
||||
messageHeaders(alice.token),
|
||||
),
|
||||
);
|
||||
expectError(blank, 400, 'invalid_request');
|
||||
const spoof = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${chat.body.id}/messages`,
|
||||
json(
|
||||
{ text: 'hello', sender_id: randomUUID() },
|
||||
messageHeaders(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' }, messageHeaders(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);
|
||||
});
|
||||
|
||||
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 }, messageHeaders(alice.token)),
|
||||
);
|
||||
expect(sent.response.status).toBe(201);
|
||||
}
|
||||
const invalidLimit = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?limit=101`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expectError(invalidLimit, 400, 'invalid_request');
|
||||
const invalidCursor = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?cursor=not-a-cursor`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expectError(invalidCursor, 400, 'invalid_request');
|
||||
const rolledOver = http<ApiErrorBody>(
|
||||
`/api/v1/chats/${chat.body.id}/messages?cursor=${encodeURIComponent(
|
||||
Buffer.from(
|
||||
JSON.stringify({
|
||||
scope: `messages:${chat.body.id}`,
|
||||
created_at: '2026-02-31T00:00:00.000Z',
|
||||
id: randomUUID(),
|
||||
}),
|
||||
'utf8',
|
||||
).toString('base64url'),
|
||||
)}`,
|
||||
{ headers: bearer(alice.token) },
|
||||
);
|
||||
expectError(await rolledOver, 400, 'invalid_request');
|
||||
const malformed = await http<ApiErrorBody>('/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<ApiErrorBody>('/api/v1/users/me', {
|
||||
headers: bearer(session.token),
|
||||
});
|
||||
expectError(expired, 401, 'unauthorized');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// lab3: the Idempotency-Key contract of POST /chats/{id}/messages. The suite is
|
||||
// black-box, so these assertions hold for one replica and for a load-balanced
|
||||
// fleet alike.
|
||||
describe('message idempotency', () => {
|
||||
async function chatFor(token: string, memberIds: string[]): Promise<string> {
|
||||
const created = await http<Chat>(
|
||||
'/api/v1/chats',
|
||||
json({ title: `idempotency-${runId}`, member_ids: memberIds }, bearer(token)),
|
||||
);
|
||||
expect(created.response.status).toBe(201);
|
||||
return created.body.id;
|
||||
}
|
||||
|
||||
async function textsIn(chatId: string, token: string): Promise<string[]> {
|
||||
const page = await http<Page<Message>>(
|
||||
`/api/v1/chats/${chatId}/messages?limit=100`,
|
||||
{ headers: bearer(token) },
|
||||
);
|
||||
expect(page.response.status).toBe(200);
|
||||
return page.body.items.map((item) => item.text);
|
||||
}
|
||||
|
||||
it('requires a well-formed Idempotency-Key', async () => {
|
||||
const alice = await actor();
|
||||
const chatId = await chatFor(alice.token, [alice.user.id]);
|
||||
const path = `/api/v1/chats/${chatId}/messages`;
|
||||
const missing = await http<ApiErrorBody>(
|
||||
path,
|
||||
json({ text: 'без ключа' }, bearer(alice.token)),
|
||||
);
|
||||
expectError(missing, 400, 'invalid_request');
|
||||
for (const key of ['has space', 'comma,separated', 'x'.repeat(129)]) {
|
||||
const malformed = await http<ApiErrorBody>(
|
||||
path,
|
||||
json({ text: 'плохой ключ' }, { ...bearer(alice.token), 'idempotency-key': key }),
|
||||
);
|
||||
expectError(malformed, 400, 'invalid_request');
|
||||
}
|
||||
});
|
||||
|
||||
it('replays the stored response and conflicts on a different body', async () => {
|
||||
const alice = await actor();
|
||||
const chatId = await chatFor(alice.token, [alice.user.id]);
|
||||
const path = `/api/v1/chats/${chatId}/messages`;
|
||||
const key = randomUUID().replaceAll('-', '');
|
||||
const headers = { ...bearer(alice.token), 'idempotency-key': key };
|
||||
const text = `повтор ${runId}`;
|
||||
|
||||
const first = await http<Message>(path, json({ text }, headers));
|
||||
expect(first.response.status).toBe(201);
|
||||
const replayed = await http<Message>(path, json({ text }, headers));
|
||||
expect(replayed.response.status).toBe(201);
|
||||
expect(replayed.body).toEqual(first.body);
|
||||
|
||||
const conflict = await http<ApiErrorBody>(
|
||||
path,
|
||||
json({ text: 'другой body' }, headers),
|
||||
);
|
||||
expectError(conflict, 409, 'conflict');
|
||||
|
||||
expect(await textsIn(chatId, alice.token)).toEqual([text]);
|
||||
});
|
||||
|
||||
it('creates exactly one message for concurrent requests with one key', async () => {
|
||||
const alice = await actor();
|
||||
const chatId = await chatFor(alice.token, [alice.user.id]);
|
||||
const path = `/api/v1/chats/${chatId}/messages`;
|
||||
const headers = { ...bearer(alice.token), ...idempotencyKey() };
|
||||
const text = `конкурентный повтор ${runId}`;
|
||||
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 8 }, () => http<Message>(path, json({ text }, headers))),
|
||||
);
|
||||
for (const result of results) expect(result.response.status).toBe(201);
|
||||
const ids = new Set(results.map((result) => result.body.id));
|
||||
expect(
|
||||
ids.size,
|
||||
'one key must resolve to exactly one message across replicas',
|
||||
).toBe(1);
|
||||
expect(await textsIn(chatId, alice.token)).toEqual([text]);
|
||||
});
|
||||
|
||||
it('replays a key created by another replica', async () => {
|
||||
// lab3: повтор с тем же ключом может прийти на любую реплику, поэтому
|
||||
// проверяем не только сам повтор, но и то, что его обслужила другая реплика
|
||||
// (иначе тест не отличал бы общий журнал от локального состояния процесса).
|
||||
const alice = await actor();
|
||||
const chatId = await chatFor(alice.token, [alice.user.id]);
|
||||
const path = `/api/v1/chats/${chatId}/messages`;
|
||||
const key = randomUUID().replaceAll('-', '');
|
||||
const headers = { ...bearer(alice.token), 'idempotency-key': key };
|
||||
|
||||
const first = await http<Message>(path, json({ text: 'переключение реплики' }, headers));
|
||||
expect(first.response.status).toBe(201);
|
||||
const firstInstance = first.response.headers.get('x-instance-id');
|
||||
expect(firstInstance).toBeTruthy();
|
||||
|
||||
let replay = first;
|
||||
let replayInstance = firstInstance;
|
||||
for (let attempt = 0; attempt < 12 && replayInstance === firstInstance; attempt += 1) {
|
||||
replay = await http<Message>(path, json({ text: 'переключение реплики' }, headers));
|
||||
expect(replay.response.status).toBe(201);
|
||||
replayInstance = replay.response.headers.get('x-instance-id');
|
||||
}
|
||||
expect(
|
||||
replayInstance,
|
||||
'повтор должен был прийти на другую реплику (round-robin за LB)',
|
||||
).not.toBe(firstInstance);
|
||||
expect(replay.body).toEqual(first.body);
|
||||
expect(await textsIn(chatId, alice.token)).toEqual(['переключение реплики']);
|
||||
});
|
||||
|
||||
it('scopes the key per user and per chat path', async () => {
|
||||
const alice = await actor();
|
||||
const bob = await actor();
|
||||
const outsider = await actor();
|
||||
const chatId = await chatFor(alice.token, [alice.user.id, bob.user.id]);
|
||||
const path = `/api/v1/chats/${chatId}/messages`;
|
||||
const key = randomUUID().replaceAll('-', '');
|
||||
const foreignChatId = await chatFor(outsider.token, [outsider.user.id]);
|
||||
|
||||
const denied = await http<ApiErrorBody>(
|
||||
`/api/v1/chats/${foreignChatId}/messages`,
|
||||
json({ text: 'чужое' }, { ...bearer(alice.token), 'idempotency-key': key }),
|
||||
);
|
||||
expectError(denied, 404, 'not_found');
|
||||
|
||||
const mine = await http<Message>(
|
||||
path,
|
||||
json({ text: 'своё' }, { ...bearer(alice.token), 'idempotency-key': key }),
|
||||
);
|
||||
expect(mine.response.status).toBe(201);
|
||||
const other = await http<Message>(
|
||||
path,
|
||||
json({ text: 'своё' }, { ...bearer(bob.token), 'idempotency-key': key }),
|
||||
);
|
||||
expect(other.response.status).toBe(201);
|
||||
expect(other.body.id).not.toBe(mine.body.id);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user