forked from mtusi2026/mtusi2026lab2
chore: migrate minimum from lab1
This commit is contained in:
@@ -16,5 +16,9 @@ backups
|
||||
.venv
|
||||
__pycache__
|
||||
node_modules
|
||||
dist
|
||||
coverage
|
||||
evidence
|
||||
.DS_Store
|
||||
.idea
|
||||
.vscode
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
* text=auto eol=lf
|
||||
*.png binary
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"useTabs": true,
|
||||
"tabWidth": 4,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM node:20.17.0-slim AS deps
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
FROM deps AS build
|
||||
COPY tsconfig.json tsconfig.build.json nest-cli.json ./
|
||||
COPY src ./src
|
||||
RUN npm run build
|
||||
|
||||
FROM build AS test
|
||||
COPY test ./test
|
||||
CMD ["npm", "test"]
|
||||
|
||||
FROM node:20.17.0-slim AS runtime
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev && npm cache clean --force
|
||||
COPY --from=build /app/dist ./dist
|
||||
|
||||
USER node
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD node -e "require('http').get('http://127.0.0.1:8080/health/live',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"
|
||||
|
||||
CMD ["node", "dist/main.js"]
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
Generated
+9710
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "mtusi-messenger-lab2",
|
||||
"version": "1.0.0",
|
||||
"description": "Lab 1: in-memory messenger API (NestJS + Fastify)",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"start": "node dist/main.js",
|
||||
"start:dev": "nest start --watch",
|
||||
"lint": "eslint \"{src,test}/**/*.ts\"",
|
||||
"test": "jest --config ./test/jest-e2e.json",
|
||||
"test:watch": "jest --config ./test/jest-e2e.json --watch"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^10.4.15",
|
||||
"@nestjs/core": "^10.4.15",
|
||||
"@nestjs/platform-fastify": "^10.4.15",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^10.4.9",
|
||||
"@nestjs/schematics": "^10.2.3",
|
||||
"@nestjs/testing": "^10.4.15",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.17.9",
|
||||
"@types/supertest": "^6.0.2",
|
||||
"@typescript-eslint/eslint-plugin": "^8.18.1",
|
||||
"@typescript-eslint/parser": "^8.18.1",
|
||||
"eslint": "^8.57.1",
|
||||
"jest": "^29.7.0",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-loader": "^9.5.1",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.7.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ChatsModule } from './chats/chats.module';
|
||||
import { CommonModule } from './common/common.module';
|
||||
import { HealthModule } from './health/health.module';
|
||||
import { MessagesModule } from './messages/messages.module';
|
||||
import { UsersModule } from './users/users.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
CommonModule,
|
||||
HealthModule,
|
||||
UsersModule,
|
||||
ChatsModule,
|
||||
MessagesModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '../common/auth/auth.guard';
|
||||
import { CurrentUser } from '../common/auth/current-user.decorator';
|
||||
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
|
||||
import { User } from '../common/store/domain';
|
||||
import { ChatsService } from './chats.service';
|
||||
import {
|
||||
ChatPageResponse,
|
||||
ChatResponse,
|
||||
toChatResponse,
|
||||
} from './dto/chat.response';
|
||||
import { CreateChatDto } from './dto/create-chat.dto';
|
||||
|
||||
@Controller('api/v1/chats')
|
||||
@UseGuards(AuthGuard)
|
||||
export class ChatsController {
|
||||
constructor(private readonly chats: ChatsService) {}
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
create(
|
||||
@Body() dto: CreateChatDto,
|
||||
@CurrentUser() user: User,
|
||||
): ChatResponse {
|
||||
const chat = this.chats.create(dto.title, dto.member_ids, user.id);
|
||||
return toChatResponse(chat);
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(
|
||||
@CurrentUser() user: User,
|
||||
@Query('limit') limitRaw: unknown,
|
||||
@Query('cursor') cursorRaw: unknown,
|
||||
): ChatPageResponse {
|
||||
const limit = parseLimit(limitRaw);
|
||||
const cursor = rawCursorParam(cursorRaw);
|
||||
return this.chats.listForMember(user.id, limit, cursor);
|
||||
}
|
||||
|
||||
@Get(':chatId')
|
||||
getOne(
|
||||
@Param('chatId') chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
): ChatResponse {
|
||||
const chat = this.chats.getForMember(chatId, user.id);
|
||||
return toChatResponse(chat);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CommonModule } from '../common/common.module';
|
||||
import { ChatsController } from './chats.controller';
|
||||
import { ChatsService } from './chats.service';
|
||||
|
||||
@Module({
|
||||
imports: [CommonModule],
|
||||
controllers: [ChatsController],
|
||||
providers: [ChatsService],
|
||||
exports: [ChatsService],
|
||||
})
|
||||
export class ChatsModule {}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import {
|
||||
decodeChatCursor,
|
||||
encodeChatCursor,
|
||||
} from '../common/store/store.service';
|
||||
import { Chat } from '../common/store/domain';
|
||||
import { StoreService } from '../common/store/store.service';
|
||||
import { validate as isUuid } from '../common/uuid';
|
||||
import { ChatPageResponse, toChatResponse } from './dto/chat.response';
|
||||
|
||||
@Injectable()
|
||||
export class ChatsService {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
create(title: string, memberIds: string[], callerId: string): Chat {
|
||||
if (!memberIds.includes(callerId)) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'member_ids must include the caller',
|
||||
);
|
||||
}
|
||||
for (const id of memberIds) {
|
||||
if (!isUuid(id) || !this.store.getUserById(id)) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
`unknown member_id: ${id}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return this.store.createChat(title.trim(), memberIds);
|
||||
}
|
||||
|
||||
getForMember(chatId: string, callerId: string): Chat {
|
||||
if (!isUuid(chatId)) {
|
||||
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
||||
}
|
||||
const chat = this.store.getChatById(chatId);
|
||||
if (!chat || !chat.memberIds.includes(callerId)) {
|
||||
throw new ApiError('not_found', 'chat not found');
|
||||
}
|
||||
return chat;
|
||||
}
|
||||
|
||||
listForMember(
|
||||
callerId: string,
|
||||
limit: number,
|
||||
rawCursor: string | null,
|
||||
): ChatPageResponse {
|
||||
const cursor = rawCursor === null ? null : decodeChatCursor(rawCursor);
|
||||
if (rawCursor !== null && cursor === null) {
|
||||
throw new ApiError('invalid_request', 'invalid cursor');
|
||||
}
|
||||
if (cursor && !this.store.chatCursorExists(callerId, cursor.id)) {
|
||||
throw new ApiError('invalid_request', 'invalid cursor');
|
||||
}
|
||||
const items = this.store.listChatsForMember(callerId, cursor, limit);
|
||||
const last = items[items.length - 1];
|
||||
const hasMore = last
|
||||
? this.store.hasMoreChatsAfter(callerId, last.id)
|
||||
: false;
|
||||
return {
|
||||
items: items.map(toChatResponse),
|
||||
next_cursor: hasMore ? encodeChatCursor({ id: last.id }) : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Chat } from '../../common/store/domain';
|
||||
|
||||
export interface ChatResponse {
|
||||
id: string;
|
||||
title: string;
|
||||
member_ids: string[];
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ChatPageResponse {
|
||||
items: ChatResponse[];
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
export function toChatResponse(chat: Chat): ChatResponse {
|
||||
return {
|
||||
id: chat.id,
|
||||
title: chat.title,
|
||||
member_ids: chat.memberIds,
|
||||
created_at: chat.createdAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { ArrayMinSize, ArrayUnique, IsArray, IsString } from 'class-validator';
|
||||
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||
import { NotBlank } from '../../common/dto/not-blank.validator';
|
||||
|
||||
export class CreateChatDto {
|
||||
@NotBlank()
|
||||
@CodePointLength(1, 100)
|
||||
title!: string;
|
||||
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ArrayUnique()
|
||||
@IsString({ each: true })
|
||||
member_ids!: string[];
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { validate as isUuid } from '../uuid';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { ApiError } from '../filters/api-error';
|
||||
import { StoreService } from '../store/store.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const request = context.switchToHttp().getRequest<FastifyRequest>();
|
||||
const header = request.headers['x-user-id'];
|
||||
const userId = Array.isArray(header) ? header[0] : header;
|
||||
if (!userId || !isUuid(userId)) {
|
||||
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
|
||||
}
|
||||
const user = this.store.getUserById(userId);
|
||||
if (!user) {
|
||||
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
|
||||
}
|
||||
request.currentUser = user;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { User } from '../store/domain';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
currentUser?: User;
|
||||
}
|
||||
}
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): User => {
|
||||
const request = ctx.switchToHttp().getRequest<FastifyRequest>();
|
||||
if (!request.currentUser) {
|
||||
throw new Error('CurrentUser used without AuthGuard');
|
||||
}
|
||||
return request.currentUser;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { AuthGuard } from './auth/auth.guard';
|
||||
import { StoreService } from './store/store.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [StoreService, AuthGuard],
|
||||
exports: [StoreService, AuthGuard],
|
||||
})
|
||||
export class CommonModule {}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { registerDecorator, ValidationOptions } from 'class-validator';
|
||||
|
||||
export function codePointLength(value: string): number {
|
||||
return [...value].length;
|
||||
}
|
||||
|
||||
export function CodePointLength(
|
||||
min: number,
|
||||
max: number,
|
||||
options?: ValidationOptions,
|
||||
) {
|
||||
return function (object: object, propertyName: string) {
|
||||
registerDecorator({
|
||||
name: 'codePointLength',
|
||||
target: object.constructor,
|
||||
propertyName,
|
||||
constraints: [min, max],
|
||||
options,
|
||||
validator: {
|
||||
validate(value: unknown): boolean {
|
||||
if (typeof value !== 'string') {
|
||||
return false;
|
||||
}
|
||||
const length = codePointLength(value);
|
||||
return length >= min && length <= max;
|
||||
},
|
||||
defaultMessage(): string {
|
||||
return `${propertyName} must be between ${min} and ${max} Unicode code points`;
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { registerDecorator, ValidationOptions } from 'class-validator';
|
||||
|
||||
export function NotBlank(options?: ValidationOptions) {
|
||||
return function (object: object, propertyName: string) {
|
||||
registerDecorator({
|
||||
name: 'notBlank',
|
||||
target: object.constructor,
|
||||
propertyName,
|
||||
options,
|
||||
validator: {
|
||||
validate(value: unknown): boolean {
|
||||
return typeof value === 'string' && value.trim().length > 0;
|
||||
},
|
||||
defaultMessage(): string {
|
||||
return `${propertyName} must not be empty or whitespace-only`;
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { ApiError } from '../filters/api-error';
|
||||
|
||||
const DEFAULT_LIMIT = 50;
|
||||
const MIN_LIMIT = 1;
|
||||
const MAX_LIMIT = 100;
|
||||
|
||||
export function parseLimit(raw: unknown): number {
|
||||
if (raw === undefined) {
|
||||
return DEFAULT_LIMIT;
|
||||
}
|
||||
const value = Array.isArray(raw) ? raw[0] : raw;
|
||||
if (typeof value !== 'string' || !/^\d+$/.test(value)) {
|
||||
throw new ApiError('invalid_request', 'limit must be an integer');
|
||||
}
|
||||
const limit = Number(value);
|
||||
if (limit < MIN_LIMIT || limit > MAX_LIMIT) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
`limit must be between ${MIN_LIMIT} and ${MAX_LIMIT}`,
|
||||
);
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
|
||||
export function rawCursorParam(raw: unknown): string | null {
|
||||
if (raw === undefined) {
|
||||
return null;
|
||||
}
|
||||
const value = Array.isArray(raw) ? raw[0] : raw;
|
||||
if (typeof value !== 'string' || value.length === 0) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'cursor must be a non-empty string',
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
|
||||
export type ErrorCode =
|
||||
| 'invalid_request'
|
||||
| 'unauthorized'
|
||||
| 'not_found'
|
||||
| 'conflict'
|
||||
| 'payload_too_large'
|
||||
| 'unsupported_media_type'
|
||||
| 'rate_limited'
|
||||
| 'unavailable'
|
||||
| 'internal_error';
|
||||
|
||||
const STATUS_BY_CODE: Record<ErrorCode, number> = {
|
||||
invalid_request: HttpStatus.BAD_REQUEST,
|
||||
unauthorized: HttpStatus.UNAUTHORIZED,
|
||||
not_found: HttpStatus.NOT_FOUND,
|
||||
conflict: HttpStatus.CONFLICT,
|
||||
payload_too_large: HttpStatus.PAYLOAD_TOO_LARGE,
|
||||
unsupported_media_type: HttpStatus.UNSUPPORTED_MEDIA_TYPE,
|
||||
rate_limited: HttpStatus.TOO_MANY_REQUESTS,
|
||||
unavailable: HttpStatus.SERVICE_UNAVAILABLE,
|
||||
internal_error: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
|
||||
export class ApiError extends HttpException {
|
||||
constructor(
|
||||
public readonly code: ErrorCode,
|
||||
message: string,
|
||||
) {
|
||||
super(message, STATUS_BY_CODE[code]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { ApiError, ErrorCode } from './api-error';
|
||||
|
||||
const CODE_BY_STATUS: Partial<Record<number, ErrorCode>> = {
|
||||
[HttpStatus.BAD_REQUEST]: 'invalid_request',
|
||||
[HttpStatus.UNAUTHORIZED]: 'unauthorized',
|
||||
[HttpStatus.NOT_FOUND]: 'not_found',
|
||||
[HttpStatus.CONFLICT]: 'conflict',
|
||||
[HttpStatus.PAYLOAD_TOO_LARGE]: 'payload_too_large',
|
||||
[HttpStatus.UNSUPPORTED_MEDIA_TYPE]: 'unsupported_media_type',
|
||||
[HttpStatus.TOO_MANY_REQUESTS]: 'rate_limited',
|
||||
[HttpStatus.SERVICE_UNAVAILABLE]: 'unavailable',
|
||||
};
|
||||
|
||||
interface Resolved {
|
||||
status: number;
|
||||
code: ErrorCode;
|
||||
message: string;
|
||||
}
|
||||
|
||||
@Catch()
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger('HttpExceptionFilter');
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost): void {
|
||||
const ctx = host.switchToHttp();
|
||||
const reply = ctx.getResponse<FastifyReply>();
|
||||
const request = ctx.getRequest<FastifyRequest>();
|
||||
const requestId = request.requestId;
|
||||
|
||||
const { status, code, message } = this.resolve(exception);
|
||||
if (status >= 500) {
|
||||
this.logger.error(
|
||||
`${request.method} ${request.url} -> ${status}: ${message}`,
|
||||
);
|
||||
}
|
||||
|
||||
reply
|
||||
.code(status)
|
||||
.header('x-request-id', requestId)
|
||||
.send({ error: { code, message, request_id: requestId } });
|
||||
}
|
||||
|
||||
private resolve(exception: unknown): Resolved {
|
||||
if (exception instanceof ApiError) {
|
||||
return {
|
||||
status: exception.getStatus(),
|
||||
code: exception.code,
|
||||
message: exception.message,
|
||||
};
|
||||
}
|
||||
if (exception instanceof HttpException) {
|
||||
const status = exception.getStatus();
|
||||
const code = CODE_BY_STATUS[status] ?? 'internal_error';
|
||||
const message =
|
||||
extractMessage(exception.getResponse()) ?? exception.message;
|
||||
return { status, code, message };
|
||||
}
|
||||
const fastifyStatus = (exception as { statusCode?: unknown })
|
||||
?.statusCode;
|
||||
if (typeof fastifyStatus === 'number' && CODE_BY_STATUS[fastifyStatus]) {
|
||||
const message =
|
||||
exception instanceof Error ? exception.message : 'Invalid request';
|
||||
return {
|
||||
status: fastifyStatus,
|
||||
code: CODE_BY_STATUS[fastifyStatus]!,
|
||||
message,
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: 500,
|
||||
code: 'internal_error',
|
||||
message: 'Internal server error',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function extractMessage(response: unknown): string | null {
|
||||
if (typeof response === 'string') {
|
||||
return response;
|
||||
}
|
||||
if (
|
||||
typeof response === 'object' &&
|
||||
response !== null &&
|
||||
'message' in response
|
||||
) {
|
||||
const value = (response as { message: unknown }).message;
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
if (Array.isArray(value) && value.every((v) => typeof v === 'string')) {
|
||||
return value.join('; ');
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
|
||||
const REQUEST_ID_HEADER = 'x-request-id';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
requestId: string;
|
||||
}
|
||||
}
|
||||
|
||||
export function registerRequestId(instance: FastifyInstance): void {
|
||||
instance.addHook('onRequest', (request: FastifyRequest, reply, done) => {
|
||||
request.requestId = randomUUID();
|
||||
reply.header(REQUEST_ID_HEADER, request.requestId);
|
||||
done();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
displayName: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface Chat {
|
||||
id: string;
|
||||
title: string;
|
||||
memberIds: string[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id: string;
|
||||
chatId: string;
|
||||
senderId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { Chat, Message, User } from './domain';
|
||||
|
||||
export interface ChatCursor {
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface MessageCursor {
|
||||
chatId: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface Ordered {
|
||||
id: string;
|
||||
seq: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
type StoredChat = Chat & Ordered;
|
||||
type StoredMessage = Message & Ordered;
|
||||
|
||||
class OrderedList<T extends Ordered> {
|
||||
private readonly items: T[] = [];
|
||||
private readonly indexById = new Map<string, number>();
|
||||
|
||||
push(item: T): void {
|
||||
this.items.push(item);
|
||||
let index = this.items.length - 1;
|
||||
while (
|
||||
index > 0 &&
|
||||
this.items[index - 1].createdAt === item.createdAt &&
|
||||
this.items[index - 1].id > item.id
|
||||
) {
|
||||
this.items[index] = this.items[index - 1];
|
||||
this.indexById.set(this.items[index].id, index);
|
||||
index--;
|
||||
}
|
||||
this.items[index] = item;
|
||||
this.indexById.set(item.id, index);
|
||||
}
|
||||
|
||||
get length(): number {
|
||||
return this.items.length;
|
||||
}
|
||||
|
||||
toArray(): T[] {
|
||||
return this.items;
|
||||
}
|
||||
|
||||
page(afterId: string | null, limit: number): T[] {
|
||||
if (afterId === null) {
|
||||
return this.items.slice(0, limit);
|
||||
}
|
||||
const cursorIndex = this.indexById.get(afterId);
|
||||
const startIndex =
|
||||
cursorIndex === undefined ? this.items.length : cursorIndex + 1;
|
||||
return this.items.slice(startIndex, startIndex + limit);
|
||||
}
|
||||
|
||||
hasMoreAfter(lastId: string): boolean {
|
||||
const cursorIndex = this.indexById.get(lastId);
|
||||
return cursorIndex !== undefined && cursorIndex < this.items.length - 1;
|
||||
}
|
||||
|
||||
hasId(id: string): boolean {
|
||||
return this.indexById.has(id);
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class StoreService {
|
||||
private readonly usersById = new Map<string, User>();
|
||||
private readonly userIdByUsername = new Map<string, string>();
|
||||
private readonly chatsById = new Map<string, StoredChat>();
|
||||
private readonly chatsByMember = new Map<string, OrderedList<StoredChat>>();
|
||||
private readonly messagesByChatId = new Map<
|
||||
string,
|
||||
OrderedList<StoredMessage>
|
||||
>();
|
||||
private nextChatSeq = 0;
|
||||
private nextMessageSeq = 0;
|
||||
|
||||
createUser(username: string, displayName: string): User | null {
|
||||
if (this.userIdByUsername.has(username)) {
|
||||
return null;
|
||||
}
|
||||
const user: User = {
|
||||
id: randomUUID(),
|
||||
username,
|
||||
displayName,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
this.usersById.set(user.id, user);
|
||||
this.userIdByUsername.set(username, user.id);
|
||||
return user;
|
||||
}
|
||||
|
||||
getUserById(id: string): User | undefined {
|
||||
return this.usersById.get(id);
|
||||
}
|
||||
|
||||
createChat(title: string, memberIds: string[]): Chat {
|
||||
const stored: StoredChat = {
|
||||
id: randomUUID(),
|
||||
title,
|
||||
memberIds: [...memberIds],
|
||||
createdAt: new Date().toISOString(),
|
||||
seq: this.nextChatSeq++,
|
||||
};
|
||||
this.chatsById.set(stored.id, stored);
|
||||
for (const memberId of memberIds) {
|
||||
this.chatListFor(memberId).push(stored);
|
||||
}
|
||||
this.messagesByChatId.set(stored.id, new OrderedList<StoredMessage>());
|
||||
return toPublicChat(stored);
|
||||
}
|
||||
|
||||
getChatById(id: string): Chat | undefined {
|
||||
const stored = this.chatsById.get(id);
|
||||
return stored ? toPublicChat(stored) : undefined;
|
||||
}
|
||||
|
||||
isMember(chatId: string, userId: string): boolean {
|
||||
return !!this.chatsById.get(chatId)?.memberIds.includes(userId);
|
||||
}
|
||||
|
||||
listChatsForMember(
|
||||
userId: string,
|
||||
afterCursor: ChatCursor | null,
|
||||
limit: number,
|
||||
): Chat[] {
|
||||
return this.chatListFor(userId)
|
||||
.page(afterCursor?.id ?? null, limit)
|
||||
.map(toPublicChat);
|
||||
}
|
||||
|
||||
hasMoreChatsAfter(userId: string, lastId: string): boolean {
|
||||
return this.chatListFor(userId).hasMoreAfter(lastId);
|
||||
}
|
||||
|
||||
chatCursorExists(userId: string, cursorId: string): boolean {
|
||||
return this.chatListFor(userId).hasId(cursorId);
|
||||
}
|
||||
|
||||
createMessage(chatId: string, senderId: string, text: string): Message {
|
||||
const list = this.messagesByChatId.get(chatId);
|
||||
if (!list) {
|
||||
throw new Error('chat must exist before appending a message');
|
||||
}
|
||||
const stored: StoredMessage = {
|
||||
id: randomUUID(),
|
||||
chatId,
|
||||
senderId,
|
||||
text,
|
||||
createdAt: new Date().toISOString(),
|
||||
seq: this.nextMessageSeq++,
|
||||
};
|
||||
list.push(stored);
|
||||
return toPublicMessage(stored);
|
||||
}
|
||||
|
||||
listMessages(
|
||||
chatId: string,
|
||||
afterCursor: MessageCursor | null,
|
||||
limit: number,
|
||||
): Message[] {
|
||||
const list = this.messagesByChatId.get(chatId);
|
||||
if (!list) {
|
||||
return [];
|
||||
}
|
||||
return list.page(afterCursor?.id ?? null, limit).map(toPublicMessage);
|
||||
}
|
||||
|
||||
hasMoreMessagesAfter(chatId: string, lastId: string): boolean {
|
||||
return this.messagesByChatId.get(chatId)?.hasMoreAfter(lastId) ?? false;
|
||||
}
|
||||
|
||||
messageCursorExists(chatId: string, cursorId: string): boolean {
|
||||
return this.messagesByChatId.get(chatId)?.hasId(cursorId) ?? false;
|
||||
}
|
||||
|
||||
private chatListFor(memberId: string): OrderedList<StoredChat> {
|
||||
let list = this.chatsByMember.get(memberId);
|
||||
if (!list) {
|
||||
list = new OrderedList<StoredChat>();
|
||||
this.chatsByMember.set(memberId, list);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
function toPublicChat(stored: StoredChat): Chat {
|
||||
const { seq: _seq, ...chat } = stored;
|
||||
return chat;
|
||||
}
|
||||
|
||||
function toPublicMessage(stored: StoredMessage): Message {
|
||||
const { seq: _seq, ...message } = stored;
|
||||
return message;
|
||||
}
|
||||
|
||||
export function encodeChatCursor(cursor: ChatCursor): string {
|
||||
return encode(cursor);
|
||||
}
|
||||
|
||||
export function decodeChatCursor(raw: string): ChatCursor | null {
|
||||
const decoded = decode(raw);
|
||||
return decoded && typeof decoded.id === 'string'
|
||||
? { id: decoded.id }
|
||||
: null;
|
||||
}
|
||||
|
||||
export function encodeMessageCursor(cursor: MessageCursor): string {
|
||||
return encode(cursor);
|
||||
}
|
||||
|
||||
export function decodeMessageCursor(raw: string): MessageCursor | null {
|
||||
const decoded = decode(raw);
|
||||
return decoded &&
|
||||
typeof decoded.chatId === 'string' &&
|
||||
typeof decoded.id === 'string'
|
||||
? { chatId: decoded.chatId, id: decoded.id }
|
||||
: null;
|
||||
}
|
||||
|
||||
function encode(value: object): string {
|
||||
return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url');
|
||||
}
|
||||
|
||||
function decode(raw: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const parsed = JSON.parse(
|
||||
Buffer.from(raw, 'base64url').toString('utf8'),
|
||||
);
|
||||
return typeof parsed === 'object' && parsed !== null ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
const UUID_PATTERN =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
export function validate(value: string): boolean {
|
||||
return UUID_PATTERN.test(value);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
|
||||
import { registerRequestId } from './common/interceptors/request-id';
|
||||
|
||||
export function configureApp(app: NestFastifyApplication): void {
|
||||
registerRequestId(app.getHttpAdapter().getInstance());
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
forbidUnknownValues: true,
|
||||
}),
|
||||
);
|
||||
app.useGlobalFilters(new HttpExceptionFilter());
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
@Get('live')
|
||||
live(): { status: 'ok' } {
|
||||
return { status: 'ok' };
|
||||
}
|
||||
|
||||
@Get('ready')
|
||||
ready(): { status: 'ok' } {
|
||||
return { status: 'ok' };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
} from '@nestjs/platform-fastify';
|
||||
import { AppModule } from './app.module';
|
||||
import { configureApp } from './configure-app';
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.create<NestFastifyApplication>(
|
||||
AppModule,
|
||||
new FastifyAdapter(),
|
||||
{
|
||||
bufferLogs: true,
|
||||
},
|
||||
);
|
||||
|
||||
configureApp(app);
|
||||
app.enableShutdownHooks();
|
||||
|
||||
const host = process.env.APP_HOST ?? '0.0.0.0';
|
||||
const port = Number(process.env.APP_PORT ?? 8080);
|
||||
await app.listen(port, host);
|
||||
Logger.log(`Listening on http://${host}:${port}`, 'Bootstrap');
|
||||
}
|
||||
|
||||
bootstrap().catch((error) => {
|
||||
Logger.error('Fatal error during bootstrap', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import { IsString } from 'class-validator';
|
||||
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||
|
||||
export class CreateMessageDto {
|
||||
@IsString()
|
||||
@CodePointLength(0, 4000)
|
||||
text!: string;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Message } from '../../common/store/domain';
|
||||
|
||||
export interface MessageResponse {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface MessagePageResponse {
|
||||
items: MessageResponse[];
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
export function toMessageResponse(message: Message): MessageResponse {
|
||||
return {
|
||||
id: message.id,
|
||||
chat_id: message.chatId,
|
||||
sender_id: message.senderId,
|
||||
text: message.text,
|
||||
created_at: message.createdAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '../common/auth/auth.guard';
|
||||
import { CurrentUser } from '../common/auth/current-user.decorator';
|
||||
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
|
||||
import { User } from '../common/store/domain';
|
||||
import { CreateMessageDto } from './dto/create-message.dto';
|
||||
import {
|
||||
MessagePageResponse,
|
||||
MessageResponse,
|
||||
toMessageResponse,
|
||||
} from './dto/message.response';
|
||||
import { MessagesService } from './messages.service';
|
||||
|
||||
@Controller('api/v1/chats/:chatId/messages')
|
||||
@UseGuards(AuthGuard)
|
||||
export class MessagesController {
|
||||
constructor(private readonly messages: MessagesService) {}
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
create(
|
||||
@Param('chatId') chatId: string,
|
||||
@Body() dto: CreateMessageDto,
|
||||
@CurrentUser() user: User,
|
||||
): MessageResponse {
|
||||
const message = this.messages.create(chatId, user.id, dto.text);
|
||||
return toMessageResponse(message);
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(
|
||||
@Param('chatId') chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
@Query('limit') limitRaw: unknown,
|
||||
@Query('cursor') cursorRaw: unknown,
|
||||
): MessagePageResponse {
|
||||
const limit = parseLimit(limitRaw);
|
||||
const cursor = rawCursorParam(cursorRaw);
|
||||
return this.messages.list(chatId, user.id, limit, cursor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CommonModule } from '../common/common.module';
|
||||
import { MessagesController } from './messages.controller';
|
||||
import { MessagesService } from './messages.service';
|
||||
|
||||
@Module({
|
||||
imports: [CommonModule],
|
||||
controllers: [MessagesController],
|
||||
providers: [MessagesService],
|
||||
})
|
||||
export class MessagesModule {}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { codePointLength } from '../common/dto/code-point-length.validator';
|
||||
import { Message } from '../common/store/domain';
|
||||
import {
|
||||
decodeMessageCursor,
|
||||
encodeMessageCursor,
|
||||
StoreService,
|
||||
} from '../common/store/store.service';
|
||||
import { validate as isUuid } from '../common/uuid';
|
||||
import { MessagePageResponse, toMessageResponse } from './dto/message.response';
|
||||
|
||||
@Injectable()
|
||||
export class MessagesService {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
create(chatId: string, callerId: string, text: string): Message {
|
||||
this.assertMember(chatId, callerId);
|
||||
if (codePointLength(text.trim()) === 0) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'text must not be empty or whitespace-only',
|
||||
);
|
||||
}
|
||||
return this.store.createMessage(chatId, callerId, text);
|
||||
}
|
||||
|
||||
list(
|
||||
chatId: string,
|
||||
callerId: string,
|
||||
limit: number,
|
||||
rawCursor: string | null,
|
||||
): MessagePageResponse {
|
||||
this.assertMember(chatId, callerId);
|
||||
const cursor =
|
||||
rawCursor === null ? null : decodeMessageCursor(rawCursor);
|
||||
if (rawCursor !== null && cursor === null) {
|
||||
throw new ApiError('invalid_request', 'invalid cursor');
|
||||
}
|
||||
if (cursor && cursor.chatId !== chatId) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'cursor belongs to a different chat',
|
||||
);
|
||||
}
|
||||
if (cursor && !this.store.messageCursorExists(chatId, cursor.id)) {
|
||||
throw new ApiError('invalid_request', 'invalid cursor');
|
||||
}
|
||||
const items = this.store.listMessages(chatId, cursor, limit);
|
||||
const last = items[items.length - 1];
|
||||
const hasMore = last
|
||||
? this.store.hasMoreMessagesAfter(chatId, last.id)
|
||||
: false;
|
||||
return {
|
||||
items: items.map(toMessageResponse),
|
||||
next_cursor: hasMore
|
||||
? encodeMessageCursor({ chatId, id: last.id })
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
private assertMember(chatId: string, callerId: string): void {
|
||||
if (!isUuid(chatId)) {
|
||||
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
||||
}
|
||||
if (
|
||||
!this.store.getChatById(chatId) ||
|
||||
!this.store.isMember(chatId, callerId)
|
||||
) {
|
||||
throw new ApiError('not_found', 'chat not found');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Matches } from 'class-validator';
|
||||
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||
import { NotBlank } from '../../common/dto/not-blank.validator';
|
||||
|
||||
export class CreateUserDto {
|
||||
@Matches(/^[a-z0-9_]{3,32}$/, {
|
||||
message: 'username must match [a-z0-9_]{3,32}',
|
||||
})
|
||||
username!: string;
|
||||
|
||||
@NotBlank()
|
||||
@CodePointLength(1, 100)
|
||||
display_name!: string;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { User } from '../../common/store/domain';
|
||||
|
||||
export interface UserResponse {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export function toUserResponse(user: User): UserResponse {
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
display_name: user.displayName,
|
||||
created_at: user.createdAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '../common/auth/auth.guard';
|
||||
import { CurrentUser } from '../common/auth/current-user.decorator';
|
||||
import { User } from '../common/store/domain';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { toUserResponse, UserResponse } from './dto/user.response';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Controller('api/v1/users')
|
||||
export class UsersController {
|
||||
constructor(private readonly users: UsersService) {}
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
create(@Body() dto: CreateUserDto): UserResponse {
|
||||
const user = this.users.register(dto.username, dto.display_name);
|
||||
return toUserResponse(user);
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@UseGuards(AuthGuard)
|
||||
me(@CurrentUser() user: User): UserResponse {
|
||||
return toUserResponse(user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CommonModule } from '../common/common.module';
|
||||
import { UsersController } from './users.controller';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Module({
|
||||
imports: [CommonModule],
|
||||
controllers: [UsersController],
|
||||
providers: [UsersService],
|
||||
exports: [UsersService],
|
||||
})
|
||||
export class UsersModule {}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { User } from '../common/store/domain';
|
||||
import { StoreService } from '../common/store/store.service';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
register(username: string, displayName: string): User {
|
||||
const user = this.store.createUser(username, displayName.trim());
|
||||
if (!user) {
|
||||
throw new ApiError('conflict', 'username is already taken');
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
} from '@nestjs/platform-fastify';
|
||||
import request from 'supertest';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { AppModule } from '../src/app.module';
|
||||
import { configureApp } from '../src/configure-app';
|
||||
|
||||
describe('API мессенджера (e2e) — граничные случаи сверх публичного smoke', () => {
|
||||
let app: INestApplication;
|
||||
let server: any;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
const fastifyApp =
|
||||
moduleRef.createNestApplication<NestFastifyApplication>(
|
||||
new FastifyAdapter(),
|
||||
);
|
||||
app = fastifyApp;
|
||||
configureApp(fastifyApp);
|
||||
await fastifyApp.listen(0, '127.0.0.1');
|
||||
server = fastifyApp.getHttpServer();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
async function createUser(label: string) {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `u_${label}_${randomUUID().slice(0, 8)}`,
|
||||
display_name: `User ${label}`,
|
||||
})
|
||||
.expect(201);
|
||||
return res.body as { id: string; username: string };
|
||||
}
|
||||
|
||||
describe('POST /api/v1/users', () => {
|
||||
it('отклоняет некорректный JSON с кодом 400', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send('{not valid json')
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
expect(res.body.error.request_id).toBeTruthy();
|
||||
});
|
||||
|
||||
it('отклоняет тело с лишними полями', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'validname1',
|
||||
display_name: 'Valid',
|
||||
extra: 'nope',
|
||||
})
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('отклоняет username с заглавными буквами', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'InvalidName', display_name: 'X' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет display_name из одних пробелов', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'wsonlyname1', display_name: ' ' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет дубликат username с кодом 409', async () => {
|
||||
const user = await createUser('dup');
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: user.username, display_name: 'Someone else' })
|
||||
.expect(409);
|
||||
expect(res.body.error.code).toBe('conflict');
|
||||
});
|
||||
|
||||
it('никогда не возвращает поле пароля или его хэша', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `nopass_${randomUUID().slice(0, 8)}`,
|
||||
display_name: 'X',
|
||||
})
|
||||
.expect(201);
|
||||
expect(res.body).not.toHaveProperty('password');
|
||||
expect(res.body).not.toHaveProperty('password_hash');
|
||||
});
|
||||
|
||||
it('отклоняет username короче 3 символов', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'ab', display_name: 'X' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет username длиннее 32 символов', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'a'.repeat(33), display_name: 'X' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет username с недопустимыми символами (дефис)', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: 'has-hyphen', display_name: 'X' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('принимает username ровно на границах длины 3 и 32 символа', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `a${randomUUID().slice(0, 2)}`,
|
||||
display_name: 'X',
|
||||
})
|
||||
.expect(201);
|
||||
const longest = ('z' + randomUUID().replace(/-/g, '')).slice(0, 32);
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username: longest, display_name: 'X' })
|
||||
.expect(201);
|
||||
});
|
||||
|
||||
it('отклоняет display_name длиннее 100 Unicode code points', async () => {
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `toolongname_${randomUUID().slice(0, 6)}`,
|
||||
display_name: 'x'.repeat(101),
|
||||
})
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('принимает display_name ровно из 100 code points, считая эмодзи вне BMP за один символ', async () => {
|
||||
const displayName = '👋'.repeat(100);
|
||||
expect([...displayName].length).toBe(100);
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `emojiname_${randomUUID().slice(0, 6)}`,
|
||||
display_name: displayName,
|
||||
})
|
||||
.expect(201);
|
||||
});
|
||||
|
||||
it('отклоняет display_name из 101 code point, состоящий из эмодзи вне BMP', async () => {
|
||||
const displayName = '👋'.repeat(100) + 'x';
|
||||
expect([...displayName].length).toBe(101);
|
||||
await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `emojitoolong_${randomUUID().slice(0, 6)}`,
|
||||
display_name: displayName,
|
||||
})
|
||||
.expect(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('контроль доступа', () => {
|
||||
it('возвращает 401 раньше 404, если и актор, и ресурс невалидны', async () => {
|
||||
const res = await request(server)
|
||||
.get(`/api/v1/chats/${randomUUID()}`)
|
||||
.set('X-User-Id', 'not-a-uuid')
|
||||
.expect(401);
|
||||
expect(res.body.error.code).toBe('unauthorized');
|
||||
});
|
||||
|
||||
it('возвращает 404 (не 403), когда чат запрашивает не его участник', async () => {
|
||||
const alice = await createUser('alice');
|
||||
const bob = await createUser('bob');
|
||||
const eve = await createUser('eve');
|
||||
const chat = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ title: 'Private', member_ids: [alice.id, bob.id] })
|
||||
.expect(201);
|
||||
|
||||
const res = await request(server)
|
||||
.get(`/api/v1/chats/${chat.body.id}`)
|
||||
.set('X-User-Id', eve.id)
|
||||
.expect(404);
|
||||
expect(res.body.error.code).toBe('not_found');
|
||||
});
|
||||
|
||||
it('отклоняет создание чата, если вызывающий не входит в member_ids', async () => {
|
||||
const alice = await createUser('alice2');
|
||||
const bob = await createUser('bob2');
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ title: 'Missing caller', member_ids: [bob.id] })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет создание чата с дублирующимися member_ids', async () => {
|
||||
const alice = await createUser('alice3');
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({
|
||||
title: 'Dup members',
|
||||
member_ids: [alice.id, alice.id],
|
||||
})
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет создание чата с неизвестным участником', async () => {
|
||||
const alice = await createUser('alice4');
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({
|
||||
title: 'Unknown member',
|
||||
member_ids: [alice.id, randomUUID()],
|
||||
})
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет создание чата с пустым/пробельным title', async () => {
|
||||
const alice = await createUser('alice4b');
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ title: ' ', member_ids: [alice.id] })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('возвращает 400 для синтаксически некорректного chat_id (не UUID)', async () => {
|
||||
const alice = await createUser('alice4c');
|
||||
const res = await request(server)
|
||||
.get('/api/v1/chats/not-a-uuid')
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('возвращает 404 для корректного по формату, но несуществующего chat_id', async () => {
|
||||
const alice = await createUser('alice4d');
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${randomUUID()}`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/chats (пагинация)', () => {
|
||||
it('использует limit=50 по умолчанию, если limit не передан', async () => {
|
||||
const alice = await createUser('pgalice1');
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ title: 'Only chat', member_ids: [alice.id] })
|
||||
.expect(201);
|
||||
const res = await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(200);
|
||||
expect(res.body.items.length).toBeGreaterThanOrEqual(1);
|
||||
expect(res.body.items.length).toBeLessThanOrEqual(50);
|
||||
});
|
||||
|
||||
it('отклоняет нечисловой limit', async () => {
|
||||
const alice = await createUser('pgalice2');
|
||||
await request(server)
|
||||
.get('/api/v1/chats?limit=abc')
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет limit=0', async () => {
|
||||
const alice = await createUser('pgalice3');
|
||||
await request(server)
|
||||
.get('/api/v1/chats?limit=0')
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет cursor, не являющийся корректным base64url JSON', async () => {
|
||||
const alice = await createUser('pgalice4');
|
||||
await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.query({ cursor: 'not-a-real-cursor!!!' })
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет корректно закодированный cursor с id чата, который никогда не существовал', async () => {
|
||||
const alice = await createUser('pgalice4b');
|
||||
const bogusCursor = Buffer.from(
|
||||
JSON.stringify({ id: randomUUID() }),
|
||||
'utf8',
|
||||
).toString('base64url');
|
||||
const res = await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.query({ cursor: bogusCursor })
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('обходит весь список чатов по страницам без пропусков и дублей', async () => {
|
||||
const alice = await createUser('pgalice5');
|
||||
const titles = ['c1', 'c2', 'c3', 'c4', 'c5'];
|
||||
for (const title of titles) {
|
||||
await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ title, member_ids: [alice.id] })
|
||||
.expect(201);
|
||||
}
|
||||
|
||||
const seen: string[] = [];
|
||||
let cursor: string | null = null;
|
||||
do {
|
||||
const res: request.Response = await request(server)
|
||||
.get('/api/v1/chats')
|
||||
.query({ limit: 2, ...(cursor ? { cursor } : {}) })
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(200);
|
||||
seen.push(
|
||||
...res.body.items.map((c: { title: string }) => c.title),
|
||||
);
|
||||
cursor = res.body.next_cursor;
|
||||
} while (cursor);
|
||||
|
||||
expect(seen).toEqual(titles);
|
||||
});
|
||||
});
|
||||
|
||||
describe('сообщения', () => {
|
||||
async function createChat(alice: { id: string }, bob: { id: string }) {
|
||||
const res = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ title: 'Chat', member_ids: [alice.id, bob.id] })
|
||||
.expect(201);
|
||||
return res.body as { id: string };
|
||||
}
|
||||
|
||||
it('не принимает sender_id, переданный клиентом', async () => {
|
||||
const alice = await createUser('alice5');
|
||||
const bob = await createUser('bob5');
|
||||
const chat = await createChat(alice, bob);
|
||||
|
||||
const res = await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ text: 'hi', sender_id: bob.id })
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('отклоняет пустое сообщение', async () => {
|
||||
const alice = await createUser('alice6');
|
||||
const bob = await createUser('bob6');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ text: '' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет сообщение из одних пробелов', async () => {
|
||||
const alice = await createUser('alice7');
|
||||
const bob = await createUser('bob7');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ text: ' \n\t ' })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет отправку в чат, где вызывающий не участник', async () => {
|
||||
const alice = await createUser('alice8');
|
||||
const bob = await createUser('bob8');
|
||||
const eve = await createUser('eve8');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('X-User-Id', eve.id)
|
||||
.send({ text: 'intrusion' })
|
||||
.expect(404);
|
||||
});
|
||||
|
||||
it('отклоняет limit=0 при чтении истории', async () => {
|
||||
const alice = await createUser('alice9');
|
||||
const bob = await createUser('bob9');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages?limit=0`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет limit=101 при чтении истории', async () => {
|
||||
const alice = await createUser('alice10');
|
||||
const bob = await createUser('bob10');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages?limit=101`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет нечисловой limit', async () => {
|
||||
const alice = await createUser('alice10b');
|
||||
const bob = await createUser('bob10b');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages?limit=abc`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет текст сообщения длиннее 4000 Unicode code points', async () => {
|
||||
const alice = await createUser('alice10c');
|
||||
const bob = await createUser('bob10c');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ text: 'x'.repeat(4001) })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('принимает текст сообщения ровно из 4000 Unicode code points', async () => {
|
||||
const alice = await createUser('alice10d');
|
||||
const bob = await createUser('bob10d');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ text: 'x'.repeat(4000) })
|
||||
.expect(201);
|
||||
});
|
||||
|
||||
it('отклоняет текст сообщения свыше 4000 code points, состоящий из эмодзи вне BMP', async () => {
|
||||
const alice = await createUser('alice10e');
|
||||
const bob = await createUser('bob10e');
|
||||
const chat = await createChat(alice, bob);
|
||||
const text = '👋'.repeat(4001);
|
||||
expect([...text].length).toBe(4001);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ text })
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет cursor, не являющийся корректным base64url JSON', async () => {
|
||||
const alice = await createUser('alice10f');
|
||||
const bob = await createUser('bob10f');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages`)
|
||||
.query({ cursor: '!!!not-valid!!!' })
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
});
|
||||
|
||||
it('отклоняет корректно закодированный cursor с id сообщения, которое никогда не существовало в этом чате', async () => {
|
||||
const alice = await createUser('alice10i');
|
||||
const bob = await createUser('bob10i');
|
||||
const chat = await createChat(alice, bob);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ text: 'only message' })
|
||||
.expect(201);
|
||||
|
||||
const bogusCursor = Buffer.from(
|
||||
JSON.stringify({ chatId: chat.id, id: randomUUID() }),
|
||||
'utf8',
|
||||
).toString('base64url');
|
||||
const res = await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages`)
|
||||
.query({ cursor: bogusCursor })
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('возвращает 400 для синтаксически некорректного chat_id при отправке сообщения', async () => {
|
||||
const alice = await createUser('alice10g');
|
||||
const res = await request(server)
|
||||
.post('/api/v1/chats/not-a-uuid/messages')
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ text: 'hi' })
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('возвращает 400 для синтаксически некорректного chat_id при чтении истории', async () => {
|
||||
const alice = await createUser('alice10h');
|
||||
const res = await request(server)
|
||||
.get('/api/v1/chats/not-a-uuid/messages')
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('отклоняет cursor, взятый из другого чата', async () => {
|
||||
const alice = await createUser('alice11');
|
||||
const bob = await createUser('bob11');
|
||||
const chatA = await createChat(alice, bob);
|
||||
const chatB = await createChat(alice, bob);
|
||||
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chatA.id}/messages`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ text: 'first' })
|
||||
.expect(201);
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chatA.id}/messages`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ text: 'second' })
|
||||
.expect(201);
|
||||
|
||||
const page1 = await request(server)
|
||||
.get(`/api/v1/chats/${chatA.id}/messages?limit=1`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(200);
|
||||
expect(page1.body.next_cursor).toBeTruthy();
|
||||
|
||||
const res = await request(server)
|
||||
.get(`/api/v1/chats/${chatB.id}/messages`)
|
||||
.query({ cursor: page1.body.next_cursor })
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(400);
|
||||
expect(res.body.error.code).toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('обходит всю историю по страницам без пропусков и дублей', async () => {
|
||||
const alice = await createUser('alice12');
|
||||
const bob = await createUser('bob12');
|
||||
const chat = await createChat(alice, bob);
|
||||
const sentTexts = ['m1', 'm2', 'm3', 'm4', 'm5'];
|
||||
for (const text of sentTexts) {
|
||||
await request(server)
|
||||
.post(`/api/v1/chats/${chat.id}/messages`)
|
||||
.set('X-User-Id', alice.id)
|
||||
.send({ text })
|
||||
.expect(201);
|
||||
}
|
||||
|
||||
const seen: string[] = [];
|
||||
let cursor: string | null = null;
|
||||
do {
|
||||
const res: request.Response = await request(server)
|
||||
.get(`/api/v1/chats/${chat.id}/messages`)
|
||||
.query({ limit: 2, ...(cursor ? { cursor } : {}) })
|
||||
.set('X-User-Id', alice.id)
|
||||
.expect(200);
|
||||
seen.push(
|
||||
...res.body.items.map((m: { text: string }) => m.text),
|
||||
);
|
||||
cursor = res.body.next_cursor;
|
||||
} while (cursor);
|
||||
|
||||
expect(seen).toEqual(sentTexts);
|
||||
});
|
||||
});
|
||||
|
||||
describe('X-Request-Id', () => {
|
||||
it('присутствует и уникален для независимых запросов', async () => {
|
||||
const first = await request(server).get('/health/live').expect(200);
|
||||
const second = await request(server)
|
||||
.get('/health/live')
|
||||
.expect(200);
|
||||
expect(first.headers['x-request-id']).toBeTruthy();
|
||||
expect(second.headers['x-request-id']).toBeTruthy();
|
||||
expect(first.headers['x-request-id']).not.toBe(
|
||||
second.headers['x-request-id'],
|
||||
);
|
||||
});
|
||||
|
||||
it('совпадает с request_id внутри тела ошибки', async () => {
|
||||
const res = await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.expect(401);
|
||||
expect(res.body.error.request_id).toBe(res.headers['x-request-id']);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
} from '@nestjs/platform-fastify';
|
||||
import request from 'supertest';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { AppModule } from '../src/app.module';
|
||||
import { configureApp } from '../src/configure-app';
|
||||
|
||||
describe('Безопасность при конкурентном доступе (e2e)', () => {
|
||||
let app: INestApplication;
|
||||
let server: any;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
const fastifyApp =
|
||||
moduleRef.createNestApplication<NestFastifyApplication>(
|
||||
new FastifyAdapter(),
|
||||
);
|
||||
app = fastifyApp;
|
||||
configureApp(fastifyApp);
|
||||
await fastifyApp.listen(0, '127.0.0.1');
|
||||
server = fastifyApp.getHttpServer();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных', async () => {
|
||||
const CLIENTS = 10;
|
||||
const MESSAGES_PER_CLIENT = 10;
|
||||
|
||||
const owner = await request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `owner_${randomUUID().slice(0, 8)}`,
|
||||
display_name: 'Owner',
|
||||
})
|
||||
.expect(201);
|
||||
|
||||
const clients = await Promise.all(
|
||||
Array.from({ length: CLIENTS }, (_, i) =>
|
||||
request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: `racer${i}_${randomUUID().slice(0, 6)}`,
|
||||
display_name: `Racer ${i}`,
|
||||
})
|
||||
.expect(201),
|
||||
),
|
||||
);
|
||||
const memberIds = [owner.body.id, ...clients.map((c) => c.body.id)];
|
||||
|
||||
const chat = await request(server)
|
||||
.post('/api/v1/chats')
|
||||
.set('X-User-Id', owner.body.id)
|
||||
.send({ title: 'Race', member_ids: memberIds })
|
||||
.expect(201);
|
||||
|
||||
const sendTasks: Promise<request.Response>[] = [];
|
||||
for (let c = 0; c < CLIENTS; c++) {
|
||||
for (let m = 0; m < MESSAGES_PER_CLIENT; m++) {
|
||||
sendTasks.push(
|
||||
request(server)
|
||||
.post(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.set('X-User-Id', clients[c].body.id)
|
||||
.send({ text: `client-${c}-message-${m}` }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const responses = await Promise.all(sendTasks);
|
||||
for (const res of responses) {
|
||||
expect(res.status).toBe(201);
|
||||
}
|
||||
|
||||
const sentIds = new Set(responses.map((r) => r.body.id));
|
||||
expect(sentIds.size).toBe(CLIENTS * MESSAGES_PER_CLIENT);
|
||||
|
||||
const collected: { id: string; text: string }[] = [];
|
||||
let cursor: string | null = null;
|
||||
do {
|
||||
const res: request.Response = await request(server)
|
||||
.get(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.query({ limit: 25, ...(cursor ? { cursor } : {}) })
|
||||
.set('X-User-Id', owner.body.id)
|
||||
.expect(200);
|
||||
collected.push(...res.body.items);
|
||||
cursor = res.body.next_cursor;
|
||||
} while (cursor);
|
||||
|
||||
expect(collected.length).toBe(CLIENTS * MESSAGES_PER_CLIENT);
|
||||
const uniqueIds = new Set(collected.map((m) => m.id));
|
||||
expect(uniqueIds.size).toBe(CLIENTS * MESSAGES_PER_CLIENT);
|
||||
|
||||
const uniqueTexts = new Set(collected.map((m) => m.text));
|
||||
expect(uniqueTexts.size).toBe(CLIENTS * MESSAGES_PER_CLIENT);
|
||||
|
||||
const fullHistory: { id: string; created_at: string }[] =
|
||||
await request(server)
|
||||
.get(`/api/v1/chats/${chat.body.id}/messages`)
|
||||
.query({ limit: 100 })
|
||||
.set('X-User-Id', owner.body.id)
|
||||
.expect(200)
|
||||
.then((res) => res.body.items);
|
||||
const sortKeys = fullHistory.map((m) => `${m.created_at}#${m.id}`);
|
||||
const sortedKeys = [...sortKeys].sort();
|
||||
expect(sortKeys).toEqual(sortedKeys);
|
||||
});
|
||||
|
||||
it('регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username', async () => {
|
||||
const username = `racer_username_${randomUUID().slice(0, 8)}`;
|
||||
const attempts = 10;
|
||||
|
||||
const responses = await Promise.all(
|
||||
Array.from({ length: attempts }, () =>
|
||||
request(server)
|
||||
.post('/api/v1/users')
|
||||
.send({ username, display_name: 'Racer' }),
|
||||
),
|
||||
);
|
||||
|
||||
const succeeded = responses.filter((r) => r.status === 201);
|
||||
const conflicted = responses.filter((r) => r.status === 409);
|
||||
|
||||
expect(succeeded.length).toBe(1);
|
||||
expect(conflicted.length).toBe(attempts - 1);
|
||||
expect(succeeded.length + conflicted.length).toBe(attempts);
|
||||
|
||||
const listRes = await request(server)
|
||||
.get('/api/v1/users/me')
|
||||
.set('X-User-Id', succeeded[0].body.id)
|
||||
.expect(200);
|
||||
expect(listRes.body.username).toBe(username);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "experiments", "**/*spec.ts"]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"declaration": false,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2021",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"strictNullChecks": true,
|
||||
"noImplicitAny": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"esModuleInterop": true,
|
||||
"types": ["node", "jest"]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user