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:
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user