feat(api): implement persistent messaging and graceful draining

Add shared sessions, cached message history and transactional idempotency backed by PostgreSQL. Return readiness 503 during draining and finish in-flight requests before closing dependencies.
This commit is contained in:
2026-10-29 11:46:28 +03:00
parent 298204dbe9
commit 24f32c3fbe
35 changed files with 2102 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
import 'dotenv/config';
import { defineConfig } from 'prisma/config';
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: { path: 'prisma/migrations' },
datasource: { url: process.env.DATABASE_URL },
});
@@ -0,0 +1,56 @@
CREATE SCHEMA IF NOT EXISTS "public";
CREATE TABLE "users" (
"id" UUID NOT NULL,
"username" VARCHAR(32) NOT NULL,
"display_name" VARCHAR(100) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "chats" (
"id" UUID NOT NULL,
"title" VARCHAR(100) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "chats_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "chat_members" (
"chat_id" UUID NOT NULL,
"user_id" UUID NOT NULL,
"position" INTEGER NOT NULL,
CONSTRAINT "chat_members_pkey" PRIMARY KEY ("chat_id","user_id")
);
CREATE TABLE "messages" (
"id" UUID NOT NULL,
"chat_id" UUID NOT NULL,
"sender_id" UUID NOT NULL,
"text" VARCHAR(4000) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "messages_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "users_username_key" ON "users"("username");
CREATE INDEX "chats_created_at_id_idx" ON "chats"("created_at", "id");
CREATE INDEX "chat_members_user_id_chat_id_idx" ON "chat_members"("user_id", "chat_id");
CREATE UNIQUE INDEX "chat_members_chat_id_position_key" ON "chat_members"("chat_id", "position");
CREATE INDEX "messages_chat_id_created_at_id_idx" ON "messages"("chat_id", "created_at", "id");
CREATE INDEX "messages_sender_id_idx" ON "messages"("sender_id");
ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "messages" ADD CONSTRAINT "messages_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "messages" ADD CONSTRAINT "messages_sender_id_fkey" FOREIGN KEY ("sender_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,20 @@
ALTER TABLE "users" ADD COLUMN "password_hash" TEXT;
CREATE TABLE "sessions" (
"id" UUID NOT NULL,
"user_id" UUID NOT NULL,
"token_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expires_at" TIMESTAMPTZ(3) NOT NULL,
"revoked_at" TIMESTAMPTZ(3),
CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "sessions_token_hash_key" ON "sessions"("token_hash");
CREATE INDEX "sessions_user_id_idx" ON "sessions"("user_id");
CREATE INDEX "sessions_expires_at_idx" ON "sessions"("expires_at");
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
ALTER TABLE "users" ADD COLUMN "chats_epoch" BIGINT NOT NULL DEFAULT 0;
ALTER TABLE "chats" ADD COLUMN "messages_epoch" BIGINT NOT NULL DEFAULT 0;
@@ -0,0 +1,13 @@
CREATE TABLE "chat_message_epochs" (
"chat_id" UUID NOT NULL,
"bucket" SMALLINT NOT NULL,
"epoch" BIGINT NOT NULL DEFAULT 0,
CONSTRAINT "chat_message_epochs_pkey" PRIMARY KEY ("chat_id", "bucket"),
CONSTRAINT "chat_message_epochs_bucket_check" CHECK ("bucket" BETWEEN 0 AND 15),
CONSTRAINT "chat_message_epochs_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "chat_message_epochs" ("chat_id", "bucket", "epoch")
SELECT "id", 0, "messages_epoch" FROM "chats";
ALTER TABLE "chats" DROP COLUMN "messages_epoch";
@@ -0,0 +1,15 @@
CREATE TABLE "message_idempotency" (
"user_id" UUID NOT NULL,
"chat_id" UUID NOT NULL,
"key" VARCHAR(128) NOT NULL,
"message_id" UUID,
"expires_at" TIMESTAMPTZ(3) NOT NULL,
CONSTRAINT "message_idempotency_pkey" PRIMARY KEY ("user_id", "chat_id", "key"),
CONSTRAINT "message_idempotency_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "message_idempotency_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "message_idempotency_message_id_fkey" FOREIGN KEY ("message_id") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE INDEX "message_idempotency_expires_at_idx" ON "message_idempotency"("expires_at");
CREATE INDEX "message_idempotency_chat_id_idx" ON "message_idempotency"("chat_id");
CREATE INDEX "message_idempotency_message_id_idx" ON "message_idempotency"("message_id");
+1
View File
@@ -0,0 +1 @@
provider = "postgresql"
+106
View File
@@ -0,0 +1,106 @@
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
moduleFormat = "cjs"
}
datasource db {
provider = "postgresql"
}
model User {
id String @id @default(uuid()) @db.Uuid
username String @unique @db.VarChar(32)
displayName String @map("display_name") @db.VarChar(100)
passwordHash String? @map("password_hash")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
chatsEpoch BigInt @default(0) @map("chats_epoch")
memberships ChatMember[]
messages Message[]
sessions Session[]
idempotencyRecords MessageIdempotency[]
@@map("users")
}
model Session {
id String @id @default(uuid()) @db.Uuid
userId String @map("user_id") @db.Uuid
tokenHash String @unique @map("token_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
expiresAt DateTime @map("expires_at") @db.Timestamptz(3)
revokedAt DateTime? @map("revoked_at") @db.Timestamptz(3)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
@@index([expiresAt])
@@map("sessions")
}
model Chat {
id String @id @default(uuid()) @db.Uuid
title String @db.VarChar(100)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
messageEpochs ChatMessageEpoch[]
members ChatMember[]
messages Message[]
idempotencyRecords MessageIdempotency[]
@@index([createdAt, id])
@@map("chats")
}
model ChatMember {
chatId String @map("chat_id") @db.Uuid
userId String @map("user_id") @db.Uuid
position Int
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
@@id([chatId, userId])
@@unique([chatId, position])
@@index([userId, chatId])
@@map("chat_members")
}
model ChatMessageEpoch {
chatId String @map("chat_id") @db.Uuid
bucket Int @db.SmallInt
epoch BigInt @default(0)
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
@@id([chatId, bucket])
@@map("chat_message_epochs")
}
model Message {
id String @id @default(uuid()) @db.Uuid
chatId String @map("chat_id") @db.Uuid
senderId String @map("sender_id") @db.Uuid
text String @db.VarChar(4000)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
sender User @relation(fields: [senderId], references: [id], onDelete: Restrict)
idempotencyRecords MessageIdempotency[]
@@index([chatId, createdAt, id])
@@index([senderId])
@@map("messages")
}
model MessageIdempotency {
userId String @map("user_id") @db.Uuid
chatId String @map("chat_id") @db.Uuid
key String @db.VarChar(128)
messageId String? @map("message_id") @db.Uuid
expiresAt DateTime @map("expires_at") @db.Timestamptz(3)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
message Message? @relation(fields: [messageId], references: [id], onDelete: Cascade)
@@id([userId, chatId, key])
@@index([chatId])
@@index([messageId])
@@index([expiresAt])
@@map("message_idempotency")
}
+69
View File
@@ -0,0 +1,69 @@
import {
Body,
Controller,
Delete,
HttpCode,
HttpStatus,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import {
ApiBasicAuth,
ApiBearerAuth,
ApiCreatedResponse,
ApiNoContentResponse,
ApiOperation,
ApiTags,
ApiUnauthorizedResponse,
} from '@nestjs/swagger';
import { UserGuard, type AuthenticatedRequest } from '../User/user.guard';
import { AuthService } from './auth.service';
import { Session } from './auth.schema';
@ApiTags('auth')
@Controller('api/v1/auth/sessions')
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Post()
@HttpCode(HttpStatus.CREATED)
@ApiBasicAuth('basicAuth')
@ApiOperation({
operationId: 'createSession',
summary: 'Вход',
})
@ApiCreatedResponse({ type: Session })
@ApiUnauthorizedResponse({
headers: {
'WWW-Authenticate': {
schema: { type: 'string' },
example: 'Basic realm="messenger", charset="UTF-8"',
},
},
})
create(@Req() request: AuthenticatedRequest, @Body() body: unknown) {
return this.auth.login(request.headers.authorization, body);
}
@Delete('current')
@HttpCode(HttpStatus.NO_CONTENT)
@UseGuards(UserGuard)
@ApiBearerAuth('bearerAuth')
@ApiOperation({
operationId: 'revokeSession',
summary: 'Отзыв текущей сессии',
})
@ApiNoContentResponse()
@ApiUnauthorizedResponse({
headers: {
'WWW-Authenticate': {
schema: { type: 'string' },
example: 'Bearer realm="messenger"',
},
},
})
logout(@Req() request: AuthenticatedRequest) {
return this.auth.logout(request.currentSessionId);
}
}
+18
View File
@@ -0,0 +1,18 @@
import { HttpStatus } from '@nestjs/common';
import { ApiException } from '../common/exceptions/api.exception';
export class AuthException extends ApiException {
readonly challenge: string;
constructor(scheme: 'Basic' | 'Bearer') {
super(
HttpStatus.UNAUTHORIZED,
'unauthorized',
'Требуется действительная аутентификация',
);
this.challenge =
scheme === 'Basic'
? 'Basic realm="messenger", charset="UTF-8"'
: 'Bearer realm="messenger"';
}
}
+15
View File
@@ -0,0 +1,15 @@
import { ApiProperty } from '@nestjs/swagger';
import { User } from '../User/user.schema';
export class Session {
token!: string;
@ApiProperty({ enum: ['Bearer'] })
token_type!: 'Bearer';
@ApiProperty({ format: 'date-time' })
expires_at!: string;
@ApiProperty({ type: User })
user!: User;
}
+182
View File
@@ -0,0 +1,182 @@
import { Injectable } from '@nestjs/common';
import { createHash, randomBytes } from 'node:crypto';
import { TextDecoder } from 'node:util';
import { PrismaService } from '../prisma/prisma.service';
import { Prisma } from '../generated/prisma/client';
import { UserService } from '../User/user.service';
import type { User } from '../User/user.schema';
import { invalidRequest, uuid, uuidPattern } from '../common/validation';
import { ApiException } from '../common/exceptions/api.exception';
import { AuthException } from './auth.exception';
import { PasswordService, validPassword } from './password.service';
import type { Session } from './auth.schema';
export interface ChatAccess {
chatId: string;
userId: string;
messagesEpoch: string;
}
@Injectable()
export class AuthService {
private readonly ttlSeconds: number;
constructor(
private readonly prisma: PrismaService,
private readonly users: UserService,
private readonly passwords: PasswordService,
) {
this.ttlSeconds = Number(process.env.SESSION_TTL_SECONDS ?? 3600);
if (
!Number.isSafeInteger(this.ttlSeconds) ||
this.ttlSeconds <= 0 ||
Number.isNaN(new Date(Date.now() + this.ttlSeconds * 1000).getTime())
) {
throw new Error(
'SESSION_TTL_SECONDS must be a positive integer representing a valid expiry',
);
}
}
async login(authorization: unknown, body: unknown): Promise<Session> {
const { username, password } = this.basicCredentials(authorization);
const user = await this.prisma.user.findUnique({ where: { username } });
const verified = await this.passwords.verify(
password,
user?.passwordHash ?? null,
);
if (!user || !verified) throw new AuthException('Basic');
if (body !== undefined)
return invalidRequest('Вход через Basic не принимает тело запроса');
const token = randomBytes(32).toString('base64url');
const session = await this.prisma.session.create({
data: {
userId: user.id,
tokenHash: this.tokenHash(token),
expiresAt: new Date(Date.now() + this.ttlSeconds * 1000),
},
});
return {
token,
token_type: 'Bearer',
expires_at: session.expiresAt.toISOString(),
user: this.users.serialize(user),
};
}
async authenticate(
authorization: unknown,
chatId?: unknown,
): Promise<{
user: User;
sessionId: string;
chatsEpoch: string;
chatAccess?: ChatAccess;
}> {
const match =
typeof authorization === 'string' &&
/^Bearer +([A-Za-z0-9_-]{43})$/i.exec(authorization);
if (!match) throw new AuthException('Bearer');
const requestedChat =
typeof chatId === 'string' && uuidPattern.test(chatId)
? chatId.toLowerCase()
: null;
const [session] = await this.prisma.$queryRaw<
{
id: string;
userId: string;
username: string;
displayName: string;
createdAt: Date;
chatsEpoch: bigint;
chatId: string | null;
messagesEpoch: bigint | null;
}[]
>(Prisma.sql`
SELECT s.id, s.user_id AS "userId", u.chats_epoch AS "chatsEpoch",
u.username, u.display_name AS "displayName", u.created_at AS "createdAt",
${
chatId === undefined
? Prisma.sql`NULL::uuid AS "chatId", NULL::bigint AS "messagesEpoch"`
: Prisma.sql`c.id AS "chatId", COALESCE((SELECT SUM(e.epoch) FROM "public"."chat_message_epochs" AS e WHERE e.chat_id = c.id), 0)::bigint AS "messagesEpoch"`
}
FROM sessions AS s
JOIN users AS u ON u.id = s.user_id
${
chatId === undefined
? Prisma.empty
: Prisma.sql`
LEFT JOIN chat_members AS cm
ON cm.user_id = s.user_id AND cm.chat_id = ${requestedChat}::uuid
LEFT JOIN chats AS c ON c.id = cm.chat_id
`
}
WHERE s.token_hash = ${this.tokenHash(match[1])}
AND s.revoked_at IS NULL AND s.expires_at > ${new Date()}
LIMIT 1
`);
if (!session) throw new AuthException('Bearer');
if (chatId !== undefined) {
uuid(chatId, 'chat_id');
if (session.chatId === null || session.messagesEpoch === null)
throw new ApiException(404, 'not_found', 'Объект не найден');
}
return {
user: this.users.serialize({ ...session, id: session.userId }),
sessionId: session.id,
chatsEpoch: session.chatsEpoch.toString(),
chatAccess:
session.chatId !== null && session.messagesEpoch !== null
? {
chatId: session.chatId,
userId: session.userId,
messagesEpoch: session.messagesEpoch.toString(),
}
: undefined,
};
}
async logout(sessionId: string): Promise<void> {
const now = new Date();
const result = await this.prisma.session.updateMany({
where: { id: sessionId, revokedAt: null, expiresAt: { gt: now } },
data: { revokedAt: now },
});
if (result.count !== 1) throw new AuthException('Bearer');
}
private tokenHash(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
private basicCredentials(authorization: unknown): {
username: string;
password: string;
} {
const match =
typeof authorization === 'string' &&
/^Basic +([A-Za-z0-9+/]+={0,2})$/i.exec(authorization);
if (!match) throw new AuthException('Basic');
try {
const bytes = Buffer.from(match[1], 'base64');
if (
bytes.toString('base64').replace(/=+$/, '') !==
match[1].replace(/=+$/, '')
)
throw new AuthException('Basic');
const value = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
const colon = value.indexOf(':');
const username = value.slice(0, colon);
const password = value.slice(colon + 1);
if (
colon < 0 ||
!/^[a-z0-9_]{3,32}$/.test(username) ||
!validPassword(password)
)
throw new AuthException('Basic');
return { username, password };
} catch {
throw new AuthException('Basic');
}
}
}
+72
View File
@@ -0,0 +1,72 @@
import { Injectable } from '@nestjs/common';
import { argon2, randomBytes, timingSafeEqual } from 'node:crypto';
import { invalidRequest } from '../common/validation';
const argonParameters = {
memory: 19456,
passes: 2,
parallelism: 1,
tagLength: 32,
};
const argonPrefix = '$argon2id$v=19$m=19456,t=2,p=1';
function decodeBase64(value: string, length: number) {
const decoded = Buffer.from(value, 'base64');
return decoded.length === length &&
decoded.toString('base64').replace(/=+$/, '') === value
? decoded
: undefined;
}
function argonHash(value: string | null) {
const parts = value?.split('$');
if (parts?.length !== 6 || parts.slice(0, 4).join('$') !== argonPrefix)
return undefined;
const salt = decodeBase64(parts[4], 16);
const key = decodeBase64(parts[5], 32);
return salt && key ? { salt, key } : undefined;
}
export function validPassword(value: unknown): value is string {
if (typeof value !== 'string' || value.trim().length === 0) return false;
const length = Array.from(value).length;
return length >= 12 && length <= 128;
}
export function registrationPassword(value: unknown): string {
if (!validPassword(value))
return invalidRequest('Пароль должен содержать 12–128 Unicode-символов');
return value;
}
@Injectable()
export class PasswordService {
async hash(password: string): Promise<string> {
const salt = randomBytes(16);
const key = await this.deriveArgon(password, salt);
return `${argonPrefix}$${salt.toString('base64').replace(/=+$/, '')}$${key.toString('base64').replace(/=+$/, '')}`;
}
async verify(password: string, storedHash: string | null): Promise<boolean> {
const stored = argonHash(storedHash);
const key = await this.deriveArgon(
password,
stored?.salt ?? Buffer.alloc(16),
);
const matches = timingSafeEqual(key, stored?.key ?? Buffer.alloc(32));
return Boolean(stored && matches);
}
private deriveArgon(password: string, salt: Buffer): Promise<Buffer> {
return new Promise((resolve, reject) => {
argon2(
'argon2id',
{ ...argonParameters, message: password, nonce: salt },
(error, key) => {
if (error) reject(error);
else resolve(key);
},
);
});
}
}
+132
View File
@@ -0,0 +1,132 @@
import {
Body,
Controller,
Get,
Headers,
HttpCode,
HttpStatus,
Param,
Post,
Query,
Req,
UseGuards,
} from '@nestjs/common';
import {
ApiBody,
ApiBearerAuth,
ApiCreatedResponse,
ApiHeader,
ApiOkResponse,
ApiOperation,
ApiQuery,
ApiTags,
} from '@nestjs/swagger';
import { UserGuard, type AuthenticatedRequest } from '../User/user.guard';
import {
CreateChatDto,
CreateMessageDto,
Chat,
Message,
ChatPage,
MessagePage,
} from './chat.schema';
import { ChatService } from './chat.service';
@ApiTags('chats')
@ApiBearerAuth('bearerAuth')
@UseGuards(UserGuard)
@Controller('api/v1/chats')
export class ChatController {
constructor(private readonly chats: ChatService) {}
@Post()
@HttpCode(HttpStatus.CREATED)
@ApiBody({ type: CreateChatDto })
@ApiOperation({ operationId: 'createChat' })
@ApiCreatedResponse({ type: Chat })
create(@Req() request: AuthenticatedRequest, @Body() body: unknown) {
return this.chats.create(body, request.currentUser.id);
}
@Get()
@ApiOperation({ operationId: 'listChats' })
@ApiOkResponse({ type: ChatPage })
@ApiQuery({
name: 'limit',
required: false,
schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },
})
@ApiQuery({ name: 'cursor', required: false, type: String })
list(
@Req() request: AuthenticatedRequest,
@Query('limit') limit: unknown,
@Query('cursor') cursor: unknown,
) {
return this.chats.list(
request.currentUser.id,
limit,
cursor,
request.currentChatsEpoch,
);
}
@Get(':chat_id')
@ApiOperation({ operationId: 'getChat' })
@ApiOkResponse({ type: Chat })
get(@Req() request: AuthenticatedRequest, @Param('chat_id') chatId: string) {
return this.chats.get(chatId, request.currentUser.id);
}
@Post(':chat_id/messages')
@HttpCode(HttpStatus.CREATED)
@ApiBody({ type: CreateMessageDto })
@ApiHeader({
name: 'Idempotency-Key',
required: true,
schema: {
type: 'string',
minLength: 1,
maxLength: 128,
pattern: '^[A-Za-z0-9._:-]+$',
},
})
@ApiOperation({ operationId: 'createMessage' })
@ApiCreatedResponse({ type: Message })
createMessage(
@Req() request: AuthenticatedRequest,
@Param('chat_id') chatId: string,
@Headers('idempotency-key') idempotencyKey: unknown,
@Body() body: unknown,
) {
return this.chats.createMessage(
chatId,
body,
request.currentUser.id,
idempotencyKey,
);
}
@Get(':chat_id/messages')
@ApiOperation({ operationId: 'listMessages' })
@ApiOkResponse({ type: MessagePage })
@ApiQuery({
name: 'limit',
required: false,
schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },
})
@ApiQuery({ name: 'cursor', required: false, type: String })
listMessages(
@Req() request: AuthenticatedRequest,
@Param('chat_id') chatId: string,
@Query('limit') limit: unknown,
@Query('cursor') cursor: unknown,
) {
return this.chats.listMessages(
chatId,
request.currentUser.id,
limit,
cursor,
request.currentChatAccess,
);
}
}
+11
View File
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { UserModule } from '../User/user.module';
import { ChatController } from './chat.controller';
import { ChatService } from './chat.service';
@Module({
imports: [UserModule],
controllers: [ChatController],
providers: [ChatService],
})
export class ChatModule {}
+57
View File
@@ -0,0 +1,57 @@
import { ApiProperty } from '@nestjs/swagger';
export class CreateChatDto {
@ApiProperty({ example: 'Проект по ВНП', maxLength: 100 })
title!: string;
@ApiProperty({ type: [String], format: 'uuid' })
member_ids!: string[];
}
export class CreateMessageDto {
@ApiProperty({ example: 'Привет, Боб!', maxLength: 4000 })
text!: string;
}
export class Chat {
@ApiProperty({ format: 'uuid' })
id!: string;
@ApiProperty({ maxLength: 100 })
title!: string;
@ApiProperty({ type: [String], format: 'uuid' })
member_ids!: string[];
@ApiProperty({ format: 'date-time' })
created_at!: string;
}
export class Message {
@ApiProperty({ format: 'uuid' })
id!: string;
@ApiProperty({ format: 'uuid' })
chat_id!: string;
@ApiProperty({ format: 'uuid' })
sender_id!: string;
@ApiProperty({ maxLength: 4000 })
text!: string;
@ApiProperty({ format: 'date-time' })
created_at!: string;
}
export class ChatPage {
@ApiProperty({ type: [Chat] })
items!: Chat[];
@ApiProperty({ type: String, nullable: true })
next_cursor!: string | null;
}
export class MessagePage {
@ApiProperty({ type: [Message] })
items!: Message[];
@ApiProperty({ type: String, nullable: true })
next_cursor!: string | null;
}
export interface Page<T> {
items: T[];
next_cursor: string | null;
}
+399
View File
@@ -0,0 +1,399 @@
import { HttpStatus, Injectable } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import type { ChatAccess } from '../Auth/auth.service';
import {
Prisma,
type Message as StoredMessage,
} from '../generated/prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { ApiException } from '../common/exceptions/api.exception';
import {
invalidRequest,
objectBody,
pageLimit,
requiredText,
uuid,
} from '../common/validation';
import type { Chat, Message, Page } from './chat.schema';
import { CacheService, CACHE_TTL } from '../cache/cache.service';
interface Cursor {
scope: string;
created_at: string;
id: string;
}
const chatInclude = {
members: { orderBy: { position: 'asc' as const } },
} satisfies Prisma.ChatInclude;
type StoredChat = Prisma.ChatGetPayload<{ include: typeof chatInclude }>;
@Injectable()
export class ChatService {
private readonly idempotencyTtlSeconds: number;
constructor(
private readonly prisma: PrismaService,
private readonly cache: CacheService,
) {
this.idempotencyTtlSeconds = Number(
process.env.IDEMPOTENCY_TTL_SECONDS ?? 86400,
);
if (
!Number.isSafeInteger(this.idempotencyTtlSeconds) ||
this.idempotencyTtlSeconds < 86400 ||
Number.isNaN(
new Date(Date.now() + this.idempotencyTtlSeconds * 1000).getTime(),
)
) {
throw new Error('IDEMPOTENCY_TTL_SECONDS must be at least 86400');
}
}
async create(value: unknown, userId: string): Promise<Chat> {
const body = objectBody(value, ['title', 'member_ids']);
const title = requiredText(body.title, 'title', 100);
if (
!Array.isArray(body.member_ids) ||
body.member_ids.length < 1 ||
body.member_ids.length > 100
) {
return invalidRequest('Некорректный member_ids');
}
const memberIds = body.member_ids.map((id: unknown) =>
uuid(id, 'member_ids'),
);
if (
new Set(memberIds).size !== memberIds.length ||
!memberIds.includes(userId)
) {
return invalidRequest(
'Список участников содержит дубликат или не содержит вызывающего',
);
}
try {
const chat = await this.prisma.$transaction(async (tx) => {
const count = await tx.user.count({ where: { id: { in: memberIds } } });
if (count !== memberIds.length)
return invalidRequest('Неизвестный участник чата');
const created = await tx.chat.create({
data: {
title,
members: {
create: memberIds.map((userId, position) => ({
userId,
position,
})),
},
},
include: chatInclude,
});
await tx.$executeRaw(Prisma.sql`
WITH locked AS MATERIALIZED (
SELECT id FROM users
WHERE id IN (${Prisma.join(memberIds.map((id) => Prisma.sql`${id}::uuid`))})
ORDER BY id FOR UPDATE
)
UPDATE users AS u SET chats_epoch = u.chats_epoch + 1
FROM locked WHERE u.id = locked.id
`);
return created;
});
return this.serializeChat(chat);
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === 'P2003'
) {
return invalidRequest('Неизвестный участник чата');
}
throw error;
}
}
async list(
userId: string,
limitValue: unknown,
cursorValue: unknown,
epoch: string,
): Promise<Page<Chat>> {
const limit = pageLimit(limitValue);
const scope = `chats:${userId}`;
const cursor = this.decodeCursor(cursorValue, scope);
return this.cache.remember(
scope,
{ limit, cursor },
CACHE_TTL.page,
async () => {
const chats = await this.prisma.chat.findMany({
where: { members: { some: { userId } }, ...this.after(cursor) },
include: chatInclude,
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
take: limit + 1,
});
return this.page(
chats.map((chat) => this.serializeChat(chat)),
limit,
scope,
);
},
epoch,
);
}
async get(value: unknown, userId: string): Promise<Chat> {
const { id } = await this.authorizeChat(value, userId);
return this.getMetadata(id);
}
private async authorizeChat(value: unknown, userId: string) {
const id = uuid(value, 'chat_id');
const [membership] = await this.prisma.$queryRaw<
{ id: string; messagesEpoch: bigint }[]
>(Prisma.sql`
SELECT c.id, COALESCE((SELECT SUM(e.epoch) FROM "public"."chat_message_epochs" AS e WHERE e.chat_id = c.id), 0)::bigint AS "messagesEpoch"
FROM chat_members AS cm JOIN chats AS c ON c.id = cm.chat_id
WHERE cm.chat_id = ${id}::uuid AND cm.user_id = ${userId}::uuid
`);
if (!membership) {
throw new ApiException(
HttpStatus.NOT_FOUND,
'not_found',
'Объект не найден',
);
}
return membership;
}
private getMetadata(id: string): Promise<Chat> {
return this.cache.remember(
`chat:${id}`,
'metadata',
CACHE_TTL.entity,
async () => {
const chat = await this.prisma.chat.findUnique({
where: { id },
include: chatInclude,
});
if (!chat)
throw new ApiException(
HttpStatus.NOT_FOUND,
'not_found',
'Объект не найден',
);
return this.serializeChat(chat);
},
);
}
async createMessage(
chatId: unknown,
value: unknown,
userId: string,
keyValue: unknown,
): Promise<Message> {
const id = uuid(chatId, 'chat_id');
if (
typeof keyValue !== 'string' ||
!/^[A-Za-z0-9._:-]{1,128}$/.test(keyValue)
) {
return invalidRequest('Некорректный Idempotency-Key');
}
const body = objectBody(value, ['text']);
const text = requiredText(body.text, 'text', 4000);
await this.authorizeChat(id, userId);
return this.prisma.$transaction(async (tx) => {
await tx.$executeRaw(Prisma.sql`
DELETE FROM message_idempotency
WHERE user_id = ${userId}::uuid AND chat_id = ${id}::uuid
AND "key" = ${keyValue} AND expires_at <= NOW()
`);
const claimed = await tx.$queryRaw<{ key: string }[]>(Prisma.sql`
INSERT INTO message_idempotency (user_id, chat_id, "key", expires_at)
VALUES (
${userId}::uuid, ${id}::uuid, ${keyValue},
NOW() + (${this.idempotencyTtlSeconds} * INTERVAL '1 second')
)
ON CONFLICT (user_id, chat_id, "key") DO NOTHING
RETURNING "key"
`);
if (claimed.length === 0) {
const [existing] = await tx.$queryRaw<StoredMessage[]>(Prisma.sql`
SELECT m.id, m.chat_id AS "chatId", m.sender_id AS "senderId",
m.text, m.created_at AS "createdAt"
FROM message_idempotency AS i
JOIN messages AS m ON m.id = i.message_id
WHERE i.user_id = ${userId}::uuid AND i.chat_id = ${id}::uuid
AND i."key" = ${keyValue}
`);
if (!existing) throw new Error('Idempotency record has no message');
if (existing.text !== text) {
throw new ApiException(
HttpStatus.CONFLICT,
'conflict',
'Idempotency-Key уже использован с другим сообщением',
);
}
return this.serializeMessage(existing);
}
const messageId = randomUUID();
const bucket = parseInt(messageId.slice(0, 2), 16) % 16;
const [message] = await tx.$queryRaw<StoredMessage[]>(Prisma.sql`
WITH updated AS (
INSERT INTO "public"."chat_message_epochs" AS e (chat_id, bucket, epoch)
SELECT cm.chat_id, ${bucket}::smallint, 1 FROM chat_members AS cm
WHERE cm.chat_id = ${id}::uuid AND cm.user_id = ${userId}::uuid
ON CONFLICT (chat_id, bucket) DO UPDATE SET epoch = e.epoch + 1
RETURNING chat_id
)
INSERT INTO messages (id, chat_id, sender_id, text)
SELECT ${messageId}::uuid, updated.chat_id, ${userId}::uuid, ${text} FROM updated
RETURNING id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt"
`);
if (!message)
throw new ApiException(
HttpStatus.NOT_FOUND,
'not_found',
'Объект не найден',
);
await tx.$executeRaw(Prisma.sql`
UPDATE message_idempotency SET message_id = ${message.id}::uuid
WHERE user_id = ${userId}::uuid AND chat_id = ${id}::uuid
AND "key" = ${keyValue}
`);
return this.serializeMessage(message);
});
}
async listMessages(
chatId: unknown,
userId: string,
limitValue: unknown,
cursorValue: unknown,
access?: ChatAccess,
): Promise<Page<Message>> {
const id = uuid(chatId, 'chat_id');
const chat =
access?.chatId === id && access.userId === userId
? { id, messagesEpoch: access.messagesEpoch }
: await this.authorizeChat(id, userId);
const limit = pageLimit(limitValue);
const scope = `messages:${chat.id}`;
const cursor = this.decodeCursor(cursorValue, scope);
return this.cache.remember(
scope,
{ limit, cursor },
CACHE_TTL.page,
async () => {
const messages = cursor
? await this.prisma.$queryRaw<StoredMessage[]>(Prisma.sql`
SELECT id, chat_id AS "chatId", sender_id AS "senderId",
text, created_at AS "createdAt"
FROM "public"."messages"
WHERE chat_id = ${chat.id}::uuid
AND (created_at, id) >
(${new Date(cursor.created_at)}::timestamptz, ${cursor.id}::uuid)
ORDER BY created_at ASC, id ASC
LIMIT ${limit + 1}
`)
: await this.prisma.message.findMany({
where: { chatId: chat.id },
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
take: limit + 1,
});
return this.page(
messages.map((message) => this.serializeMessage(message)),
limit,
scope,
);
},
chat.messagesEpoch.toString(),
);
}
private after(cursor: Cursor | null) {
if (!cursor) return {};
const createdAt = new Date(cursor.created_at);
return {
OR: [
{ createdAt: { gt: createdAt } },
{ createdAt, id: { gt: cursor.id } },
],
};
}
private serializeChat(chat: StoredChat): Chat {
return {
id: chat.id,
title: chat.title,
member_ids: chat.members.map((member) => member.userId),
created_at: chat.createdAt.toISOString(),
};
}
private serializeMessage(message: StoredMessage): Message {
return {
id: message.id,
chat_id: message.chatId,
sender_id: message.senderId,
text: message.text,
created_at: message.createdAt.toISOString(),
};
}
private page<T extends { id: string; created_at: string }>(
items: T[],
limit: number,
scope: string,
): Page<T> {
const result = items.slice(0, limit);
const last = result.at(-1);
return {
items: result,
next_cursor:
items.length > limit && last
? Buffer.from(
JSON.stringify({
scope,
created_at: last.created_at,
id: last.id,
}),
).toString('base64url')
: null,
};
}
private decodeCursor(value: unknown, scope: string): Cursor | null {
if (value === undefined) return null;
if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value))
return invalidRequest('Некорректный cursor');
try {
const cursor: unknown = JSON.parse(
Buffer.from(value, 'base64url').toString('utf8'),
);
if (
typeof cursor !== 'object' ||
cursor === null ||
Array.isArray(cursor)
)
return invalidRequest('Некорректный cursor');
const data = cursor as Record<string, unknown>;
if (
data.scope !== scope ||
typeof data.created_at !== 'string' ||
Number.isNaN(Date.parse(data.created_at)) ||
typeof data.id !== 'string'
) {
return invalidRequest('Некорректный cursor');
}
return {
scope,
created_at: data.created_at,
id: uuid(data.id, 'cursor'),
};
} catch {
return invalidRequest('Некорректный cursor');
}
}
}
+45
View File
@@ -0,0 +1,45 @@
import {
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import {
ApiBody,
ApiBearerAuth,
ApiCreatedResponse,
ApiOkResponse,
ApiOperation,
ApiTags,
} from '@nestjs/swagger';
import { UserGuard, type AuthenticatedRequest } from './user.guard';
import { CreateUserDto, User } from './user.schema';
import { UserService } from './user.service';
@ApiTags('users')
@Controller('api/v1/users')
export class UserController {
constructor(private readonly users: UserService) {}
@Post()
@HttpCode(HttpStatus.CREATED)
@ApiBody({ type: CreateUserDto })
@ApiOperation({ operationId: 'registerUser' })
@ApiCreatedResponse({ type: User })
create(@Body() body: unknown) {
return this.users.create(body);
}
@Get('me')
@UseGuards(UserGuard)
@ApiBearerAuth('bearerAuth')
@ApiOperation({ operationId: 'currentUser' })
@ApiOkResponse({ type: User })
me(@Req() request: AuthenticatedRequest) {
return request.currentUser;
}
}
+34
View File
@@ -0,0 +1,34 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import type { FastifyRequest } from 'fastify';
import { AuthService, type ChatAccess } from '../Auth/auth.service';
import type { User } from './user.schema';
export type AuthenticatedRequest = FastifyRequest & {
currentUser: User;
currentSessionId: string;
currentChatsEpoch: string;
currentChatAccess?: ChatAccess;
};
@Injectable()
export class UserGuard implements CanActivate {
constructor(private readonly auth: AuthService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
const chatId =
request.method === 'GET' &&
request.routeOptions.url === '/api/v1/chats/:chat_id/messages'
? (request.params as { chat_id: string }).chat_id
: undefined;
const session = await this.auth.authenticate(
request.headers.authorization,
chatId,
);
request.currentUser = session.user;
request.currentSessionId = session.sessionId;
request.currentChatsEpoch = session.chatsEpoch;
request.currentChatAccess = session.chatAccess;
return true;
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserGuard } from './user.guard';
import { UserService } from './user.service';
import { AuthController } from '../Auth/auth.controller';
import { AuthService } from '../Auth/auth.service';
import { PasswordService } from '../Auth/password.service';
@Module({
controllers: [UserController, AuthController],
providers: [UserService, UserGuard, AuthService, PasswordService],
exports: [UserService, UserGuard, AuthService],
})
export class UserModule {}
+28
View File
@@ -0,0 +1,28 @@
import { ApiProperty } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({ example: 'alice', pattern: '^[a-z0-9_]{3,32}$' })
username!: string;
@ApiProperty({ example: 'Алиса', maxLength: 100 })
display_name!: string;
@ApiProperty({
writeOnly: true,
minLength: 12,
maxLength: 128,
example: 'Example-only-not-a-real-secret-123',
})
password!: string;
}
export class User {
@ApiProperty({ format: 'uuid' })
id!: string;
@ApiProperty({ pattern: '^[a-z0-9_]{3,32}$' })
username!: string;
@ApiProperty({ minLength: 1, maxLength: 100 })
display_name!: string;
@ApiProperty({ format: 'date-time' })
created_at!: string;
}
+77
View File
@@ -0,0 +1,77 @@
import { HttpStatus, Injectable } from '@nestjs/common';
import { Prisma, type User as StoredUser } from '../generated/prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { ApiException } from '../common/exceptions/api.exception';
import { objectBody, requiredText } from '../common/validation';
import {
PasswordService,
registrationPassword,
} from '../Auth/password.service';
import type { User } from './user.schema';
import { CacheService, CACHE_TTL } from '../cache/cache.service';
@Injectable()
export class UserService {
constructor(
private readonly prisma: PrismaService,
private readonly passwords: PasswordService,
private readonly cache: CacheService,
) {}
async create(value: unknown): Promise<User> {
const body = objectBody(value, ['username', 'display_name', 'password']);
const username = body.username;
if (typeof username !== 'string' || !/^[a-z0-9_]{3,32}$/.test(username)) {
throw new ApiException(
HttpStatus.BAD_REQUEST,
'invalid_request',
'Некорректный username',
);
}
const displayName = requiredText(body.display_name, 'display_name', 100);
const password = registrationPassword(body.password);
const passwordHash = await this.passwords.hash(password);
try {
return this.serialize(
await this.prisma.user.create({
data: { username, displayName, passwordHash },
}),
);
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === 'P2002'
) {
throw new ApiException(
HttpStatus.CONFLICT,
'conflict',
'Username уже занят',
);
}
throw error;
}
}
async get(id: string): Promise<User | undefined> {
return this.cache.remember(
`user:${id}`,
'profile',
CACHE_TTL.entity,
async () => {
const user = await this.prisma.user.findUnique({ where: { id } });
return user ? this.serialize(user) : undefined;
},
);
}
serialize(
user: Pick<StoredUser, 'id' | 'username' | 'displayName' | 'createdAt'>,
): User {
return {
id: user.id,
username: user.username,
display_name: user.displayName,
created_at: user.createdAt.toISOString(),
};
}
}
+38
View File
@@ -0,0 +1,38 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaService } from './prisma/prisma.service';
describe('AppController', () => {
let appController: AppController;
const queryRaw = jest.fn();
beforeEach(async () => {
queryRaw.mockReset();
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [
AppService,
{ provide: PrismaService, useValue: { $queryRaw: queryRaw } },
],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
it('reports ready when PostgreSQL is reachable', async () => {
queryRaw.mockResolvedValue([{ '?column?': 1 }]);
await expect(appController.ready()).resolves.toEqual({ status: 'ok' });
});
it('returns 503 when PostgreSQL is unavailable', async () => {
queryRaw.mockRejectedValue(new Error('connection refused'));
await expect(appController.ready()).rejects.toMatchObject({ status: 503 });
});
});
+52
View File
@@ -0,0 +1,52 @@
import { Controller, Get, HttpStatus } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { AppService } from './app.service';
import { PrismaService } from './prisma/prisma.service';
import { ApiException } from './common/exceptions/api.exception';
import { DrainingFastifyAdapter } from './common/http/fastify-adapter';
@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
private readonly prisma: PrismaService,
private readonly adapterHost: HttpAdapterHost,
) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
@Get('health/live')
live() {
return { status: 'ok' };
}
@Get('health/ready')
async ready() {
this.assertNotDraining();
try {
await this.prisma.$queryRaw`SELECT 1`;
} catch {
throw new ApiException(
HttpStatus.SERVICE_UNAVAILABLE,
'unavailable',
'База данных недоступна',
);
}
this.assertNotDraining();
return { status: 'ok' };
}
private assertNotDraining(): void {
const adapter = this.adapterHost.httpAdapter;
if (adapter instanceof DrainingFastifyAdapter && adapter.isDraining) {
throw new ApiException(
HttpStatus.SERVICE_UNAVAILABLE,
'unavailable',
'API завершает работу',
);
}
}
}
+58
View File
@@ -0,0 +1,58 @@
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { LoggerModule } from 'nestjs-pino';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { UserModule } from './User/user.module';
import { ChatModule } from './Chat/chat.module';
import { PrismaModule } from './prisma/prisma.module';
import { CacheModule } from './cache/cache.module';
@Module({
imports: [
PrismaModule,
CacheModule,
UserModule,
ChatModule,
LoggerModule.forRoot({
pinoHttp: {
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
transport:
process.env.NODE_ENV !== 'production'
? {
target: 'pino-pretty',
options: {
colorize: true,
singleLine: true,
translateTime: 'SYS:standard',
},
}
: undefined,
redact: {
paths: [
'req.headers.authorization',
'req.headers.cookie',
'res.headers.set-cookie',
],
censor: '[REDACTED]',
},
autoLogging: {
ignore: (request) => request.url === '/health',
},
},
}),
],
controllers: [AppController],
providers: [
AppService,
{
provide: APP_FILTER,
useClass: AllExceptionsFilter,
},
],
})
export class AppModule {}
+8
View File
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
+6
View File
@@ -0,0 +1,6 @@
import { Global, Module } from '@nestjs/common';
import { CacheService } from './cache.service';
@Global()
@Module({ providers: [CacheService], exports: [CacheService] })
export class CacheModule {}
+149
View File
@@ -0,0 +1,149 @@
import {
Injectable,
Logger,
type OnModuleDestroy,
type OnModuleInit,
} from '@nestjs/common';
import { createHash, randomUUID } from 'node:crypto';
import Redis from 'ioredis';
export const CACHE_TTL = { entity: 300, page: 30 } as const;
const generationTtl = 600;
const storeIfCurrent = `
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('SET', KEYS[2], ARGV[2], 'EX', ARGV[3])
end
return false`;
@Injectable()
export class CacheService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(CacheService.name);
private readonly redis?: Redis;
private readonly prefix = process.env.CACHE_PREFIX ?? 'messenger:cache:v1';
private warned = false;
constructor() {
if (process.env.CACHE_URL) {
this.redis = new Redis(process.env.CACHE_URL, {
lazyConnect: true,
connectTimeout: 1000,
commandTimeout: 300,
maxRetriesPerRequest: 0,
enableOfflineQueue: false,
autoResendUnfulfilledCommands: false,
retryStrategy: () => 1000,
});
this.redis.on('error', () => this.unavailable());
this.redis.on('ready', () => {
this.warned = false;
});
}
}
async onModuleInit(): Promise<void> {
try {
await this.redis?.connect();
} catch {
this.unavailable();
}
}
onModuleDestroy(): void {
this.redis?.disconnect();
}
async remember<T>(
namespace: string,
parameters: unknown,
ttl: number,
load: () => Promise<T>,
epoch?: string,
): Promise<T> {
if (!this.redis || this.redis.status !== 'ready') return load();
if (epoch !== undefined) {
const digest = createHash('sha256')
.update(JSON.stringify(parameters))
.digest('hex');
const key = `${this.prefix}:${namespace}:epoch:${epoch}:${digest}`;
try {
const value = await this.redis.get(key);
if (value !== null) return JSON.parse(value) as T;
} catch {
this.unavailable();
}
const result = await load();
const serialized = JSON.stringify(result);
if (serialized !== undefined && this.redis.status === 'ready') {
try {
await this.redis.set(key, serialized, 'EX', ttl);
} catch {
this.unavailable();
}
}
return result;
}
const versionKey = `${this.prefix}:${namespace}:generation`;
let version: string | null = null;
let dataKey = '';
try {
await this.redis.set(versionKey, randomUUID(), 'EX', generationTtl, 'NX');
version = await this.redis.get(versionKey);
if (version) {
const digest = createHash('sha256')
.update(JSON.stringify(parameters))
.digest('hex');
dataKey = `${this.prefix}:${namespace}:${version}:${digest}`;
const value = await this.redis.get(dataKey);
if (value !== null) return JSON.parse(value) as T;
}
} catch {
this.unavailable();
}
const result = await load();
const serialized = JSON.stringify(result);
if (version && serialized !== undefined && this.redis.status === 'ready') {
try {
await this.redis.eval(
storeIfCurrent,
2,
versionKey,
dataKey,
version,
serialized,
ttl,
);
} catch {
this.unavailable();
}
}
return result;
}
async invalidate(...namespaces: string[]): Promise<void> {
if (!this.redis || this.redis.status !== 'ready' || namespaces.length === 0)
return;
try {
const transaction = this.redis.multi();
for (const namespace of new Set(namespaces)) {
transaction.set(
`${this.prefix}:${namespace}:generation`,
randomUUID(),
'EX',
generationTtl,
);
}
const results = await transaction.exec();
if (results?.some(([error]) => error !== null)) this.unavailable();
} catch {
this.unavailable();
}
}
private unavailable(): void {
if (!this.warned) {
this.logger.warn('Redis cache unavailable');
this.warned = true;
}
}
}
+16
View File
@@ -0,0 +1,16 @@
import {
HttpException,
HttpExceptionOptions,
HttpStatus,
} from '@nestjs/common';
export class ApiException extends HttpException {
constructor(
status: HttpStatus,
code: string,
message: string,
options?: HttpExceptionOptions,
) {
super({ code, message }, status, options);
}
}
+177
View File
@@ -0,0 +1,177 @@
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
} from '@nestjs/common';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { Prisma } from '../../generated/prisma/client';
import { ApiException } from '../exceptions/api.exception';
import { AuthException } from '../../Auth/auth.exception';
interface ExceptionPayload {
code?: unknown;
}
const defaultCodes: Partial<Record<HttpStatus, string>> = {
[HttpStatus.BAD_REQUEST]: 'invalid_request',
[HttpStatus.UNAUTHORIZED]: 'unauthorized',
[HttpStatus.FORBIDDEN]: 'forbidden',
[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',
};
const defaultMessages: Partial<Record<HttpStatus, string>> = {
[HttpStatus.BAD_REQUEST]: 'Некорректный запрос',
[HttpStatus.UNAUTHORIZED]: 'Требуется авторизация',
[HttpStatus.FORBIDDEN]: 'Доступ запрещён',
[HttpStatus.NOT_FOUND]: 'Ресурс не найден',
[HttpStatus.METHOD_NOT_ALLOWED]: 'Метод не поддерживается',
[HttpStatus.CONFLICT]: 'Конфликт данных',
[HttpStatus.PAYLOAD_TOO_LARGE]: 'Тело запроса слишком большое',
[HttpStatus.UNSUPPORTED_MEDIA_TYPE]: 'Неподдерживаемый формат данных',
[HttpStatus.TOO_MANY_REQUESTS]: 'Слишком много запросов',
[HttpStatus.INTERNAL_SERVER_ERROR]: 'Внутренняя ошибка сервера',
[HttpStatus.SERVICE_UNAVAILABLE]: 'Сервис временно недоступен',
};
const databaseUnavailableCodes = new Set([
'P1000',
'P1001',
'P1002',
'P1008',
'P1017',
'P2024',
'P2037',
'ECONNREFUSED',
'ECONNRESET',
'ETIMEDOUT',
'EPIPE',
'ENOTFOUND',
'EAI_AGAIN',
'EACCES',
'08000',
'08001',
'08003',
'08004',
'08006',
'53300',
'57P01',
'57P02',
'57P03',
'57014',
]);
const driverTimeoutMessages = [
'Query read timeout',
'timeout exceeded when trying to connect',
'Connection terminated unexpectedly',
'Connection terminated due to connection timeout',
];
function databaseUnavailable(exception: unknown): boolean {
if (exception instanceof Prisma.PrismaClientInitializationError) return true;
if (exception instanceof HttpException || !(exception instanceof Error))
return false;
const error = exception as Error & { code?: unknown };
if (
typeof error.code === 'string' &&
databaseUnavailableCodes.has(error.code)
)
return true;
if (exception instanceof Prisma.PrismaClientKnownRequestError) {
const originalCode = exception.meta?.code;
if (
typeof originalCode === 'string' &&
databaseUnavailableCodes.has(originalCode)
)
return true;
const adapter = exception.meta?.driverAdapterError;
if (adapter !== null && typeof adapter === 'object' && 'cause' in adapter) {
const cause = adapter.cause;
if (cause !== null && typeof cause === 'object') {
if ('kind' in cause && cause.kind === 'ConnectionClosed') return true;
if (
'originalCode' in cause &&
typeof cause.originalCode === 'string' &&
databaseUnavailableCodes.has(cause.originalCode)
)
return true;
}
}
}
return driverTimeoutMessages.some((message) =>
exception.message.includes(message),
);
}
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost): void {
if (databaseUnavailable(exception)) {
exception = new ApiException(
HttpStatus.SERVICE_UNAVAILABLE,
'unavailable',
'База данных недоступна',
);
}
const context = host.switchToHttp();
const request = context.getRequest<FastifyRequest>();
const response = context.getResponse<FastifyReply>();
if (exception instanceof AuthException) {
void response.header('WWW-Authenticate', exception.challenge);
}
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const payload =
exception instanceof HttpException ? exception.getResponse() : undefined;
const { code, message } = this.extractError(status, payload);
const requestId = request.id;
if (status >= HttpStatus.INTERNAL_SERVER_ERROR) {
request.raw.log?.error(
{ err: exception, status, requestId },
'Request failed',
);
}
void response.status(status).send({
error: { code, message, request_id: requestId },
});
}
private extractError(
status: HttpStatus,
payload: string | object | undefined,
): { code: string; message: string } {
if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
return {
code: 'internal_error',
message: defaultMessages[status] ?? 'Ошибка сервера',
};
}
const body = (
payload !== null && typeof payload === 'object' ? payload : {}
) as ExceptionPayload;
return {
code:
typeof body.code === 'string'
? body.code
: (defaultCodes[status] ?? 'http_error'),
message:
defaultMessages[status] ??
(status >= HttpStatus.INTERNAL_SERVER_ERROR
? 'Ошибка сервера'
: 'Ошибка запроса'),
};
}
}
+66
View File
@@ -0,0 +1,66 @@
import { randomUUID } from 'node:crypto';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
const requestIdHeader = 'x-request-id';
const instanceIdHeader = 'x-instance-id';
const instanceId = process.env.INSTANCE_ID?.trim() || randomUUID();
// Two parallel readiness rounds: 2 * (1s request timeout + 2s interval),
// plus one second for the upstream reload. Keep below the public hook's 10s limit.
export const DRAIN_DELAY_MS = 7000;
export class DrainingFastifyAdapter extends FastifyAdapter {
private draining = false;
private closing?: Promise<void>;
private httpClosing?: Promise<undefined>;
constructor(private readonly drainDelayMs: number) {
super({ requestIdHeader, genReqId: () => randomUUID() });
this.getInstance().addHook('onSend', (_request, reply, payload, done) => {
// An already active request may finish after Fastify starts closing.
// Finish its response, then close its keep-alive socket as well.
if (this.httpClosing) void reply.header('connection', 'close');
done(null, payload);
});
}
get isDraining(): boolean {
return this.draining;
}
override beforeClose(): Promise<void> {
return (this.closing ??= this.drainAndClose());
}
override close(): Promise<undefined> {
return (this.httpClosing ??= super.close());
}
private async drainAndClose(): Promise<void> {
this.draining = true;
if (this.drainDelayMs > 0) {
await new Promise<void>((resolve) => setTimeout(resolve, this.drainDelayMs));
}
// Nest awaits beforeClose before destroying Prisma/Redis providers.
// Fastify first stops new connections and finishes active HTTP requests.
await this.close();
}
}
export function createFastifyAdapter(drainDelayMs = 0): DrainingFastifyAdapter {
return new DrainingFastifyAdapter(drainDelayMs);
}
export function exposeRequestIdHeader(app: NestFastifyApplication): void {
app
.getHttpAdapter()
.getInstance()
.addHook('onRequest', (request, reply, done) => {
void reply.header(requestIdHeader, request.id);
void reply.header(instanceIdHeader, instanceId);
done();
});
}
+54
View File
@@ -0,0 +1,54 @@
import { ApiException } from './exceptions/api.exception';
import { HttpStatus } from '@nestjs/common';
export const uuidPattern =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function invalidRequest(message: string): never {
throw new ApiException(HttpStatus.BAD_REQUEST, 'invalid_request', message);
}
export function objectBody(
value: unknown,
keys: string[],
): Record<string, unknown> {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
return invalidRequest('Ожидается JSON-объект');
}
const body = value as Record<string, unknown>;
if (Object.keys(body).some((key) => !keys.includes(key))) {
return invalidRequest('Неизвестное поле запроса');
}
return body;
}
export function requiredText(
value: unknown,
field: string,
max: number,
): string {
if (typeof value !== 'string' || value.trim().length === 0) {
return invalidRequest(`Некорректное поле ${field}`);
}
let codePoints = 0;
for (const _character of value) codePoints++;
if (codePoints > max) return invalidRequest(`Некорректное поле ${field}`);
return value;
}
export function uuid(value: unknown, field: string): string {
if (typeof value !== 'string' || !uuidPattern.test(value)) {
return invalidRequest(`Некорректное поле ${field}`);
}
return value.toLowerCase();
}
export function pageLimit(value: unknown): number {
if (value === undefined) return 50;
if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) {
return invalidRequest('Некорректный limit');
}
const limit = Number(value);
if (limit > 100) return invalidRequest('Некорректный limit');
return limit;
}
+56
View File
@@ -0,0 +1,56 @@
import { NestFactory } from '@nestjs/core';
import { NestFastifyApplication } from '@nestjs/platform-fastify';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { apiReference } from '@scalar/nestjs-api-reference';
import { AppModule } from './app.module';
import { Logger } from 'nestjs-pino';
import {
createFastifyAdapter,
DRAIN_DELAY_MS,
exposeRequestIdHeader,
} from './common/http/fastify-adapter';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
createFastifyAdapter(DRAIN_DELAY_MS),
{
bufferLogs: true,
},
);
exposeRequestIdHeader(app);
app.useLogger(app.get(Logger));
app.enableShutdownHooks();
const swaggerConfig = new DocumentBuilder()
.setTitle('Messenger API')
.setDescription('Документация API')
.setVersion('1.3.0')
.addBasicAuth({ type: 'http', scheme: 'basic' }, 'basicAuth')
.addBearerAuth(
{ type: 'http', scheme: 'bearer', bearerFormat: 'opaque' },
'bearerAuth',
)
.build();
const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('swagger', app, document);
app.use(
'/docs',
apiReference({
content: document,
theme: 'laserwave',
withFastify: true,
}),
);
await app.listen(
Number(process.env.APP_PORT ?? process.env.PORT ?? 8080),
process.env.APP_HOST ?? '0.0.0.0',
);
}
void bootstrap();
+6
View File
@@ -0,0 +1,6 @@
import { Global, Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';
@Global()
@Module({ providers: [PrismaService], exports: [PrismaService] })
export class PrismaModule {}
+42
View File
@@ -0,0 +1,42 @@
import 'dotenv/config';
import {
Injectable,
type OnModuleDestroy,
type OnModuleInit,
} from '@nestjs/common';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../generated/prisma/client';
@Injectable()
export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
constructor() {
const connectionString = process.env.DATABASE_URL;
if (!connectionString) throw new Error('DATABASE_URL is required');
const poolMax = Number(process.env.DB_POOL_MAX ?? 15);
if (!Number.isSafeInteger(poolMax) || poolMax < 1) {
throw new Error('DB_POOL_MAX must be a positive integer');
}
super({
adapter: new PrismaPg({
connectionString,
max: poolMax,
connectionTimeoutMillis: 5000,
query_timeout: 5000,
idleTimeoutMillis: 30000,
options: '-c statement_timeout=5000',
}),
transactionOptions: { maxWait: 5000, timeout: 10000 },
});
}
async onModuleInit(): Promise<void> {
await this.$connect();
}
async onModuleDestroy(): Promise<void> {
await this.$disconnect();
}
}