feat: lab2 done

This commit is contained in:
2026-10-09 15:48:03 +03:00
parent f743ee10a2
commit 575f8ee386
104 changed files with 7038 additions and 1099 deletions
+145 -87
View File
@@ -1,114 +1,172 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
</p>
# app — API мессенджера (лабораторная 2)
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
NestJS 12 + Fastify, ESM TypeScript. PostgreSQL — источник истины бизнес-данных,
Redis — серверные Bearer-сессии и производный кэш истории сообщений.
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
Общая документация (в корне репозитория):
## Description
| Документ | Что содержит |
|---|---|
| [`../REPORT.md`](../REPORT.md) | архитектура, схема данных, транзакции, политика кэша, команды, результаты проверок и трека 1 |
| [`../evidence/README.md`](../evidence/README.md) | индекс доказательств: что подтверждено и как это воспроизвести |
| [`../bruno/README.md`](../bruno/README.md) | коллекция ручных запросов ко всем эндпоинтам |
| [`../contracts/openapi.json`](../contracts/openapi.json) | нормативный контракт API |
| [`../tests/README.md`](../tests/README.md) | публичные проверки репозитория (`make check`, `make test`, persistence) |
| [`../docs/architecture/README.md`](../docs/architecture/README.md) | граф модулей NestJS (`npm run graph`) |
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Что внутри
## Project setup
```bash
$ npm install
```text
src/
main.ts bootstrap: Fastify, ValidationPipe, shutdown hooks
app.module.ts сборка модулей приложения
config/ Zod-схема env + глобальный ConfigModule
database/ pg.Pool, транзакции, миграции (001, 002)
redis/ клиент Redis (AOF-совместимый, без offline queue)
auth/ Basic-вход, Redis-сессии, logout
users/ регистрация (Argon2id), профиль
chats/ создание чата в транзакции, список и чтение
messages/ отправка сообщения, keyset-история
cache/ версионированный кэш истории + lock на страницу
metrics/ /internal/metrics и /internal/metrics/reset
health/ liveness/readiness с проверкой зависимостей
common/ guard, exception filter, request-id, cursor, errors
test/
app.e2e-spec.ts black-box набор против запущенного API (PG + Redis)
scripts/
graph-modules.ts генератор графа зависимостей (nestjs-spelunker)
```
## Compile and run the project
Принципы: raw `pg.Pool` без ORM, параметризованные запросы, никаких in-memory
хранилищ в боевых путях; кэш — производное состояние и всегда допускает
восстановление из PostgreSQL; отказ зависимости даёт ограниченную ошибку
(`503`), а не аварийное завершение процесса.
```bash
# development
$ npm run start
## Быстрый старт
# watch mode
$ npm run start:dev
Рекомендуемый путь — весь стенд из корня репозитория (PostgreSQL, Redis, миграции, API):
# production mode
$ npm run start:prod
```sh
cd ..
cp .env.example .env
password=$(openssl rand -hex 32)
sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$password/" .env
sed -i "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://messenger:$password@postgres:5432/messenger|" .env
docker compose --env-file .env up -d --build
curl -fsS http://localhost:8080/health/ready
```
## Run tests
Локальный запуск без Docker (нужны доступные PostgreSQL и Redis):
```bash
# unit tests
$ npm run test
```sh
cd app
npm ci
npm run build
# e2e tests
$ npm run test:e2e
export DATABASE_URL=postgresql://messenger:<password>@127.0.0.1:5432/messenger
export REDIS_URL=redis://127.0.0.1:6379
export APP_PORT=8080
node dist/database/migration.runner.js # применяет миграции из dist/database/migrations
# test coverage
$ npm run test:cov
npm run start:dev # или npm run start:prod после build
```
## Deployment
## Переменные окружения
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
Читаются только через конфигурационный слой (`src/config`), типы и диапазоны
проверяет Zod-схема на старте — при некорректном значении приложение падает
с понятной ошибкой.
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
| Переменная | По умолчанию | Назначение |
|---|---|---|
| `APP_HOST` / `APP_PORT` | `0.0.0.0` / `8080` | адрес прослушивания |
| `APP_ENV` | `lab` | метка окружения |
| `DATABASE_URL` | — (обязательна) | строка подключения PostgreSQL |
| `REDIS_URL` | — (обязательна) | строка подключения Redis |
| `DATABASE_POOL_MAX` | `10` | размер пула соединений |
| `DATABASE_CONNECTION_TIMEOUT_MS` | `5000` | таймаут установки соединения |
| `DATABASE_STATEMENT_TIMEOUT_MS` | `5000` | таймаут SQL-запроса |
| `SESSION_TTL_SECONDS` | `3600` | TTL сессии (минимум 2) |
| `CACHE_TTL_SECONDS` | `30` | TTL страницы истории в Redis |
| `CACHE_MODE` | `protected` | `protected` (lock на страницу) или `naive` (только для эксперимента) |
| `CACHE_LOCK_TTL_MS` | `1000` | TTL lock-а страницы |
| `CACHE_MISS_DELAY_MS` | `0` | искусственная пауза на промахе; влияет только на `naive` |
| `METRICS_TOKEN` | — (необязательна) | токен доступа к `/internal/metrics*`; без него endpoint закрыт |
| `DRAIN_DELAY_MS` | `5000` | окно дрейна при получении сигнала завершения |
```bash
$ npm install -g @nestjs/mau
$ mau deploy
Поддерживаются также `DATABASE_URL_FILE` / `REDIS_URL_FILE`: если заданы, значение
читается из файла (docker secrets / Swarm). Подробности и компромиссы —
[`../REPORT.md`](../REPORT.md), раздел «Конфигурация и секреты».
## Эндпоинты
Публичный контракт — [`../contracts/openapi.json`](../contracts/openapi.json).
| Метод и путь | Аутентификация | Назначение |
|---|---|---|
| `GET /health/live` | нет | процесс жив |
| `GET /health/ready` | нет | готовность: PostgreSQL и Redis доступны, иначе `503` |
| `POST /api/v1/users` | нет | регистрация с паролем (Argon2id) |
| `POST /api/v1/auth/sessions` | `Basic` | вход, выдаёт opaque Bearer-токен |
| `DELETE /api/v1/auth/sessions/current` | `Bearer` | отзыв текущей сессии, `204` |
| `GET /api/v1/users/me` | `Bearer` | текущий пользователь |
| `POST /api/v1/chats` | `Bearer` | создание чата (транзакция) |
| `GET /api/v1/chats` | `Bearer` | список доступных чатов |
| `GET /api/v1/chats/:chatId` | `Bearer` | чат по id (чужой — `404`) |
| `POST /api/v1/chats/:chatId/messages` | `Bearer` | отправка сообщения |
| `GET /api/v1/chats/:chatId/messages` | `Bearer` | история, keyset-пагинация `(created_at, id)` |
| `GET /internal/metrics` | `Bearer METRICS_TOKEN` | счётчики и агрегаты латентности |
| `POST /internal/metrics/reset` | `Bearer METRICS_TOKEN` | сброс счётчиков (`200`) |
Правила: `Basic` принимается только на создании сессии, бизнес-запросы — только
`Bearer`; заголовок `X-User-Id` не аутентифицирует и не подменяет владельца
сессии; истёкший, отозванный или неизвестный токен — `401` с соответствующим
`WWW-Authenticate`.
## npm-скрипты
| Команда | Что делает |
|---|---|
| `npm run build` | сборка в `dist/` |
| `npm run start:dev` | watch-режим |
| `npm run start:prod` | запуск собранного приложения (`node dist/main`) |
| `npm test` / `npm run test:unit` | unit-тесты (vitest) |
| `npm run test:e2e` | black-box набор против запущенного API (см. ниже) |
| `npm run lint` | oxlint по `src/` и `test/` |
| `npm run format` | prettier |
| `npm run graph` | граф модулей и провайдеров через nestjs-spelunker (пишет `../docs/architecture/`) |
## Тесты
Unit-тесты не требуют инфраструктуры:
```sh
npm test
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
Интеграционный набор работает по HTTP против запущенного стенда и дополнительно
подключается к PostgreSQL (очистка тестовых данных) и Redis:
## Observability
```sh
export API_BASE_URL=http://localhost:8080
export DATABASE_URL=postgresql://messenger:<password>@<pg-host>:5432/messenger
export REDIS_URL=redis://<redis-host>:6379
npm run test:e2e
```
In production applications, observability is essential for understanding how your system behaves, detecting issues early, and maintaining reliable performance.
Название `API_BASE_URL` (а не `BASE_URL`) выбрано потому, что Vitest сам
устанавливает `process.env.BASE_URL` в значение Vite base. Кейс истечения сессии
включается переменной `SESSION_TTL_SECONDS=2` и у запущенного API, и у набора.
[NestJS Observe](https://observe.nestjs.com) automatically instruments your NestJS application, giving you deep visibility into your system with minimal setup:
## Метрики
- **Distributed tracing:** Follow requests across services and understand how they flow through your system.
- **Waterfall analysis:** Visualize request execution and identify slow operations, bottlenecks, and unexpected delays.
- **Performance analysis:** Analyze application performance in real time and quickly pinpoint areas that need optimization.
- **Metrics:** Track key application and infrastructure metrics to understand system health and performance trends.
- **Logging:** Centralize and correlate logs with traces and other telemetry to make debugging easier.
- **Error tracking:** Detect errors quickly and investigate their root causes with the surrounding context.
- **SLA monitoring:** Track service-level objectives and identify when your application is approaching or exceeding defined thresholds.
- **Alarms and alerts:** Set up alerts for critical errors, performance degradation, SLA violations, and other anomalies so your team can react quickly.
`GET /internal/metrics` возвращает `{counters, latency_ms}`: именованные SQL-метки,
операции Redis, `cache_hit`/`cache_miss`/`cache_lock_wait`, `session_get/set/del`,
`request_count` и процентили латентности (буфер ограничен). Деградации
наблюдаемы отдельными счётчиками: `cache_fallback`, `cache_write_error`,
`cache_unlock_error`, `cache_lock_timeout`, `cache_corrupt_entry`,
`database.pool_error`, `database.rollback_error`, `redis.error`.
## Resources
Check out a few resources that may come in handy when working with NestJS:
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
- Auto-instrument your application with [NestJS Observer](https://observer.nestjs.com). Distributed tracing, metrics, and logging made easy. Error tracking and performance monitoring for your NestJS applications.
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
Счётчики локальны процессу: при нескольких репликах их нельзя суммировать как
распределённый снимок, а рестарт API обнуляет их (данные PostgreSQL и Redis при
этом не затрагиваются).