feat: init after lab 1

This commit is contained in:
2026-10-01 19:29:22 +03:00
parent 65003b6119
commit f743ee10a2
44 changed files with 8111 additions and 0 deletions
+29
View File
@@ -0,0 +1,29 @@
FROM node:25.7.0-slim AS build
WORKDIR /usr/src/app
COPY app/package.json app/package-lock.json ./
RUN npm ci
COPY app/ ./
RUN npm run build
FROM node:25.7.0-slim AS runtime
WORKDIR /usr/src/app
ENV NODE_ENV=production
ENV APP_PORT=8080
ENV DRAIN_DELAY_MS=5000
COPY --from=build /usr/src/app/package.json /usr/src/app/package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=build /usr/src/app/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"]
+59
View File
@@ -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
+6
View File
@@ -0,0 +1,6 @@
{
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 4,
"useTabs": true
}
+114
View File
@@ -0,0 +1,114 @@
<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>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<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
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Project setup
```bash
$ npm install
```
## Compile and run the project
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Run tests
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## 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.
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:
```bash
$ npm install -g @nestjs/mau
$ mau deploy
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
## Observability
In production applications, observability is essential for understanding how your system behaves, detecting issues early, and maintaining reliable performance.
[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.
## 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).
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
+10
View File
@@ -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
}
}
+6446
View File
File diff suppressed because it is too large Load Diff
+54
View File
@@ -0,0 +1,54 @@
{
"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",
"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
},
"dependencies": {
"@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",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"fastify": "^5.12.5",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1"
},
"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/supertest": "^7.0.0",
"@vitest/coverage-v8": "^4.1.2",
"oxlint": "^1.58.0",
"prettier": "^3.4.2",
"source-map-support": "^0.5.21",
"supertest": "^7.2.2",
"typescript": "^6.0.3",
"vite-tsconfig-paths": "^5.1.4",
"vitest": "^4.1.2"
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { ChatsModule } from './chats/chats.module.js';
import { HealthModule } from './health/health.module.js';
import { MessagesModule } from './messages/messages.module.js';
import { UsersModule } from './users/users.module.js';
@Module({
imports: [HealthModule, UsersModule, ChatsModule, MessagesModule],
})
export class AppModule {}
+6
View File
@@ -0,0 +1,6 @@
export type Chat = {
id: string;
title: string;
member_ids: string[];
created_at: string;
};
+54
View File
@@ -0,0 +1,54 @@
import {
BadRequestException,
Body,
Controller,
DefaultValuePipe,
Get,
Param,
ParseIntPipe,
ParseUUIDPipe,
Post,
Query,
Req,
UseGuards,
} from '@nestjs/common';
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
import type { FastifyRequest } from 'fastify';
import { ChatsService } from './chats.service.js';
import { CreateChatDto } from './dto/create-chat.dto.js';
@Controller('api/v1/chats')
@UseGuards(CurrentUserGuard)
export class ChatsController {
constructor(private readonly chatsService: ChatsService) {}
@Post()
create(@Body() body: CreateChatDto, @Req() request: FastifyRequest) {
return this.chatsService.create(body, request.currentUser!);
}
@Get()
list(
@Req() request: FastifyRequest,
@Query('limit', new DefaultValuePipe(50), new ParseIntPipe()) limit: number,
@Query('cursor') cursor?: string,
) {
if (limit < 1 || limit > 100) {
throw new BadRequestException('limit must be between 1 and 100');
}
return this.chatsService.listForUser(
request.currentUser!,
limit,
cursor,
);
}
@Get(':chatId')
get(
@Param('chatId', new ParseUUIDPipe()) chatId: string,
@Req() request: FastifyRequest,
) {
return this.chatsService.getForUser(chatId, request.currentUser!);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { ChatsController } from './chats.controller.js';
import { UsersModule } from '../users/users.module.js';
import { ChatsRepository } from './chats.repository.js';
import { ChatsService } from './chats.service.js';
@Module({
imports: [UsersModule],
controllers: [ChatsController],
providers: [ChatsRepository, ChatsService],
exports: [ChatsService],
})
export class ChatsModule {}
+19
View File
@@ -0,0 +1,19 @@
import { Injectable } from '@nestjs/common';
import { Chat } from './chat.js';
@Injectable()
export class ChatsRepository {
private readonly chatsById = new Map<string, Chat>();
save(chat: Chat): void {
this.chatsById.set(chat.id, chat);
}
findById(id: string): Chat | undefined {
return this.chatsById.get(id);
}
findAll(): Chat[] {
return Array.from(this.chatsById.values());
}
}
+95
View File
@@ -0,0 +1,95 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import {
decodeCursor,
encodeCursor,
isAfter,
} from '../common/http/cursor.js';
import type { User } from '../users/user.js';
import { UsersService } from '../users/users.service.js';
import type { Chat } from './chat.js';
import type { CreateChatDto } from './dto/create-chat.dto.js';
import { ChatsRepository } from './chats.repository.js';
@Injectable()
export class ChatsService {
constructor(
private readonly chatsRepository: ChatsRepository,
private readonly usersService: UsersService,
) {}
create(input: CreateChatDto, currentUser: User): Chat {
if (!input.member_ids.includes(currentUser.id)) {
throw new BadRequestException('Current user must be a chat member');
}
for (const memberId of input.member_ids) {
if (!this.usersService.findById(memberId)) {
throw new BadRequestException('Chat member does not exist');
}
}
const chat: Chat = {
id: randomUUID(),
title: input.title,
member_ids: [...input.member_ids],
created_at: new Date().toISOString(),
};
this.chatsRepository.save(chat);
return chat;
}
getForUser(chatId: string, currentUser: User): Chat {
const chat = this.chatsRepository.findById(chatId);
if (!chat || !chat.member_ids.includes(currentUser.id)) {
throw new NotFoundException();
}
return chat;
}
listForUser(
currentUser: User,
limit: number,
cursorValue?: string,
): { items: Chat[]; next_cursor: string | null } {
const scope = `chats:${currentUser.id}`;
const cursor = cursorValue
? decodeCursor(cursorValue, scope)
: undefined;
const chats = this.chatsRepository
.findAll()
.filter((chat) => chat.member_ids.includes(currentUser.id))
.sort((left, right) => {
const byDate = left.created_at.localeCompare(right.created_at);
return byDate !== 0 ? byDate : left.id.localeCompare(right.id);
});
const start = cursor
? chats.findIndex((chat) => isAfter(chat.created_at, chat.id, cursor))
: 0;
const visible = chats.slice(start < 0 ? chats.length : start);
const items = visible.slice(0, limit);
const hasMore = visible.length > limit;
const last = items.at(-1);
return {
items,
next_cursor:
hasMore && last
? encodeCursor({
scope,
created_at: last.created_at,
id: last.id,
})
: null,
};
}
}
+26
View File
@@ -0,0 +1,26 @@
import {
ArrayMaxSize,
ArrayMinSize,
ArrayUnique,
IsArray,
IsString,
IsUUID,
Length,
Matches,
} from 'class-validator';
export class CreateChatDto {
@IsString()
@Length(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[];
}
+43
View File
@@ -0,0 +1,43 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { isUUID } from 'class-validator';
import type { User } from '../../users/user.js';
import { UsersService } from '../../users/users.service.js';
export type RequestWithCurrentUser = {
headers: {
'x-user-id'?: string | string[];
};
currentUser?: User;
};
@Injectable()
export class CurrentUserGuard implements CanActivate {
constructor(private readonly usersService: UsersService) {}
canActivate(context: ExecutionContext): boolean {
const request = context
.switchToHttp()
.getRequest<RequestWithCurrentUser>();
const header = request.headers['x-user-id'];
if (typeof header !== 'string' || !isUUID(header)) {
throw new UnauthorizedException();
}
const user = this.usersService.findById(header);
if (!user) {
throw new UnauthorizedException();
}
request.currentUser = user;
return true;
}
}
@@ -0,0 +1,89 @@
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
type RequestWithId = {
requestId?: string;
};
type HttpResponse = {
header(name: string, value: string): void;
status(code: number): HttpResponse;
send(body: unknown): void;
};
function errorCodeForStatus(status: number): string {
switch (status) {
case HttpStatus.BAD_REQUEST:
return 'invalid_request';
case HttpStatus.UNAUTHORIZED:
return 'unauthorized';
case HttpStatus.NOT_FOUND:
return 'not_found';
case HttpStatus.CONFLICT:
return 'conflict';
case HttpStatus.PAYLOAD_TOO_LARGE:
return 'payload_too_large';
case HttpStatus.UNSUPPORTED_MEDIA_TYPE:
return 'unsupported_media_type';
case HttpStatus.TOO_MANY_REQUESTS:
return 'rate_limited';
case HttpStatus.SERVICE_UNAVAILABLE:
return 'unavailable';
default:
return 'internal_error';
}
}
@Catch()
export class ApiExceptionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
const context = host.switchToHttp();
const request = context.getRequest<RequestWithId>();
const response = context.getResponse<HttpResponse>();
const requestId = request.requestId ?? randomUUID();
request.requestId = requestId;
response.header('X-Request-Id', requestId);
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let message = 'Internal server error';
if (exception instanceof HttpException) {
status = exception.getStatus();
const exceptionResponse = exception.getResponse();
const rawMessage =
typeof exceptionResponse === 'object' &&
exceptionResponse !== null &&
'message' in exceptionResponse
? exceptionResponse.message
: undefined;
message = Array.isArray(rawMessage)
? rawMessage.join('; ')
: typeof rawMessage === 'string'
? rawMessage
: 'Request failed';
if (status === HttpStatus.NOT_FOUND) {
message = 'Resource not found';
}
}
response.status(status).send({
error: {
code: errorCodeForStatus(status),
message: message,
request_id: requestId,
},
});
}
}
+54
View File
@@ -0,0 +1,54 @@
import { BadRequestException } from '@nestjs/common';
export type Cursor = {
scope: string;
created_at: string;
id: string;
};
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 ||
parsed.created_at.length === 0 ||
parsed.id.length === 0
) {
throw new Error('invalid cursor');
}
return {
scope: parsed.scope,
created_at: parsed.created_at,
id: parsed.id,
};
} catch {
throw new BadRequestException('Invalid cursor');
}
}
export function isAfter(
createdAt: string,
id: string,
cursor: Cursor,
): boolean {
return (
createdAt > cursor.created_at ||
(createdAt === cursor.created_at && id > cursor.id)
);
}
@@ -0,0 +1,35 @@
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { Observable } from 'rxjs';
type RequestWithId = {
requestId?: string;
};
type ResponseWithHeader = {
header(name: string, value: string): void;
};
@Injectable()
export class RequestIdInterceptor implements NestInterceptor {
intercept(
context: ExecutionContext,
next: CallHandler<any>,
): Observable<any> | Promise<Observable<any>> {
const request = context.switchToHttp().getRequest<RequestWithId>();
const response = context.switchToHttp().getResponse<ResponseWithHeader>();
const requestId = randomUUID();
request.requestId = requestId;
response.header('X-Request-Id', requestId);
return next.handle();
}
}
+17
View File
@@ -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')
getReady() {
return this.healthService.getReadiness();
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { HealthController } from './health.controller.js';
import { HealthService } from './health.service.js';
@Module({
imports: [],
controllers: [HealthController],
providers: [HealthService],
})
export class HealthModule {}
+57
View File
@@ -0,0 +1,57 @@
import { ServiceUnavailableException } from '@nestjs/common';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { HealthService } from './health.service.js';
describe('HealthService', () => {
const originalDrainDelay = process.env.DRAIN_DELAY_MS;
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
if (originalDrainDelay === undefined) {
delete process.env.DRAIN_DELAY_MS;
} else {
process.env.DRAIN_DELAY_MS = originalDrainDelay;
}
});
it('reports live and ready before shutdown starts', () => {
const service = new HealthService();
expect(service.getLiveness()).toEqual({ status: 'ok' });
expect(service.getReadiness()).toEqual({ status: 'ok' });
});
it('keeps liveness healthy but rejects readiness while draining', () => {
const service = new HealthService();
service.setDraining();
expect(service.getLiveness()).toEqual({ status: 'ok' });
expect(() => service.getReadiness()).toThrow(ServiceUnavailableException);
expect(() => service.getReadiness()).toThrow('Service is shutting down');
});
it('waits for the configured drain window after a termination signal', async () => {
process.env.DRAIN_DELAY_MS = '5000';
const service = new HealthService();
const shutdown = service.beforeApplicationShutdown('SIGTERM');
await vi.advanceTimersByTimeAsync(4999);
expect(() => service.getReadiness()).toThrow('Service is shutting down');
await vi.advanceTimersByTimeAsync(1);
await expect(shutdown).resolves.toBeUndefined();
});
it('does not delay explicit application close without a signal', async () => {
process.env.DRAIN_DELAY_MS = '5000';
const service = new HealthService();
await expect(service.beforeApplicationShutdown()).resolves.toBeUndefined();
expect(() => service.getReadiness()).toThrow('Service is shutting down');
expect(vi.getTimerCount()).toBe(0);
});
});
+45
View File
@@ -0,0 +1,45 @@
import {
Injectable,
ServiceUnavailableException,
} from '@nestjs/common';
import type { BeforeApplicationShutdown } from '@nestjs/common';
@Injectable()
export class HealthService implements BeforeApplicationShutdown {
private ready = true;
private readonly drainDelayMs = this.readDrainDelay();
getLiveness() {
return { status: 'ok' as const };
}
getReadiness() {
if (!this.ready) {
throw new ServiceUnavailableException('Service is shutting down');
}
return { status: 'ok' as const };
}
setDraining(): void {
this.ready = false;
}
async beforeApplicationShutdown(signal?: string): Promise<void> {
this.setDraining();
// Explicit app.close() in tests should remain immediate. Signals get a
// drain window so orchestrators can observe readiness=503 before Nest
// closes the HTTP server.
if (signal && this.drainDelayMs > 0) {
await new Promise<void>((resolve) => {
setTimeout(resolve, this.drainDelayMs);
});
}
}
private readDrainDelay(): number {
const value = Number.parseInt(process.env.DRAIN_DELAY_MS ?? '5000', 10);
return Number.isFinite(value) && value >= 0 ? value : 5000;
}
}
+38
View File
@@ -0,0 +1,38 @@
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module.js';
import { ApiExceptionFilter } from './common/errors/api-exception.filter.js';
import { RequestIdInterceptor } from './common/http/request-id.interceptor.js';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({
logger: true,
}),
);
app.useGlobalInterceptors(new RequestIdInterceptor());
app.useGlobalFilters(new ApiExceptionFilter());
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
app.enableShutdownHooks();
const port = Number(process.env.APP_PORT ?? '8080');
const host = process.env.APP_HOST ?? '0.0.0.0';
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('APP_PORT must be an integer between 1 and 65535');
}
await app.listen(port, host);
}
await bootstrap();
@@ -0,0 +1,7 @@
import { IsString, Length } from 'class-validator';
export class CreateMessageDto {
@IsString()
@Length(1, 4000)
text!: string;
}
+7
View File
@@ -0,0 +1,7 @@
export type Message = {
id: string;
chat_id: string;
sender_id: string;
text: string;
created_at: string;
};
+55
View File
@@ -0,0 +1,55 @@
import {
BadRequestException,
Body,
Controller,
DefaultValuePipe,
Get,
Param,
ParseIntPipe,
ParseUUIDPipe,
Post,
Query,
Req,
UseGuards,
} from '@nestjs/common';
import type { FastifyRequest } from 'fastify';
import { CurrentUserGuard } from '../common/auth/current-user.guard.js';
import type { RequestWithCurrentUser } from '../common/auth/current-user.guard.js';
import { CreateMessageDto } from './dto/create-message.dto.js';
import { MessagesService } from './messages.service.js';
type MessageRequest = FastifyRequest & RequestWithCurrentUser;
@Controller('api/v1/chats/:chatId/messages')
@UseGuards(CurrentUserGuard)
export class MessagesController {
constructor(private readonly messagesService: MessagesService) {}
@Post()
create(
@Param('chatId', new ParseUUIDPipe()) chatId: string,
@Body() body: CreateMessageDto,
@Req() request: MessageRequest,
) {
return this.messagesService.create(chatId, body, request.currentUser!);
}
@Get()
list(
@Param('chatId', new ParseUUIDPipe()) chatId: string,
@Req() request: MessageRequest,
@Query('limit', new DefaultValuePipe(50), new ParseIntPipe()) limit: number,
@Query('cursor') cursor?: string,
) {
if (limit < 1 || limit > 100) {
throw new BadRequestException('limit must be between 1 and 100');
}
return this.messagesService.list(
chatId,
request.currentUser!,
limit,
cursor,
);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { ChatsModule } from '../chats/chats.module.js';
import { UsersModule } from '../users/users.module.js';
import { MessagesController } from './messages.controller.js';
import { MessagesRepository } from './messages.repository.js';
import { MessagesService } from './messages.service.js';
@Module({
imports: [UsersModule, ChatsModule],
controllers: [MessagesController],
providers: [MessagesRepository, MessagesService],
})
export class MessagesModule {}
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest';
import type { Cursor } from '../common/http/cursor.js';
import type { Message } from './message.js';
import { MessagesRepository } from './messages.repository.js';
const message = (id: string, created_at: string): Message => ({
id,
chat_id: 'chat',
sender_id: 'sender',
text: id,
created_at,
});
describe('MessagesRepository', () => {
it('appends messages whose key is after the current tail', () => {
const repository = new MessagesRepository();
repository.save(message('1', '2026-01-01T00:00:00.000Z'));
repository.save(message('2', '2026-01-01T00:00:01.000Z'));
expect(repository.findByChatId('chat').map((item) => item.id)).toEqual([
'1',
'2',
]);
});
it('keeps key order for delayed out-of-order messages', () => {
const repository = new MessagesRepository();
repository.save(message('2', '2026-01-01T00:00:02.000Z'));
repository.save(message('1', '2026-01-01T00:00:01.000Z'));
repository.save(message('3', '2026-01-01T00:00:03.000Z'));
const messages = repository.findByChatId('chat');
expect(messages.map((item) => item.id)).toEqual(['1', '2', '3']);
const cursor: Cursor = {
scope: 'messages:chat',
created_at: '2026-01-01T00:00:01.000Z',
id: '1',
};
expect(repository.findFirstAfter('chat', cursor)).toBe(1);
});
});
+68
View File
@@ -0,0 +1,68 @@
import { Injectable } from '@nestjs/common';
import type { Cursor } from '../common/http/cursor.js';
import { isAfter } from '../common/http/cursor.js';
import type { Message } from './message.js';
@Injectable()
export class MessagesRepository {
private readonly messagesByChatId = new Map<string, Message[]>();
save(message: Message): void {
const messages = this.messagesByChatId.get(message.chat_id) ?? [];
const last = messages.at(-1);
if (
!last ||
last.created_at < message.created_at ||
(last.created_at === message.created_at && last.id < message.id)
) {
messages.push(message);
this.messagesByChatId.set(message.chat_id, messages);
return;
}
// Preserve keyset order if a delayed request carries an older key.
let low = 0;
let high = messages.length;
while (low < high) {
const middle = Math.floor((low + high) / 2);
const current = messages[middle];
const comesAfter =
current.created_at > message.created_at ||
(current.created_at === message.created_at && current.id > message.id);
if (comesAfter) high = middle;
else low = middle + 1;
}
messages.splice(low, 0, message);
this.messagesByChatId.set(message.chat_id, messages);
}
findByChatId(chatId: string): Message[] {
return this.messagesByChatId.get(chatId) ?? [];
}
findFirstAfter(chatId: string, cursor: Cursor): number {
const messages = this.messagesByChatId.get(chatId) ?? [];
if (process.env.BENCHMARK_CURSOR_SEARCH === 'linear') {
return messages.findIndex((message) =>
isAfter(message.created_at, message.id, cursor),
);
}
let low = 0;
let high = messages.length;
while (low < high) {
const middle = Math.floor((low + high) / 2);
if (isAfter(messages[middle].created_at, messages[middle].id, cursor)) {
high = middle;
} else {
low = middle + 1;
}
}
return low;
}
}
+75
View File
@@ -0,0 +1,75 @@
import {
BadRequestException,
Injectable,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { decodeCursor, encodeCursor } from '../common/http/cursor.js';
import type { User } from '../users/user.js';
import { ChatsService } from '../chats/chats.service.js';
import type { CreateMessageDto } from './dto/create-message.dto.js';
import type { Message } from './message.js';
import { MessagesRepository } from './messages.repository.js';
@Injectable()
export class MessagesService {
constructor(
private readonly messagesRepository: MessagesRepository,
private readonly chatsService: ChatsService,
) {}
create(
chatId: string,
input: CreateMessageDto,
currentUser: User,
): Message {
const chat = this.chatsService.getForUser(chatId, currentUser);
if ([...input.text].every((character) => /\s/u.test(character))) {
throw new BadRequestException('Message text cannot be blank');
}
const message: Message = {
id: randomUUID(),
chat_id: chat.id,
sender_id: currentUser.id,
text: input.text,
created_at: new Date().toISOString(),
};
this.messagesRepository.save(message);
return message;
}
list(
chatId: string,
currentUser: User,
limit: number,
cursorValue?: string,
): { items: Message[]; next_cursor: string | null } {
this.chatsService.getForUser(chatId, currentUser);
const scope = `messages:${chatId}`;
const cursor = cursorValue
? decodeCursor(cursorValue, scope)
: undefined;
const messages = this.messagesRepository.findByChatId(chatId);
const start = cursor
? this.messagesRepository.findFirstAfter(chatId, cursor)
: 0;
const items = messages.slice(start, start + limit);
const hasMore = messages.length > start + limit;
const last = items.at(-1);
return {
items,
next_cursor:
hasMore && last
? encodeCursor({
scope,
created_at: last.created_at,
id: last.id,
})
: null,
};
}
}
+7
View File
@@ -0,0 +1,7 @@
import { User } from './users/user.ts';
declare module 'fastify' {
interface FastifyRequest {
currentUser?: User;
}
}
+11
View File
@@ -0,0 +1,11 @@
import { IsNotEmpty, IsString, Matches } from 'class-validator';
export class CreateUserDTO {
@IsString()
@Matches(/^[a-z0-9_]{3,32}$/)
username: string;
@IsString()
@IsNotEmpty()
display_name: string;
}
+6
View File
@@ -0,0 +1,6 @@
export type User = {
id: string;
username: string;
display_name: string;
created_at: string;
};
+21
View File
@@ -0,0 +1,21 @@
import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
import { UsersService } from './users.service.js';
import { CreateUserDTO } from './dto/create-user.dto.js';
import type { FastifyRequest } from 'fastify';
import { CurrentUserGuard } from '../common/auth/current-user.guard.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(@Req() request: FastifyRequest) {
return request.currentUser;
}
}
+12
View File
@@ -0,0 +1,12 @@
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';
@Module({
controllers: [UsersController],
providers: [UsersRepository, UsersService, CurrentUserGuard],
exports: [UsersService, CurrentUserGuard],
})
export class UsersModule {}
+25
View File
@@ -0,0 +1,25 @@
import { Injectable } from '@nestjs/common';
import { User } from './user.js';
@Injectable()
export class UsersRepository {
private readonly usersById = new Map<string, User>();
private readonly userIdByUsername = new Map<string, string>();
findById(id: string): User | undefined {
return this.usersById.get(id);
}
findByUsername(username: string): User | undefined {
const userId = this.userIdByUsername.get(username);
if (!userId) {
return undefined;
}
return this.usersById.get(userId);
}
save(user: User): void {
this.usersById.set(user.id, user);
this.userIdByUsername.set(user.username, user.id);
}
}
+45
View File
@@ -0,0 +1,45 @@
import {
BadRequestException,
ConflictException,
Injectable,
} from '@nestjs/common';
import { UsersRepository } from './users.repository.js';
import { CreateUserDTO } from './dto/create-user.dto.js';
import { User } from './user.js';
import { randomUUID } from 'node:crypto';
@Injectable()
export class UsersService {
constructor(private readonly usersRepository: UsersRepository) {}
create(input: CreateUserDTO): User {
const displayNameLength = [...input.display_name].length;
if (
displayNameLength < 1 ||
displayNameLength > 100 ||
input.display_name.trim().length === 0
) {
throw new BadRequestException('Invalid display name');
}
if (this.usersRepository.findByUsername(input.username)) {
throw new ConflictException('Username already exists');
}
const user: User = {
id: randomUUID(),
username: input.username,
display_name: input.display_name,
created_at: new Date().toISOString(),
};
this.usersRepository.save(user);
return user;
}
findById(id: string): User | undefined {
return this.usersRepository.findById(id);
}
}
+313
View File
@@ -0,0 +1,313 @@
import { HealthService } from './../src/health/health.service.js';
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from './../src/app.module.js';
import { RequestIdInterceptor } from './../src/common/http/request-id.interceptor.js';
import { ApiExceptionFilter } from './../src/common/errors/api-exception.filter.js';
describe('Foundation HTTP contract', () => {
let app: INestApplication<App>;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
app.useGlobalInterceptors(new RequestIdInterceptor());
app.useGlobalFilters(new ApiExceptionFilter());
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
await app.init();
});
afterEach(async () => {
await app.close();
});
it('returns liveness status with request id', async () => {
const response = await request(app.getHttpServer())
.get('/health/live')
.expect(200);
expect(response.body).toEqual({ status: 'ok' });
expect(response.headers['x-request-id']).toEqual(expect.any(String));
expect(response.headers['x-request-id']).not.toHaveLength(0);
});
it('returns readiness status with request id', async () => {
const response = await request(app.getHttpServer())
.get('/health/ready')
.expect(200);
expect(response.body).toEqual({ status: 'ok' });
expect(response.headers['x-request-id']).toEqual(expect.any(String));
});
it('keeps liveness alive while readiness is draining', async () => {
app.get(HealthService).setDraining();
const liveResponse = await request(app.getHttpServer())
.get('/health/live')
.expect(200);
expect(liveResponse.body).toEqual({ status: 'ok' });
const readyResponse = await request(app.getHttpServer())
.get('/health/ready')
.expect(503);
const requestId = readyResponse.headers['x-request-id'];
expect(requestId).toEqual(expect.any(String));
expect(readyResponse.body).toEqual({
error: {
code: 'unavailable',
message: 'Service is shutting down',
request_id: requestId,
},
});
});
it('returns contract error with matching request id for unknown route', async () => {
const response = await request(app.getHttpServer())
.get('/health/unknown')
.expect(404);
const requestId = response.headers['x-request-id'];
expect(requestId).toEqual(expect.any(String));
expect(response.body).toEqual({
error: {
code: 'not_found',
message: 'Resource not found',
request_id: requestId,
},
});
});
it('registers a user and returns it from /me', async () => {
const created = await request(app.getHttpServer())
.post('/api/v1/users')
.send({
username: 'alice',
display_name: 'Алиса',
})
.expect(201);
const user = created.body;
const current = await request(app.getHttpServer())
.get('/api/v1/users/me')
.set('X-User-Id', user.id)
.expect(200);
expect(current.body).toEqual(user);
});
it('rejects /me without X-User-Id', async () => {
const response = await request(app.getHttpServer())
.get('/api/v1/users/me')
.expect(401);
expect(response.body.error.code).toBe('unauthorized');
expect(response.headers['x-request-id']).toBe(
response.body.error.request_id,
);
});
it('rejects duplicate usernames', async () => {
await request(app.getHttpServer())
.post('/api/v1/users')
.send({
username: 'duplicate_user',
display_name: 'Первый',
})
.expect(201);
const response = await request(app.getHttpServer())
.post('/api/v1/users')
.send({
username: 'duplicate_user',
display_name: 'Второй',
})
.expect(409);
expect(response.body.error.code).toBe('conflict');
});
it('creates a chat and hides it from a non-member', async () => {
const aliceResponse = await request(app.getHttpServer())
.post('/api/v1/users')
.send({
username: 'alice_chat',
display_name: 'Алиса',
})
.expect(201);
const bobResponse = await request(app.getHttpServer())
.post('/api/v1/users')
.send({
username: 'bob_chat',
display_name: 'Боб',
})
.expect(201);
const aliceId = aliceResponse.body.id;
const bobId = bobResponse.body.id;
const chatResponse = await request(app.getHttpServer())
.post('/api/v1/chats')
.set('X-User-Id', aliceId)
.send({
title: 'Учебный чат',
member_ids: [aliceId, bobId],
})
.expect(201);
expect(chatResponse.body.member_ids).toEqual([aliceId, bobId]);
await request(app.getHttpServer())
.get(`/api/v1/chats/${chatResponse.body.id}`)
.set('X-User-Id', bobId)
.expect(200);
const outsiderResponse = await request(app.getHttpServer())
.post('/api/v1/users')
.send({
username: 'charlie_chat',
display_name: 'Чарли',
})
.expect(201);
await request(app.getHttpServer())
.get(`/api/v1/chats/${chatResponse.body.id}`)
.set('X-User-Id', outsiderResponse.body.id)
.expect(404);
});
it('rejects chat when current user is not in member_ids', async () => {
const aliceResponse = await request(app.getHttpServer())
.post('/api/v1/users')
.send({
username: 'alice_member',
display_name: 'Алиса',
})
.expect(201);
const bobResponse = await request(app.getHttpServer())
.post('/api/v1/users')
.send({
username: 'bob_member',
display_name: 'Боб',
})
.expect(201);
const response = await request(app.getHttpServer())
.post('/api/v1/chats')
.set('X-User-Id', aliceResponse.body.id)
.send({
title: 'Неверный чат',
member_ids: [bobResponse.body.id],
})
.expect(400);
expect(response.body.error.code).toBe('invalid_request');
});
it('paginates chat history without repeating messages', async () => {
const alice = await request(app.getHttpServer())
.post('/api/v1/users')
.send({ username: 'page_alice', display_name: 'Алиса' })
.expect(201);
const bob = await request(app.getHttpServer())
.post('/api/v1/users')
.send({ username: 'page_bob', display_name: 'Боб' })
.expect(201);
const aliceId = alice.body.id;
const bobId = bob.body.id;
const chat = await request(app.getHttpServer())
.post('/api/v1/chats')
.set('X-User-Id', aliceId)
.send({ title: 'История', member_ids: [aliceId, bobId] })
.expect(201);
const createdMessages: Array<{ id: string }> = [];
for (const text of ['one', 'two', 'three']) {
const response = await request(app.getHttpServer())
.post(`/api/v1/chats/${chat.body.id}/messages`)
.set('X-User-Id', aliceId)
.send({ text })
.expect(201);
createdMessages.push(response.body);
}
const firstPage = await request(app.getHttpServer())
.get(`/api/v1/chats/${chat.body.id}/messages`)
.query({ limit: 2 })
.set('X-User-Id', bobId)
.expect(200);
expect(firstPage.body.items.map((item: { id: string }) => item.id)).toEqual(
createdMessages.slice(0, 2).map((item) => item.id),
);
expect(firstPage.body.next_cursor).toEqual(expect.any(String));
const secondPage = await request(app.getHttpServer())
.get(`/api/v1/chats/${chat.body.id}/messages`)
.query({ limit: 2, cursor: firstPage.body.next_cursor })
.set('X-User-Id', bobId)
.expect(200);
expect(secondPage.body.items.map((item: { id: string }) => item.id)).toEqual(
[createdMessages[2].id],
);
expect(secondPage.body.next_cursor).toBeNull();
});
it('rejects blank messages and sender spoofing fields', async () => {
const alice = await request(app.getHttpServer())
.post('/api/v1/users')
.send({ username: 'blank_alice', display_name: 'Алиса' })
.expect(201);
const chat = await request(app.getHttpServer())
.post('/api/v1/chats')
.set('X-User-Id', alice.body.id)
.send({ title: 'Проверка', member_ids: [alice.body.id] })
.expect(201);
const response = await request(app.getHttpServer())
.post(`/api/v1/chats/${chat.body.id}/messages`)
.set('X-User-Id', alice.body.id)
.send({ text: ' ', sender_id: 'spoofed' })
.expect(400);
expect(response.body.error.code).toBe('invalid_request');
});
it('rejects an invalid cursor and an invalid limit', async () => {
const alice = await request(app.getHttpServer())
.post('/api/v1/users')
.send({ username: 'cursor_alice', display_name: 'Алиса' })
.expect(201);
const response = await request(app.getHttpServer())
.get('/api/v1/chats')
.query({ limit: 101, cursor: 'not-a-cursor' })
.set('X-User-Id', alice.body.id)
.expect(400);
expect(response.body.error.code).toBe('invalid_request');
});
});
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"rootDir": "./src"
},
"include": ["src"],
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"resolvePackageJsonExports": true,
"esModuleInterop": true,
"isolatedModules": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"incremental": true,
"skipLibCheck": true,
"strict": true,
"strictPropertyInitialization": false,
"types": ["vitest/globals", "node"]
}
}
+11
View File
@@ -0,0 +1,11 @@
import { defineConfig } from 'vitest/config';
import tsconfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
plugins: [tsconfigPaths()],
test: {
globals: true,
root: './',
include: ['**/*.e2e-spec.ts'],
},
});
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from 'vitest/config';
import tsconfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
// Resolves the path aliases declared in tsconfig.json, including the ones
// added by `nest g library`.
plugins: [tsconfigPaths()],
test: {
globals: true,
root: './',
include: ['**/*.spec.ts'],
},
});
+13
View File
@@ -0,0 +1,13 @@
services:
nest-app:
build:
context: .
dockerfile: Dockerfile
image: mtusi-messenger:lab2
ports:
- ${APP_PUBLIC_PORT:-8080}:${APP_PORT:-8080}
env_file:
- .env
environment:
BENCHMARK_CURSOR_SEARCH: ${BENCHMARK_CURSOR_SEARCH:-binary}
stop_grace_period: 30s